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: Python framework for SOAP web services I need an advice. What python framework I can use to develop a SOAP web service? I know about SOAPpy and ZSI but that libraries aren't under active development. Is there something better? Thanks. A: I've used SOAPpy before and wouldn't recommend it unless you need to highly...
Python framework for SOAP web services
I need an advice. What python framework I can use to develop a SOAP web service? I know about SOAPpy and ZSI but that libraries aren't under active development. Is there something better? Thanks.
[ "I've used SOAPpy before and wouldn't recommend it unless you need to highly customize your web service to get it to interface with other non-standard SOAP implementations.\nI haven't used ZSI, but I understand that they tried to incorporate some of SOAPpy's features into ZSI.\nYou might try looking at soaplib for ...
[ 1, 0, 0 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0003195437_python_soap.txt
Q: Find n greatest numbers in a sparse matrix I am using sparse matrices as a mean of compressing data, with loss of course, what I do is I create a sparse dictionary from all the values greater than a specified treshold. I'd want my compressed data size to be a variable which my user can choose. My problem is, I hav...
Find n greatest numbers in a sparse matrix
I am using sparse matrices as a mean of compressing data, with loss of course, what I do is I create a sparse dictionary from all the values greater than a specified treshold. I'd want my compressed data size to be a variable which my user can choose. My problem is, I have a sparse matrix with alot of near-zero values,...
[ "scipy.stats.scoreatpercentile(arr,per) returns the value at a given percentile:\nimport scipy.stats as ss\nprint(ss.scoreatpercentile([1, 4, 2, 3], 75))\n# 3.25\n\nThe value is interpolated if the desired percentile lies between two points in arr.\nSo if you set per=(len(smat)-n)/len(smat) then \nthreshold = ss.sc...
[ 2 ]
[]
[]
[ "numpy", "python", "sparse_matrix" ]
stackoverflow_0003195781_numpy_python_sparse_matrix.txt
Q: Need help sorting list of objects by key I am unable to get this code to sort a list of objects using either .sort() or sorted(). What am I missing here? P.S. My solution.distance() method could use some cosmetic surgery too if anyone has any suggestions. Thanks! import random import math POPULATION_SIZE = 100...
Need help sorting list of objects by key
I am unable to get this code to sort a list of objects using either .sort() or sorted(). What am I missing here? P.S. My solution.distance() method could use some cosmetic surgery too if anyone has any suggestions. Thanks! import random import math POPULATION_SIZE = 100 data = [[1, 565.0, 575.0], [2, 25.0,...
[ "Change \nkey=lambda solution: solution.distance\n\nto\nkey=lambda solution: solution.distance()\n\n(The parentheses are needed to call the function.)\nAlternatively, you could make the distance method a property:\n @property\n def distance(self): \n ....\n\nIn this case, change all occurances of solution.di...
[ 3, 1, 1 ]
[]
[]
[ "genetic_algorithm", "key", "list", "python", "sorting" ]
stackoverflow_0003196112_genetic_algorithm_key_list_python_sorting.txt
Q: Using subprocess to find out when a process ends I wish to sequentially run some c scripts that fork their own processes (in a new command line window) and give the "Press any key to continue..." when they are completed. Technically, it is a special compiler. It pops up with acommand line window and tells me whe...
Using subprocess to find out when a process ends
I wish to sequentially run some c scripts that fork their own processes (in a new command line window) and give the "Press any key to continue..." when they are completed. Technically, it is a special compiler. It pops up with acommand line window and tells me whether the compile was successful or not. But that comm...
[ "You can use subprocess.poll to check the status without blocking, and subprocess.communicate to send information to the subprocess. \n" ]
[ 2 ]
[]
[]
[ "build_automation", "fork", "process", "python", "windows" ]
stackoverflow_0003196546_build_automation_fork_process_python_windows.txt
Q: Can you pass multiple paths to the Django runserver --pythonpath directive? For each of my projects I create an apps directory that holds all the apps I need. Satchmo also has an apps directory. Can I do something like python manage.py runserver --pythonpath=/path/to/my/apps /path/to/satchmo/apps? Is there some se...
Can you pass multiple paths to the Django runserver --pythonpath directive?
For each of my projects I create an apps directory that holds all the apps I need. Satchmo also has an apps directory. Can I do something like python manage.py runserver --pythonpath=/path/to/my/apps /path/to/satchmo/apps? Is there some separator that it can take?
[ "There's no --pythonpath option to runserver. You either want to add it to your .bashrc file or in your settings.py file add something like the following at the top:\nimport os,sys\nPROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))\nsys.path.append(PROJECT_ROOT, 'to', 'my', 'apps')\nsys.path.append(os.pat...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003196510_django_python.txt
Q: How do I get my Python date in the format that I want? I'm reading a date from an Excel cell in Python (using .Value on the cell)... the result that I get is: 07/06/10 00:00:00 I thought this was a string, and so went about trying to figure out how to convert this to the format I need ("yyyyMMdd", or "20100706" i...
How do I get my Python date in the format that I want?
I'm reading a date from an Excel cell in Python (using .Value on the cell)... the result that I get is: 07/06/10 00:00:00 I thought this was a string, and so went about trying to figure out how to convert this to the format I need ("yyyyMMdd", or "20100706" in this example). However, after some playing around I realiz...
[ "You can convert it to a time object like this:\nimport time\ntime.strptime(str(thetime), '%m/%d/%y %H:%M:%S')\n\nAnd then you should be able to manipulate it to your hearts content.\nHTH\n", "Have you tried str(time)? That should give it to you in a string and then you can play around with the formatting all you...
[ 4, 2 ]
[]
[]
[ "date_formatting", "date_parsing", "python", "time" ]
stackoverflow_0003196592_date_formatting_date_parsing_python_time.txt
Q: Regular expression not matching what I think it should In python, I'm compiling a regular expression pattern like so: rule_remark_pattern = re.compile('access-list shc-[(in)(out)] [(remark)(extended)].*') I would expect it to match any of the following lines: access-list shc-in remark C883101 Permit http from UPH...
Regular expression not matching what I think it should
In python, I'm compiling a regular expression pattern like so: rule_remark_pattern = re.compile('access-list shc-[(in)(out)] [(remark)(extended)].*') I would expect it to match any of the following lines: access-list shc-in remark C883101 Permit http from UPHC outside to Printers inside access-list shc-in extended per...
[ "My regex-fu is not Python-based, but assuming it is anything like standard, I think you are misunderstanding the use of '[' and ']'. They represent a character class and it seems like you need an alternation.\nTry replacing your \"[(word1)(word2)]\" constructs with \"(word1|word2)\".\nEDIT: Just checked the Python...
[ 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003197013_python_regex.txt
Q: Dilemma: Should I learn Seaside or a Python framework? I know it's kinda subjective but, if you were to put yourself in my shoes which would you invest the time in learning? I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb eac...
Dilemma: Should I learn Seaside or a Python framework?
I know it's kinda subjective but, if you were to put yourself in my shoes which would you invest the time in learning? I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone num...
[ "Forget about mod_python, there is WSGI. \nI'd recommend Django. It runs on any WSGI server, there are a lot to choose from. There is mod_wsgi for Apache, wsgiref - reference implementation included in Python and many more. Also Google App Engine is WSGI, and includes Django.\nDjango is very popular and it's commun...
[ 10, 10, 8, 6, 5, 4, 3, 1, 1 ]
[]
[]
[ "frameworks", "python", "seaside" ]
stackoverflow_0000697866_frameworks_python_seaside.txt
Q: python - refresh with webbrowser module I need a code portion to refresh the current page. I get the controller object from webbrowser module and start my webpage. And at a certain point I want to refresh my page inside the python code. According to the documentation at http://docs.python.org/library/webbrowser.ht...
python - refresh with webbrowser module
I need a code portion to refresh the current page. I get the controller object from webbrowser module and start my webpage. And at a certain point I want to refresh my page inside the python code. According to the documentation at http://docs.python.org/library/webbrowser.html, when I call the open() function of the co...
[ "I think there is no portable way to do such refresh. The codes for \"new\" are just hints and they aren't guaranteed. If you can, you could add a refresh into your webpage, but I don't know if you have access to the webpage you're accessing, but you can create a \"webpage wrapper\" which opens the page you want as...
[ 0 ]
[]
[]
[ "browser", "python", "refresh" ]
stackoverflow_0003195815_browser_python_refresh.txt
Q: Twisted Web Proxy Help! I wrote a Twisted Python HTTP proxy, and keep getting the following Traceback after navigating to a page through the proxy. Traceback (most recent call last): File "C:\ZBrownTechnology\Web Lock\Proxy.py", line 57, in <module> reactor.run() File "C:\Python26\lib\site-packages\twisted...
Twisted Web Proxy Help!
I wrote a Twisted Python HTTP proxy, and keep getting the following Traceback after navigating to a page through the proxy. Traceback (most recent call last): File "C:\ZBrownTechnology\Web Lock\Proxy.py", line 57, in <module> reactor.run() File "C:\Python26\lib\site-packages\twisted\internet\base.py", line 1165...
[ "This is a known bug in twisted.web.proxy. It's typically harmless. If it's causing problems for you, please consider contributing a patch to fix it!\n" ]
[ 3 ]
[]
[]
[ "proxy", "python", "traceback", "twisted" ]
stackoverflow_0003196528_proxy_python_traceback_twisted.txt
Q: Python authentication I want to be able to authenticate to a website and then access some of the private pages in that site. I've looked at some examples and tutorials but I can't get it to work. For example, I want to access https://www.billmonk.com/home which is available only after authentication. Here's the co...
Python authentication
I want to be able to authenticate to a website and then access some of the private pages in that site. I've looked at some examples and tutorials but I can't get it to work. For example, I want to access https://www.billmonk.com/home which is available only after authentication. Here's the code I'm using: url = 'https:...
[ "Looking at the source of the BillMonk page, it looks like the login action is a POST to /sign_in (not /home as your code uses).\n" ]
[ 1 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0003197171_authentication_python.txt
Q: How to use list comprehension to add an element to copies of a dictionary? given: template = {'a': 'b', 'c': 'd'} add = ['e', 'f'] k = 'z' I want to use list comprehension to generate [{'a': 'b', 'c': 'd', 'z': 'e'}, {'a': 'b', 'c': 'd', 'z': 'f'}] I know I can do this: out = [] for v in add: t = template.cop...
How to use list comprehension to add an element to copies of a dictionary?
given: template = {'a': 'b', 'c': 'd'} add = ['e', 'f'] k = 'z' I want to use list comprehension to generate [{'a': 'b', 'c': 'd', 'z': 'e'}, {'a': 'b', 'c': 'd', 'z': 'f'}] I know I can do this: out = [] for v in add: t = template.copy() t[k] = v out.append(t) but it is a little verbose and has no advantage ...
[ "[dict(template,z=value) for value in add]\n\nor (to use k):\n[dict(template,**{k:value}) for value in add]\n\n" ]
[ 31 ]
[]
[]
[ "dictionary", "list_comprehension", "python" ]
stackoverflow_0003197342_dictionary_list_comprehension_python.txt
Q: Integrity Error in Sqlite Database I am trying to import large amounts of data into a sqlite DB through python 2.5. The data consists of strings, but there are multiple duplicates in the data. An example; addres,type_code, location 123,01,work 123,01,mall 132,49,home 132,33,home My issue is that when loading th...
Integrity Error in Sqlite Database
I am trying to import large amounts of data into a sqlite DB through python 2.5. The data consists of strings, but there are multiple duplicates in the data. An example; addres,type_code, location 123,01,work 123,01,mall 132,49,home 132,33,home My issue is that when loading the data I get an Integrity error, address...
[ "your table probably has primary key set as addres + typ_code. If those three fields are indeed should be unique in that particular table then redefine primary key to include all three fields addres, type_code and location. That would fix the problem you facing.\n" ]
[ 3 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0003197578_python_sqlite.txt
Q: django views urllib2.py https error twilio api I'm looking to send an SMS with the Twilio api, but I'm getting the following error: "unknown url type: https" I've recompiled python with Openssl, so my code runs fine from the python interpretor, but whenever I try to run it in one of my django views I get this erro...
django views urllib2.py https error twilio api
I'm looking to send an SMS with the Twilio api, but I'm getting the following error: "unknown url type: https" I've recompiled python with Openssl, so my code runs fine from the python interpretor, but whenever I try to run it in one of my django views I get this error. Here is my code from my view: def send_sms(reques...
[ "Looks like it was just user error. My wsgi file was using a different interpreter but the paths were so similar I was just over looking it. Once I fixed that django was using the python version that I compiled with openssl and everything worked fine.\nAlways check if the tv is plugged in before you take it apart. ...
[ 1 ]
[]
[]
[ "django", "https", "python", "twilio", "urllib2" ]
stackoverflow_0003169589_django_https_python_twilio_urllib2.txt
Q: Regular expression to search for a string1 that is never followed by string2 How to construct a regular expression search pattern to find string1 that is not followed by string2 (immediately or not)? For for instance, if string1="MAN" and string2="PN", example search results would be: "M": Not found "MA": Not foun...
Regular expression to search for a string1 that is never followed by string2
How to construct a regular expression search pattern to find string1 that is not followed by string2 (immediately or not)? For for instance, if string1="MAN" and string2="PN", example search results would be: "M": Not found "MA": Not found "MAN": Found "BLAH_MAN_BLEH": Found "MAN_PN": Not found "BLAH_MAN_BLEH_PN": Not ...
[ "It looks like you can use MAN(?!.*PN). This matches MAN and uses negative lookahead to make sure that it's not followed by PN (as seen on rubular.com).\nGiven MAN_PN_MAN_BLEH, the above pattern will find the second MAN, since it's not followed by PN. If you want to validate the entire string and make sure that the...
[ 3 ]
[]
[]
[ "expression", "python", "regex" ]
stackoverflow_0003197765_expression_python_regex.txt
Q: Return an image to the browser in python, cgi-bin I'm trying to set up a python script in cgi-bin that simply returns a header with content-type: image/png and returns the image. I've tried opening the image and returning it with print f.read() but that isn't working. EDIT: the code I'm trying to use is: print "C...
Return an image to the browser in python, cgi-bin
I'm trying to set up a python script in cgi-bin that simply returns a header with content-type: image/png and returns the image. I've tried opening the image and returning it with print f.read() but that isn't working. EDIT: the code I'm trying to use is: print "Content-type: image/png\n\n" with open("/home/user/tmp/i...
[ "\nYou may need to open the file as \"rb\" (in windows based environments it's usually the case.\nSimply printing may not work (as it adds '\\n' and stuff), better just write it to sys.stdout.\nThe statement print \"Content-type: image/png\\n\\n\" actually prints 3 newlines (as print automatically adds one \"\\n\" ...
[ 7, 0 ]
[]
[]
[ "apache2", "cgi_bin", "image", "python" ]
stackoverflow_0003198093_apache2_cgi_bin_image_python.txt
Q: does google-app-engine has "required_admin" method @required_admin def get(self): I want to use this method to make user must be admin. A: The standard route is to use login: admin in your app.yaml, but here's a decorator: def admin_required(handler_method): def check_admin(self, *args): if not users.is_c...
does google-app-engine has "required_admin" method
@required_admin def get(self): I want to use this method to make user must be admin.
[ "The standard route is to use login: admin in your app.yaml, but here's a decorator:\ndef admin_required(handler_method):\n def check_admin(self, *args):\n if not users.is_current_user_admin():\n self.redirect(users.create_login_url(self.request.uri))\n return\n else:\n handler_method(self, *a...
[ 4 ]
[]
[]
[ "admin", "google_app_engine", "python", "require" ]
stackoverflow_0003197894_admin_google_app_engine_python_require.txt
Q: How can I explode a tuple so that it can be passed as a parameter list? Let's say I have a method definition like this: def myMethod(a, b, c, d, e) Then, I have a variable and a tuple like this: myVariable = 1 myTuple = (2, 3, 4, 5) Is there a way I can pass explode the tuple so that I can pass its members as pa...
How can I explode a tuple so that it can be passed as a parameter list?
Let's say I have a method definition like this: def myMethod(a, b, c, d, e) Then, I have a variable and a tuple like this: myVariable = 1 myTuple = (2, 3, 4, 5) Is there a way I can pass explode the tuple so that I can pass its members as parameters? Something like this (although I know this won't work as the entire ...
[ "You are looking for the argument unpacking operator *:\nmyMethod(myVariable, *myTuple)\n\n", "From the Python documentation:\n\nThe reverse situation occurs when the\n arguments are already in a list or\n tuple but need to be unpacked for a\n function call requiring separate\n positional arguments. For insta...
[ 44, 7 ]
[]
[]
[ "iterable_unpacking", "parameters", "python", "tuples" ]
stackoverflow_0003198218_iterable_unpacking_parameters_python_tuples.txt
Q: Python socket server craps out after receiving data I'm currently dabbling in sockets. I've got a jquery script that uses a very small flash swf file to establish a true socket connection. As a server I'd like to use python. Everything works, but I can only send information to the server just once. I've tried 2 pi...
Python socket server craps out after receiving data
I'm currently dabbling in sockets. I've got a jquery script that uses a very small flash swf file to establish a true socket connection. As a server I'd like to use python. Everything works, but I can only send information to the server just once. I've tried 2 pieces of python code for the server. I guess since they bo...
[ "I think you need to 'listen' again after you close the connection.\nAlso, Sockets deliver data as per the tcp specifications. You're not guaranteed to get all of any data sent in one socket read. I see nothing to perform multiple reads and assemble a complete 'message'\n", "For communicating between flash and py...
[ 2, 1 ]
[]
[]
[ "flash", "javascript", "python", "sockets" ]
stackoverflow_0003198050_flash_javascript_python_sockets.txt
Q: Adding methods to a simple RPC server in a clean and separated way I created a simple RPC server to perform certain tasks common to our teams, but which are called from different networks. The server looks like this (I don't include error handling for brevity): from twisted.internet.protocol import Protocol, Facto...
Adding methods to a simple RPC server in a clean and separated way
I created a simple RPC server to perform certain tasks common to our teams, but which are called from different networks. The server looks like this (I don't include error handling for brevity): from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor import json class MyProtocol(Pr...
[ "A bit of a largish order ;) but here's some initial steps for you (very heavily mocked-up, twisted specifics ommited in the examples):\n# your twisted imports...\nimport json\n\nclass MyProtocol(object): # Would be Protocol instead of object in real code\n\n def dataReceived(self, data):\n req = json.loa...
[ 1 ]
[]
[]
[ "architecture", "json_rpc", "network_protocols", "python", "twisted" ]
stackoverflow_0003197988_architecture_json_rpc_network_protocols_python_twisted.txt
Q: pylons file uploading - access 1st file Currently, I'm using request.params["filename"] to access uploaded files. In Pylons, what is the syntax to access a file if you don't know the filename, something like request.files[0]? A: Based on what this: http://pylonshq.com/docs/en/1.0/forms/#file-uploads page says, y...
pylons file uploading - access 1st file
Currently, I'm using request.params["filename"] to access uploaded files. In Pylons, what is the syntax to access a file if you don't know the filename, something like request.files[0]?
[ "Based on what this: http://pylonshq.com/docs/en/1.0/forms/#file-uploads page says, you could search through the params or request.POST looking for values of the type cgi.FieldStorage\n", "It's not the file name that's used as a key in request.params, it's the field name that was used in the HTML: <input type=\"f...
[ 1, 0 ]
[]
[]
[ "file_upload", "pylons", "python" ]
stackoverflow_0003073572_file_upload_pylons_python.txt
Q: Returning Database Blobs in TurboGears 2.x / FCGI / Lighttpd extremely slow I am running a TG2 App on lighttpd via flup/fastcgi. We are reading images (~30kb each) from BlobFields in a MySQL database and return those images with a custom mime type via a controller method. Caching these images on the hard disk mak...
Returning Database Blobs in TurboGears 2.x / FCGI / Lighttpd extremely slow
I am running a TG2 App on lighttpd via flup/fastcgi. We are reading images (~30kb each) from BlobFields in a MySQL database and return those images with a custom mime type via a controller method. Caching these images on the hard disk makes no sense because they change with every request, the only reason we cache thes...
[ "I've no clue, really, but seeing as there are no answers here, I'll try a wild guess.\nPerhaps\nresponse.headers['content-length'] = len(img.data)\n\nwould help?\n" ]
[ 0 ]
[]
[]
[ "fastcgi", "pylons", "python", "turbogears" ]
stackoverflow_0002911867_fastcgi_pylons_python_turbogears.txt
Q: How to display multiple images? I'm trying to get multiple image paths from my database in order to display them, but it currently doesn't work. Here's what i'm using: def get_image(self, userid, id): image = meta.Session.query(Image).filter_by(userid=userid) permanent_file = open(image[id].image_path, 'r...
How to display multiple images?
I'm trying to get multiple image paths from my database in order to display them, but it currently doesn't work. Here's what i'm using: def get_image(self, userid, id): image = meta.Session.query(Image).filter_by(userid=userid) permanent_file = open(image[id].image_path, 'rb') if not os.path.exists(image.i...
[ "Twice you use image.image_path, but in one spot (where, you tell us, you get a mistake) you use image[id].image_path instead. What's id that you believe could be a proper index into image, and why the discrepancy in usage among different spots of your code?\nIf you want a certain number of images, why not use sli...
[ 1, 1, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0002841917_pylons_python_sqlalchemy.txt
Q: Python or Java? Whats better for mobile development, and GUI applications I know Python apps are faster to write, but it seems Java is the 800 lb gorilla for mobile and GUI development. Are there any mobile platforms that run Python, or should I go the Java route? A: Java is certainly available on more platform...
Python or Java? Whats better for mobile development, and GUI applications
I know Python apps are faster to write, but it seems Java is the 800 lb gorilla for mobile and GUI development. Are there any mobile platforms that run Python, or should I go the Java route?
[ "Java is certainly available on more platforms. I would pick a target platform (or set of targets) and see what language(s) would require the least number of redundant implementations. \nAlso, when you get to a certain level of complexity, the language often doesn't factor into speed. For initial prototypes, sure...
[ 2, 1, 0 ]
[]
[]
[ "java", "mobile", "python", "user_interface" ]
stackoverflow_0003198646_java_mobile_python_user_interface.txt
Q: Where did Pylons beautiful error handling go? Using Nginx + Paster + Flup#fcgi_thread I need to run my development through nginx due to some complicated subdomain routing rules in my pylons app that wouldn't be handled otherwise. I had been using lighttpd + paster + Flup#scgi_thread and the nice error reporting by...
Where did Pylons beautiful error handling go? Using Nginx + Paster + Flup#fcgi_thread
I need to run my development through nginx due to some complicated subdomain routing rules in my pylons app that wouldn't be handled otherwise. I had been using lighttpd + paster + Flup#scgi_thread and the nice error reporting by Pylons had been working fine in that environment. Yesterday I recompiled Python and MySQL ...
[ "I would guess that you need to configure Flup to disable its own error handling, so that the nice one one used by Paster could pass through.\n", "It looks like you are not getting the trackback css from _debug/media/traceback.css You might want to see if you can view the actual CSS and investigate whether nginx...
[ 2, 0 ]
[]
[]
[ "error_handling", "nginx", "paster", "pylons", "python" ]
stackoverflow_0002549611_error_handling_nginx_paster_pylons_python.txt
Q: Function expects 2 arguments when should only one I have a function friend_exists like this: def friend_exists(request, pid): result = False try: user = Friend.objects.get(pid=pid) except Friend.DoesNotExist: pass if user: result = True return result I'm calling it f...
Function expects 2 arguments when should only one
I have a function friend_exists like this: def friend_exists(request, pid): result = False try: user = Friend.objects.get(pid=pid) except Friend.DoesNotExist: pass if user: result = True return result I'm calling it from my other function like this: exists = friend_exists...
[ "Why do you think it should only take one? You've clearly got two arguments in the function definition:\ndef friend_exists(request, pid):\n\nRight there it says it expects request and pid.\n", "It takes two arguments and you are only giving it one, the value of form.cleaned_data['pid']. If that value is actually ...
[ 6, 2, 1 ]
[]
[]
[ "argument_passing", "django", "function", "python" ]
stackoverflow_0003199181_argument_passing_django_function_python.txt
Q: Unable to access database from within a method I keep receiving the error, "TypeError: 'Shard' object is unsubscriptable." #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session....
Unable to access database from within a method
I keep receiving the error, "TypeError: 'Shard' object is unsubscriptable." #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session.configure(bind=engine) #Establish an on-demand conn...
[ "Given the incomplete snippet of code you've given, the only relevant line is: \nshard.Session.configure(bind=shard.engine)\n\nThe error indication is a base Python type error, a scalar (or None) needed to be subscripted inside SQLAlchemy. This almost certainly is the result of an incompletely or erroneously constr...
[ 0, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0002349614_pylons_python_sqlalchemy.txt
Q: Setting Up virtualenv with python2.6 I'm setting up a virtualenv, but it seems to be using python2.5 by default. I'm using this command virtualenv newenv --no-site-packages -p python because the python found on my path is python2.6. I believe this to be true because when I type python and go into the shell, it te...
Setting Up virtualenv with python2.6
I'm setting up a virtualenv, but it seems to be using python2.5 by default. I'm using this command virtualenv newenv --no-site-packages -p python because the python found on my path is python2.6. I believe this to be true because when I type python and go into the shell, it tells me it's 2.6. When I create the virtual...
[ "using this as the location of python works on OSX 10.6\n/System/Library/Frameworks/Python.framework/Versions/2.6/Python\n" ]
[ 1 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0002784398_python_virtualenv.txt
Q: How do I slice a sequence to get the last item? I am practicing slicing, and I want to run a program that prints a name backwards. Mainly, I want to know how to access the last item in the sequence. I wrote the following: name = raw_input("Enter Your Name: ") backname = ??? print backname Is this a sound approac...
How do I slice a sequence to get the last item?
I am practicing slicing, and I want to run a program that prints a name backwards. Mainly, I want to know how to access the last item in the sequence. I wrote the following: name = raw_input("Enter Your Name: ") backname = ??? print backname Is this a sound approach? Obviously, the ??? is not a part of my syntax, jus...
[ "To access the last item in a sequence, use:\nprint name[-1]\n\nThis is the same as:\nprint name[len(name) - 1]\n\nReversing a sequence has a common idiom in Python:\nbackname = name[::-1]\n\nThe Good primer for Python slice notation question has more complete information.\n", "backname[-1] #the last item in the ...
[ 3, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003199447_python.txt
Q: Fill a table horiziantally say i have a list e.g. apple car bin How to i get it to fill horizonatlly in a table rather than vertically i.e so it looks like this in a table: apple car bin The code im using just repeats each entry of the list for the entire row, code below: <body> <div metal:fill-slot="main"...
Fill a table horiziantally
say i have a list e.g. apple car bin How to i get it to fill horizonatlly in a table rather than vertically i.e so it looks like this in a table: apple car bin The code im using just repeats each entry of the list for the entire row, code below: <body> <div metal:fill-slot="main"> <h1>List of Species in...
[ "<table border=\"0\" width=\"100%\">\n <tr tal:repeat=\"records container/Query_Species\">\n <td tal:content=\"records/gene_bank_species\">Species</td>\n </tr>\n <tr tal:repeat=\"records container/Query_Species\">\n <td tal:content=\"records/gene_bank_species\">Species</td> \n <...
[ 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003199487_html_python.txt
Q: pydev and twisted framework It seems like my Eclipse PyDev does not recognize that Twisted is installed on my system. I can't make auto suggest working. Does anyone know how to solve it? A: go to preferences->Pydev->Interpreter - Python and hit the apply button. That will rescan your modules directory and add an...
pydev and twisted framework
It seems like my Eclipse PyDev does not recognize that Twisted is installed on my system. I can't make auto suggest working. Does anyone know how to solve it?
[ "go to preferences->Pydev->Interpreter - Python and hit the apply button. That will rescan your modules directory and add any missing modules.\nThat should fix any normal import errors. Some modules do some runtime magic that PyDev cant follow.\n" ]
[ 12 ]
[]
[]
[ "eclipse", "pydev", "python", "twisted" ]
stackoverflow_0003199702_eclipse_pydev_python_twisted.txt
Q: Configuring pep8 in Textmate Textmate has a Python PEP8 bundle that will run pep8 validation on your file. How can I set it to do the equivalent of pep8 --ignore=E501 my_file.py? A: The author of the pep8 bundle has added a feature to hide user-specified error codes. http://github.com/ppierre/python-pep8-tmbund...
Configuring pep8 in Textmate
Textmate has a Python PEP8 bundle that will run pep8 validation on your file. How can I set it to do the equivalent of pep8 --ignore=E501 my_file.py?
[ "The author of the pep8 bundle has added a feature to hide user-specified error codes.\nhttp://github.com/ppierre/python-pep8-tmbundle\n" ]
[ 1 ]
[]
[]
[ "pep8", "python", "textmate", "textmatebundles" ]
stackoverflow_0003193871_pep8_python_textmate_textmatebundles.txt
Q: Threaded SOAP requests in Python (Django) application? I'm working with an application that needs to be make some time consuming SOAP requests (using suds, as it were). There are several instances where a user will change the state of an object and in doing so trigger one or more SOAP requests that fetch some dat...
Threaded SOAP requests in Python (Django) application?
I'm working with an application that needs to be make some time consuming SOAP requests (using suds, as it were). There are several instances where a user will change the state of an object and in doing so trigger one or more SOAP requests that fetch some data. This could be done in the background, and right now the u...
[ "That sounds great! You almost always want to do long running stuff in a background thread, and many soap requests spend a lot of time waiting on network IO...\nThe only question is how do you get the data back to the user. Is this a GUI app, or a web app, or what? \n", "I use the producer consumer model with a ...
[ 1, 0 ]
[]
[]
[ "asynchronous", "django", "multithreading", "python", "soap" ]
stackoverflow_0003200004_asynchronous_django_multithreading_python_soap.txt
Q: BadStatusLine Error in Python (On Windows Only) I am developing an application with PyQT4 which will POST some data to a web service to send SMS. The application works perfectly on Ubuntu 10.04. But when I deploy it on Windows, I get the BadStatusLine Error. I am running Python 2.6.4 on Windows 7. The Error Messag...
BadStatusLine Error in Python (On Windows Only)
I am developing an application with PyQT4 which will POST some data to a web service to send SMS. The application works perfectly on Ubuntu 10.04. But when I deploy it on Windows, I get the BadStatusLine Error. I am running Python 2.6.4 on Windows 7. The Error Message and the source codes follow. I didn't put the gui.p...
[ "Well, I just got id of it. You can not mix up Unicode and Strings. I also used urllib instead of urllib2. It worked. But I am not yet sure where the problem came from :(\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003176934_python.txt
Q: Python: Redis as session backend to Beaker Anyone had success with using Redis as Beaker backend? Can you tell me link or library how to do it? I am looking for any library which does this but could not get anything out of google search. A: I have posted to pylons user group and this information resolve my quest...
Python: Redis as session backend to Beaker
Anyone had success with using Redis as Beaker backend? Can you tell me link or library how to do it? I am looking for any library which does this but could not get anything out of google search.
[ "I have posted to pylons user group and this information resolve my question..\nhttp://groups.google.com/group/pylons-discuss/msg/a1144aa1ca8e0417\nHere are the steps that worked for me:\n\neasy_install redis\neasy_install pip\npip install git+git://github.com/bbangert/beaker_extensions.git\nEdit Pylons' developmen...
[ 11 ]
[]
[]
[ "beaker", "pylons", "python", "redis", "session" ]
stackoverflow_0003192677_beaker_pylons_python_redis_session.txt
Q: sqlalchemy filter using in_ Is there a more efficient way to do the following? I am more interested in knowing if there is a way to set "mylist" to match anything if day is equal to 'all' because in other scenarios, "mylist" can contain a lot more elements. if day == 'all': mylist = ['monday','tuesday','wedn...
sqlalchemy filter using in_
Is there a more efficient way to do the following? I am more interested in knowing if there is a way to set "mylist" to match anything if day is equal to 'all' because in other scenarios, "mylist" can contain a lot more elements. if day == 'all': mylist = ['monday','tuesday','wednesday','thursday','friday','satur...
[ "What about just not filtering on the day if it's equal to 'all'?\nquery = meta.session.query(Transaction)\nif day != 'all':\n query = query.filter(Transaction.day == day)\nrecords = query.all()\n\n" ]
[ 7 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003200395_python_sqlalchemy.txt
Q: How to add Tkinter support for PIL Python library Okay, well supposedly PIL is supposed to be able to work with Tkinter automatically, but mine is not. I found this text file in the Imaging directories Tk directory. Using PIL With Tkinter Starting with 1.0 final (release candidate 2 and later, to be precise), P...
How to add Tkinter support for PIL Python library
Okay, well supposedly PIL is supposed to be able to work with Tkinter automatically, but mine is not. I found this text file in the Imaging directories Tk directory. Using PIL With Tkinter Starting with 1.0 final (release candidate 2 and later, to be precise), PIL can attach itself to Tkinter in flight. As a result...
[ "What versions of Python and PIL are you using (and on what platform, etc)? All reasonably recent versions should already support all of these required options (with setup.py as well as Modules/Setup.dict) -- e.g., including tkappinit.c etc -- so it's particularly hard to know what to suggest \"in a vacuum\". Als...
[ 0 ]
[]
[]
[ "compilation", "python", "python_imaging_library", "tkinter" ]
stackoverflow_0003200308_compilation_python_python_imaging_library_tkinter.txt
Q: How to make a group for each word in a sentence? This may be a silly question but... Say you have a sentence like: The quick brown fox Or you might get a sentence like: The quick brown fox jumped over the lazy dog The simple regexp (\w*) finds the first word "The" and puts it in a group. For the first sentence...
How to make a group for each word in a sentence?
This may be a silly question but... Say you have a sentence like: The quick brown fox Or you might get a sentence like: The quick brown fox jumped over the lazy dog The simple regexp (\w*) finds the first word "The" and puts it in a group. For the first sentence, you could write (\w*)\s*(\w*)\s*(\w*)\s*(\w*)\s* to ...
[ "You can also use the function findall in the module re\nimport re\n>>> re.findall(\"\\w+\", \"The quick brown fox\")\n['The', 'quick', 'brown', 'fox']\n\n", "I don't believe that it is possible. Regexes pair the captures with the parentheses in the given regular expression... if you only listed one group, like '...
[ 6, 4, 3, 1 ]
[]
[]
[ "python", "regex", "regex_group" ]
stackoverflow_0003200467_python_regex_regex_group.txt
Q: Django: How to define the models when parent model has two foreign keys come from one same model? I want to define two model fields: created_by, modified_by in a parent model, they will be acting as common fields for the child models. class ExtendedModel(models.Model): created_by = models.ForeignKey(User,r...
Django: How to define the models when parent model has two foreign keys come from one same model?
I want to define two model fields: created_by, modified_by in a parent model, they will be acting as common fields for the child models. class ExtendedModel(models.Model): created_by = models.ForeignKey(User,related_name='r_created_by') modified_by = models.ForeignKey(User,related_name='r_modified_by') ...
[ "The Django docs explain how to work around this: http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-related-name\nclass ExtendedModel(models.Model):\n created_by = models.ForeignKey(User,related_name='\"%(app_label)s_%(class)s_created_by')\n modified_by = models.ForeignKey(User,related_n...
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003200519_django_django_models_python.txt
Q: Python: does calling a method 'directly' instantiate the object? I am new to Python and while unit testing some methods on my object I noticed something 'weird'. class Ape(object): def __init__(self): print 'ooook' def say(self, s): print s def main(): Ape().say('eeek') if __name__ ...
Python: does calling a method 'directly' instantiate the object?
I am new to Python and while unit testing some methods on my object I noticed something 'weird'. class Ape(object): def __init__(self): print 'ooook' def say(self, s): print s def main(): Ape().say('eeek') if __name__ == '__main__': main() I wrote this little example to illustrate w...
[ "If you want to call a method directly without creating an instance you can use the staticmethod decorator. Notice that there is no self when you use a static method\nclass Ape(object):\n def __init__(self):\n print 'ooook'\n\n @staticmethod\n def say(s):\n print s\n\ndef main():\n Ape.say...
[ 14, 12, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003200309_python.txt
Q: excess positional arguments, unpacking argument lists or tuples, and extended iterable unpacking This question is going to be rather long, so I apologize preemptively. In Python we can use * in the following three cases: I. When defining a function that we want to be callable with an arbitrary number of arguments,...
excess positional arguments, unpacking argument lists or tuples, and extended iterable unpacking
This question is going to be rather long, so I apologize preemptively. In Python we can use * in the following three cases: I. When defining a function that we want to be callable with an arbitrary number of arguments, such as in this example: def write_multiple_items(file, separator, *args): file.write(separator.j...
[ "You missed one.\nIV. Also, in Python 3, a bare * in the argument list marks the end of positional arguments, allowing for keyword-only arguments.\ndef foo(a, b, *, key = None):\n pass\n\nThis can be called foo(1, 2, key = 3) but not foo(1, 2, 3).\n", "\nIn Python we can use * in the\n following three cases:\...
[ 8, 7 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0003200120_list_python_tuples.txt
Q: What is the best way to get Facebook Connect going with a Django app? (Given the new data permissions.) I'm new to Django and trying to set up a Facebook connected site. There seem to be three available options at the moment: Use middleware with PyFacebook. I was able to get the django-facebookconnect app going...
What is the best way to get Facebook Connect going with a Django app? (Given the new data permissions.)
I'm new to Django and trying to set up a Facebook connected site. There seem to be three available options at the moment: Use middleware with PyFacebook. I was able to get the django-facebookconnect app going fairly easily and mod it to suit my needs, but it is currently unclear whether PyFacebook even supports exte...
[ "\nI plan to have users authenticate only through Facebook connect and then maintain dummy Django user accounts for each on the backend. \n\nSeems you want exactly what http://github.com/flashingpumpkin/django-socialregistration does\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "javascript", "python" ]
stackoverflow_0003192764_django_facebook_javascript_python.txt
Q: Getting return values from a class How would I get return values in this case. (as I would a function) class A(object): def __init__(self,a,b): self.a = a self.b = b self.run() def run(self): return a + b When I do that I get an instance, how would I get a return value? Tha...
Getting return values from a class
How would I get return values in this case. (as I would a function) class A(object): def __init__(self,a,b): self.a = a self.b = b self.run() def run(self): return a + b When I do that I get an instance, how would I get a return value? Thanks James
[ "Are you trying to do something like:\nclass A(object):\n def __init__(self,a,b):\n self.a = a\n self.b = b\n def __call__(self):\n return self.a + self.b\n\na = A(3, 4)\na() # returns 7\n\nIt's not clear what you want and why. __init__ modifies the self object, but is required to return...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003199931_python.txt
Q: Keeping track of data types in Python So I hope this is a valid question... I've recently (today actually) decided to learn how a scripting language, so I chose Python. While glancing over code, I felt overwhelmed, and I soon realized that the reason was that I didn't know what data type conversions and stuff were...
Keeping track of data types in Python
So I hope this is a valid question... I've recently (today actually) decided to learn how a scripting language, so I chose Python. While glancing over code, I felt overwhelmed, and I soon realized that the reason was that I didn't know what data type conversions and stuff were going on. My question is: Is there any co...
[ "The normal Python approach is duck typing -- from the old phrase \"if it quacks like a duck, and walks like a duck, it's duck enough for me\".\nIn exceptional cases where you really must check what type something is (to do different things to otherwise similar types... usually not a good idea), that's what isinsta...
[ 6, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0003200683_python_types.txt
Q: "Deparsing" a list using pyparsing Is it possible to give pyparsing a parsed list and have it return the original string? A: Yes, you can if you've instructed the parser not to throw away any input. You do it with the Combine combinator. Let's say your input is: >>> s = 'abc,def, ghi' Here's a parser that grab...
"Deparsing" a list using pyparsing
Is it possible to give pyparsing a parsed list and have it return the original string?
[ "Yes, you can if you've instructed the parser not to throw away any input. You do it with the Combine combinator.\nLet's say your input is:\n>>> s = 'abc,def, ghi'\n\nHere's a parser that grabs the exact text of the list:\n>>> from pyparsing import *\n>>> myList = Word(alphas) + ZeroOrMore(',' + Optional(White()) ...
[ 7 ]
[]
[]
[ "parsing", "pyparsing", "python" ]
stackoverflow_0003188746_parsing_pyparsing_python.txt
Q: Python lib for publishing email to web I want to read email and publish it to the web. Is there a good python library available to read email, understand headers, data, attachments etc. and which can easily convert this data to web publishable format? A: Try python email module This tutorial will also be helpful...
Python lib for publishing email to web
I want to read email and publish it to the web. Is there a good python library available to read email, understand headers, data, attachments etc. and which can easily convert this data to web publishable format?
[ "Try python email module\nThis tutorial will also be helpful.\n" ]
[ 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0003200759_email_python.txt
Q: google app engine (python) confusing class 'object has no attribute' error I have a 2 classes. One looks like this: class Feed(db.Model): bid = db.StringProperty() title = db.StringProperty() url = db.StringProperty() datecreated = db.DateProperty(auto_now_add=True) voice = db.StringProperty() ...
google app engine (python) confusing class 'object has no attribute' error
I have a 2 classes. One looks like this: class Feed(db.Model): bid = db.StringProperty() title = db.StringProperty() url = db.StringProperty() datecreated = db.DateProperty(auto_now_add=True) voice = db.StringProperty() lastchecked = db.DateProperty(auto_now=True) language = db.StringPropert...
[ "I've pasted your models in a \"hello world\" main.py; then running it on the local SDK, I enter on the interactive console:\nimport main as m\n\np = m.Post()\np.put()\nf = m.Feed()\nf.put()\n\nif p.key() not in f.posts:\n f.posts.append(p.key())\n f.put()\n\nprint f.posts\n\nand I see, just as expected, in t...
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003199408_google_app_engine_python.txt
Q: Reading files to list of strings in Python When you use the fileName.readlines() function in Python, is there a symbol for the end of the file that is included in the list? For example, if the file is read into a list of strings and the last line is 'End', will there be another place in the list with a symbol indi...
Reading files to list of strings in Python
When you use the fileName.readlines() function in Python, is there a symbol for the end of the file that is included in the list? For example, if the file is read into a list of strings and the last line is 'End', will there be another place in the list with a symbol indicating the end of the file? Thanks.
[ "No, the list contains one element for each line in the file.\nYou can do something with each line in a for look like this:\nlines = infile.readlines()\nfor line in lines:\n # Do something with this line\n process(line)\n\nPython has a shorter way of accomplishing this that avoids reading the whole file into ...
[ 5, 1, 0 ]
[]
[]
[ "file", "list", "python" ]
stackoverflow_0003199363_file_list_python.txt
Q: to merge two columns in a csv file merge two columns in a csv file A: Here is an example, dont know your delimiter. if you want to write it to the same file you have to buffer the whole file first, modify the rows, then write it back to the same file. import csv for row in csv.reader(open('test.txt'),delimiter...
to merge two columns in a csv file
merge two columns in a csv file
[ "Here is an example, dont know your delimiter. if you want to write it to the same file you have to buffer the whole file first, modify the rows, then write it back to the same file.\n import csv\n for row in csv.reader(open('test.txt'),delimiter=\"\\t\"):\n print row[0]+row[1]\n\n", " fin = open('file.csv...
[ 3, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003200857_csv_python.txt
Q: How does the decimal accuracy of Python compare to that of C? I was looking at the Golden Ratio formula for finding the nth Fibonacci number, and it made me curious. I know Python handles arbitrarily large integers, but what sort of precision do you get with decimals? Is it just straight on top of a C double or so...
How does the decimal accuracy of Python compare to that of C?
I was looking at the Golden Ratio formula for finding the nth Fibonacci number, and it made me curious. I know Python handles arbitrarily large integers, but what sort of precision do you get with decimals? Is it just straight on top of a C double or something, or does it use a a more accurate modified implementation t...
[ "almost all platforms map Python floats to IEEE-754 “double precision”.\nhttp://docs.python.org/tutorial/floatingpoint.html#representation-error\nthere's also the decimal module for arbitrary precision floating point math\n", "Python floats use the double type of the underlying C compiler. As Bwmat says, this is...
[ 3, 2 ]
[]
[]
[ "c", "floating_accuracy", "language_implementation", "programming_languages", "python" ]
stackoverflow_0003201319_c_floating_accuracy_language_implementation_programming_languages_python.txt
Q: Faster Deserialization in Python What do you think is the fastest deserialization method? Pickle? YAML? or JSONPickle? A: I'd imagine cPickle would be the fastest method of serialisation, though it's just an (educated) guess. It's written in pure C, with Python bindings, and uses a binary format for storing obje...
Faster Deserialization in Python
What do you think is the fastest deserialization method? Pickle? YAML? or JSONPickle?
[ "I'd imagine cPickle would be the fastest method of serialisation, though it's just an (educated) guess. It's written in pure C, with Python bindings, and uses a binary format for storing objects, thus should be pretty fast!\n" ]
[ 1 ]
[]
[]
[ "python", "serialization" ]
stackoverflow_0003201545_python_serialization.txt
Q: what's a good module for writing an http web service interface for a daemon? To give a little background, I'm writing (or am going to write) a daemon in Python for scheduling tasks to run at user-specified dates. The scheduler daemon also needs to have a JSON-based HTTP web service interface (buzzword mania, I kno...
what's a good module for writing an http web service interface for a daemon?
To give a little background, I'm writing (or am going to write) a daemon in Python for scheduling tasks to run at user-specified dates. The scheduler daemon also needs to have a JSON-based HTTP web service interface (buzzword mania, I know) for adding tasks to the queue and monitoring the scheduler's status. The interf...
[ "Check out the class BaseHTTPServer -- a \"Basic HTTP server\" bundled with Python.\nhttp://docs.python.org/library/basehttpserver.html\nYou can spin up a second thread and have it serve your requests for you very easily (probably < 30 lines of code). And it all runs in the same process and Python interpreter spac...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0003201446_python_web_services.txt
Q: How to get the point in time of (last) vertical retrace under Python? I am using Pygame to pageflip different stimuli on the screen. The problem is that pygame's flip function, although syncing the flip to the vertical retrace, does not tell me when the retrace was. Does anyone know of a way to get this informatio...
How to get the point in time of (last) vertical retrace under Python?
I am using Pygame to pageflip different stimuli on the screen. The problem is that pygame's flip function, although syncing the flip to the vertical retrace, does not tell me when the retrace was. Does anyone know of a way to get this information (preferably platform independent) in Python? Regards, fladd
[ "Just poll for the time immediately after the flip call, if that one syncs to the vertical retrace.\n" ]
[ 0 ]
[]
[]
[ "flip", "pygame", "python" ]
stackoverflow_0003201685_flip_pygame_python.txt
Q: Kick off daemonized service using djangos manage.py custom command? I got a custom command in my reusable django app which I want to kick off a daemonized service and then return, leaving the service running. I've implemented my service as a simple class with a start-method. When start is called it runs in an eter...
Kick off daemonized service using djangos manage.py custom command?
I got a custom command in my reusable django app which I want to kick off a daemonized service and then return, leaving the service running. I've implemented my service as a simple class with a start-method. When start is called it runs in an eternal loop, sleeping for 10 seconds, then using the django orm to check the...
[ "I have the beginnings of a library, django-initd, to handle this: see the project on GitHub. \nDjango actually includes a utility for a process to daemonize itself, in django.utils.daemonize, my library takes care of the startup/shutdown, logging, and interaction with the management command. I'd be interested to k...
[ 2, 0 ]
[]
[]
[ "command", "django", "python", "service" ]
stackoverflow_0003201799_command_django_python_service.txt
Q: Mod_python on django and debug variable I have a problem with my django application. On django developer server its work perfect, but when I switch it to apache something strange happening. Lets check the code: class Criteria(models.Model): district = models.ManyToManyField(District, verbose_name=u"Województwo...
Mod_python on django and debug variable
I have a problem with my django application. On django developer server its work perfect, but when I switch it to apache something strange happening. Lets check the code: class Criteria(models.Model): district = models.ManyToManyField(District, verbose_name=u"Województwo", blank=True) respondents = models.ManyT...
[ "I would look into this block node \"loginBox\" and the required parameter 'user' if I were you.\n" ]
[ 0 ]
[]
[]
[ "apache2", "django", "mod_python", "python" ]
stackoverflow_0003198916_apache2_django_mod_python_python.txt
Q: BeautifulSoup get innerhtml data I am trying to read data from a website. I can see the value I need but the value does not appear in the downloaded html code (using urllib2). The value is created by some js file and embedded into the webpage as innerhtml for that id. PS: How can that be extracted? raw source code...
BeautifulSoup get innerhtml data
I am trying to read data from a website. I can see the value I need but the value does not appear in the downloaded html code (using urllib2). The value is created by some js file and embedded into the webpage as innerhtml for that id. PS: How can that be extracted? raw source code cannot render js unlike the browsers!...
[ "Another way of getting data is leaving the browser do all the stuff using Selenium and read the rendered html. A bit slow but surely effective.\nHere you can find a getting started guide for using Selenium with Python:\nhttp://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html\n", "You have two o...
[ 4, 1 ]
[]
[]
[ "beautifulsoup", "innerhtml", "javascript", "python", "urllib2" ]
stackoverflow_0003201824_beautifulsoup_innerhtml_javascript_python_urllib2.txt
Q: Django: Saving an image file from a form I want to save the image which as been uploaded via the PaletteGenForm as such: #Form class PaletteGenForm(forms.Form): im = forms.ImageField(required=True) #View def palette_gen_view(request): PATH_OF_IMAGE_TO_BE_PALETTED= MEDIA_ROOT+ "/tobesaved.png" if requ...
Django: Saving an image file from a form
I want to save the image which as been uploaded via the PaletteGenForm as such: #Form class PaletteGenForm(forms.Form): im = forms.ImageField(required=True) #View def palette_gen_view(request): PATH_OF_IMAGE_TO_BE_PALETTED= MEDIA_ROOT+ "/tobesaved.png" if request.method == 'POST': form = PaletteGe...
[ "Try this:\nim = Image.open(StringIO(request.FILES['im'].read()))\n\n", "Not sure you need to wrap it in a StringIO at all. Try\nim = Image.open(request.FILES['im']['content'])\n\n", "try reading the data from form cleaned_data\nim = Image.open(StringIO(form.cleaned_data['im'].read()))\n\nfor me this worked (di...
[ 4, 1, 0 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0003201777_django_django_forms_django_views_python.txt
Q: Django - Selecting related set : how many times does it hit the database? I took this sample code here : Django ORM: Selecting related set polls = Poll.objects.filter(category='foo') choices = Choice.objects.filter(poll__in=polls) My question is very simple : do you hit twice the database when you finally use the...
Django - Selecting related set : how many times does it hit the database?
I took this sample code here : Django ORM: Selecting related set polls = Poll.objects.filter(category='foo') choices = Choice.objects.filter(poll__in=polls) My question is very simple : do you hit twice the database when you finally use the queryset choices ?
[ "It will be one query, but containing an inner SELECT; if you want to do some debugging on that, you could either use the marvellous django-debug-toolbar, or do something like print str(choices.query) which will output the raw sql of your query!\n" ]
[ 1 ]
[]
[]
[ "django", "django_orm", "performance", "python" ]
stackoverflow_0003202186_django_django_orm_performance_python.txt
Q: Insert inline image into Lotus Notes message I've been able to send emails using Lotus Notes and VBA and Python using the COM API like this: Can I use Lotus Notes to send mail? My question is how can I insert an image inline with the body text (not as an attachment) in a programmatic way (equivalent to the Edit | ...
Insert inline image into Lotus Notes message
I've been able to send emails using Lotus Notes and VBA and Python using the COM API like this: Can I use Lotus Notes to send mail? My question is how can I insert an image inline with the body text (not as an attachment) in a programmatic way (equivalent to the Edit | Paste Special)? I haven't been able to find any wo...
[ "It should be possible to do this using the DXLImporter class, available from VBA through the COM interface. DXL is a Notes-specific XML, which you can generate to a temp file, then import into your database. There is sample code on this blog entry, which may be close to what you are looking for (this imports a ric...
[ 1, 1 ]
[]
[]
[ "lotus_notes", "python", "vba" ]
stackoverflow_0003189622_lotus_notes_python_vba.txt
Q: What's the best way to store quickly-changing data in Python? On a quest to learn a bit about Python and sockets I'm writing a little 2d-game server. And although I don't see more than a few people on this server at any given time, I want to write it as efficiently as I can. I have a global dictionary called "glob...
What's the best way to store quickly-changing data in Python?
On a quest to learn a bit about Python and sockets I'm writing a little 2d-game server. And although I don't see more than a few people on this server at any given time, I want to write it as efficiently as I can. I have a global dictionary called "globuser", in it is another dictionary containing the user stats (like ...
[ "One thing I might look at is storing the users as a list of Player objects. Look into __slots__, as that will save you memory when creating many instances.\nI also would not worry much about performance at this stage. Write the code first and then run it through a profiler to find out where it is slowest -- making...
[ 3, 2 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0003202376_python_variables.txt
Q: Good practices for a flexible search page - Django I'm just wondering if there is any example I could take from others on the topic. I have a page within Django which uses filters, in order to perform searches. At the moment I'm doing a simple check for the GET parameters and adding a .filter() to a queryset accor...
Good practices for a flexible search page - Django
I'm just wondering if there is any example I could take from others on the topic. I have a page within Django which uses filters, in order to perform searches. At the moment I'm doing a simple check for the GET parameters and adding a .filter() to a queryset accordingly: if color: query.filter(color=color) This fee...
[ "Try this:\nALLOWED = ('color', 'size', 'model')\nkwargs = dict(\n (key, value)\n for key, value in request.GET.items()\n if key in ALLOWED\n)\nquery.filter(**kwargs)\n\nThis will allow you to make requests like this /search/?color=red&size=1 or /search/?model=Nikon&color=black.\n" ]
[ 5 ]
[]
[]
[ "django", "django_models", "django_queryset", "filter", "python" ]
stackoverflow_0003202922_django_django_models_django_queryset_filter_python.txt
Q: Images are not being stored?? - Django These are my following settings: MEDIA_ROOT = '/home/webapps/test_project/media/' MEDIA_URL = 'http://192.168.0.2:8090/site_media/' ADMIN_MEDIA_PREFIX = '/media/' These are my model fields: large = models.ImageField(blank=True, null=True, upload_to="images") thumb = models.I...
Images are not being stored?? - Django
These are my following settings: MEDIA_ROOT = '/home/webapps/test_project/media/' MEDIA_URL = 'http://192.168.0.2:8090/site_media/' ADMIN_MEDIA_PREFIX = '/media/' These are my model fields: large = models.ImageField(blank=True, null=True, upload_to="images") thumb = models.ImageField(blank=True, null=True, upload_to="...
[ "Mistyped \nMEDIA_ROOT = '/home/webapps/test_project/media/'\n\nwrote home instead of root\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_uploads", "python" ]
stackoverflow_0003203119_django_django_models_django_uploads_python.txt
Q: how do i store the output of my cursor object to a text file? I have accessed a database and have the result in a cursor object. when I try to save it to a text file, python says TypeError: argument 1 must be string or read-only character buffer, not sqlite3.Cursor can someone tell me what I should do here? curo...
how do i store the output of my cursor object to a text file?
I have accessed a database and have the result in a cursor object. when I try to save it to a text file, python says TypeError: argument 1 must be string or read-only character buffer, not sqlite3.Cursor can someone tell me what I should do here? curobject.execute('select * from device_auth') for row in curobject: ...
[ "You can't just write objects to a file, you have to either serialize them or write your own string representation of the object. For records of a database the csv module could make sense.\nWhich approach is better depends on what you want to do with the file later.\n", "For example something like this:\nwith ope...
[ 1, 0 ]
[]
[]
[ "file_io", "python", "sqlite" ]
stackoverflow_0003203241_file_io_python_sqlite.txt
Q: How to debug Python code that is partially covered by passing unit tests but produces wrong results when being reused? I have a Python class and its methods are partially covered by unit tests like this: class MyClass: def __init__(self): self.instancevar1 = None # some methods change this value ...
How to debug Python code that is partially covered by passing unit tests but produces wrong results when being reused?
I have a Python class and its methods are partially covered by unit tests like this: class MyClass: def __init__(self): self.instancevar1 = None # some methods change this value self.instancevar2 = None # some methods change this value ... def method1(self, input_data): ... ...
[ "As Rudi said, there's either a bug in MyClass.method1() that causes it to return False when it shouldn't, or there's a bug in other parts of the code that puts mc in a state you didn't expect.\nYou can address both problems with additional unit tests:\n\nIf there's a bug in MyClass.method1() when mc is in a partic...
[ 2, 1 ]
[]
[]
[ "debugging", "python", "unit_testing" ]
stackoverflow_0003203101_debugging_python_unit_testing.txt
Q: read file from server with some offset How can I read file from server starting with some offset (Similar behavior to wget -c)? What headers I must send to server? What futures must server support? A: You should use the Range header in the request. But you may use it only if the server informs you that it accept...
read file from server with some offset
How can I read file from server starting with some offset (Similar behavior to wget -c)? What headers I must send to server? What futures must server support?
[ "You should use the Range header in the request. But you may use it only if the server informs you that it accept range request by Accept-Ranges response header.\nThis is an example session. Suppose we are interested in getting a part of this picture. First, we send a HTTP HEAD request to determine: a) if the serve...
[ 18, 3 ]
[]
[]
[ "http", "python" ]
stackoverflow_0003203217_http_python.txt
Q: How to make persistent a python dictionary on google appengine Using datastore framework of appengine, what's the pythonic way to make persistent a {}? A: You would only need to use the expando option if you intend to query on the individual dictionary elements. Assuming you don't want to do this, then you can u...
How to make persistent a python dictionary on google appengine
Using datastore framework of appengine, what's the pythonic way to make persistent a {}?
[ "You would only need to use the expando option if you intend to query on the individual dictionary elements.\nAssuming you don't want to do this, then you can use a custom property -\nclass ObjectProperty(db.Property):\n data_type = db.Blob\n\n def get_value_for_datastore(self, model_instance):\n value = self....
[ 5, 3, 2 ]
[]
[]
[ "dictionary", "persistence", "python" ]
stackoverflow_0003203543_dictionary_persistence_python.txt
Q: Is there a way to set the value of wsgi.input when testing? When using wsgiref.util.setup_testing_defaults() to set up a WSGI environ is it possible to set the wsgi.input value so that one can test HTTP POST requests? Investigating the wsgi.input value created by setup_testing_defaults() shows that it's a wsgi.val...
Is there a way to set the value of wsgi.input when testing?
When using wsgiref.util.setup_testing_defaults() to set up a WSGI environ is it possible to set the wsgi.input value so that one can test HTTP POST requests? Investigating the wsgi.input value created by setup_testing_defaults() shows that it's a wsgi.validate.InputWrapper object with read, readline, readlines, input, ...
[ "According to the WSGI spec, the wsgi.input is just a file-like object. So even if your helper library assigns some weird object to the environ['wsgi.input'], you may replace it with any file-like object you want. In particular, with a StringIO object:\ne = {}\nsetup_testing_defaults(e)\ns = urlencode({'q': 'is the...
[ 3 ]
[]
[]
[ "python", "unit_testing", "wsgi" ]
stackoverflow_0003203422_python_unit_testing_wsgi.txt
Q: What's the meaning of '@' in python code? Reading some Python (PyQt) code, I came across as follows. @pyqtSignature("QString") def on_findLineEdit_textEdited(self, text): self.__index = 0 self.updateUi() How does this @pyqtSignature work? How Python treat this @? A: It is the decorator syntax, simply it...
What's the meaning of '@' in python code?
Reading some Python (PyQt) code, I came across as follows. @pyqtSignature("QString") def on_findLineEdit_textEdited(self, text): self.__index = 0 self.updateUi() How does this @pyqtSignature work? How Python treat this @?
[ "It is the decorator syntax, simply it is equivalent to this form:\non_findLineEdit_textEdited = pyqtSignature(\"Qstring\")(on_findLineEdit_textEdited)\n\nReally simple.\nA typical decorator takes as the first argument the function that has to be decorated, and perform stuff/adds functionalities to it. A typical ex...
[ 5, 2 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003203824_python_syntax.txt
Q: Django script add field to database I added a slug field to my database and now need to go through and add those. I want to run a script that looks at the slug field in the database and if empty generates and saves. Here is what I thought was along the lines, but is not working. from project.apps.tracks.models imp...
Django script add field to database
I added a slug field to my database and now need to go through and add those. I want to run a script that looks at the slug field in the database and if empty generates and saves. Here is what I thought was along the lines, but is not working. from project.apps.tracks.models import * def process_slug(): if not t...
[ "From your posted code it is not evident, that you are actually looping through all your Track objects. \nfrom project.apps.tracks.models import Track\n# import for slugify\n\ndef process_slug():\n \"\"\" Populate slug field, if they are empty. \n \"\"\"\n for track in Track.objects.all():\n if not ...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003203823_django_python.txt
Q: How to read String in java that was written using python’s struct.pack method out.write( struct.pack(">f", 1.1) ); out.write( struct.pack(">i", 12) ); out.write( struct.pack(">3s", "abc") ); how to import struct package in java it says .. no package found when i am trying to execute it so kindly tell me any su...
How to read String in java that was written using python’s struct.pack method
out.write( struct.pack(">f", 1.1) ); out.write( struct.pack(">i", 12) ); out.write( struct.pack(">3s", "abc") ); how to import struct package in java it says .. no package found when i am trying to execute it so kindly tell me any suggestions if any Thanking you i took that code from How to read String in java that...
[ "Read the answer to the question you referenced. The sample code in the question was incorrect.\nAlso, you don't import the struct package in Java. It's a Python package. Also as described in the other question, you use java.io.DataInputStream to read the file created from Python.\n" ]
[ 0 ]
[]
[]
[ "binary", "java", "python", "struct" ]
stackoverflow_0003203930_binary_java_python_struct.txt
Q: How to call process by name or tags in python I am using multiprocessing module. This module is works on Queue that is its pick random process and assign the entery from Queue. I want to decide which process will work on which entry of Queue Here is my requirements, I will pass 2 parameters to queue Initiator P...
How to call process by name or tags in python
I am using multiprocessing module. This module is works on Queue that is its pick random process and assign the entery from Queue. I want to decide which process will work on which entry of Queue Here is my requirements, I will pass 2 parameters to queue Initiator Process name Action/method ( What process is going ...
[ "multiprocessing.Process objects take an optional name argument on initialization. You can use that name as a key in a dictionary:\nchild_procs = {'name1' : Process(target=myprocfunc, name='name1'), ...}\nAs for IPC between the parent process and the children, you should be fine with just maintaining a separate mu...
[ 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0003204037_multiprocessing_python.txt
Q: how to check if a file is a directory or regular file in python? How do you check if a path is a directory or file in python? A: os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory? os.path.isdir("bob") A: use os.path.isdir(path) more info here http://docs.python.org/library/os.path....
how to check if a file is a directory or regular file in python?
How do you check if a path is a directory or file in python?
[ "os.path.isfile(\"bob.txt\") # Does bob.txt exist? Is it a file, or a directory?\nos.path.isdir(\"bob\")\n\n", "use os.path.isdir(path) \nmore info here http://docs.python.org/library/os.path.html\n", "Many of the Python directory functions are in the os.path module.\nimport os\nos.path.isdir(d)\n\n", "An ed...
[ 671, 146, 73, 22 ]
[]
[]
[ "python" ]
stackoverflow_0003204782_python.txt
Q: How to write Russian characters in file? In console when I'm trying output Russian characters It gives me ??????????????? Who know why? I tried write to file - in this case the same situation. for example f=open('tets.txt','w') f.write('some russian text') f.close inside file is - ?????????????????????????/ or p...
How to write Russian characters in file?
In console when I'm trying output Russian characters It gives me ??????????????? Who know why? I tried write to file - in this case the same situation. for example f=open('tets.txt','w') f.write('some russian text') f.close inside file is - ?????????????????????????/ or p="some russian text" print p ????????????? In...
[ "Here is a worked-out example, please read the comments:\n#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n# The above encoding declaration is required and the file must be saved as UTF-8\n\nfrom __future__ import with_statement # Not required in Python 2.6 any more\n\nimport codecs\n\np = u\"абвгдежзийкл\" # no...
[ 19, 9, 2, 1, 0 ]
[]
[]
[ "python", "python_2.x", "python_unicode", "unicode", "windows" ]
stackoverflow_0003198765_python_python_2.x_python_unicode_unicode_windows.txt
Q: How do I convert a tuple of tuples to a one-dimensional list using list comprehension? I have a tuple of tuples - for example: tupleOfTuples = ((1, 2), (3, 4), (5,)) I want to convert this into a flat, one-dimensional list of all the elements in order: [1, 2, 3, 4, 5] I've been trying to accomplish this with lis...
How do I convert a tuple of tuples to a one-dimensional list using list comprehension?
I have a tuple of tuples - for example: tupleOfTuples = ((1, 2), (3, 4), (5,)) I want to convert this into a flat, one-dimensional list of all the elements in order: [1, 2, 3, 4, 5] I've been trying to accomplish this with list comprehension. But I can't seem to figure it out. I was able to accomplish it with a for-e...
[ "it's typically referred to as flattening a nested structure.\n>>> tupleOfTuples = ((1, 2), (3, 4), (5,))\n>>> [element for tupl in tupleOfTuples for element in tupl]\n[1, 2, 3, 4, 5]\n\nJust to demonstrate efficiency:\n>>> import timeit\n>>> it = lambda: list(chain(*tupleOfTuples))\n>>> timeit.timeit(it)\n2.147573...
[ 74, 46, 13, 9, 9, 4, 4 ]
[]
[]
[ "iterable_unpacking", "list_comprehension", "python", "tuples" ]
stackoverflow_0003204245_iterable_unpacking_list_comprehension_python_tuples.txt
Q: HTTP based authentication/encryption protocol in a custom system We have a custom built program that needs authenticated/encrypted communication between a client and a server[both in Python]. We are doing an overhaul from custom written Diffie-Hellman+AES to RSA+AES in a non-orthodox way. So I would be very intere...
HTTP based authentication/encryption protocol in a custom system
We have a custom built program that needs authenticated/encrypted communication between a client and a server[both in Python]. We are doing an overhaul from custom written Diffie-Hellman+AES to RSA+AES in a non-orthodox way. So I would be very interested in comments about my idea. Prequisites: Klient has a 128bit Regis...
[ "Don't re-invent the wheal, use HTTPS. \nThe server can issue certificates to the client and store them in the Database. Clients can be distributed with the server's self-signed certificate for verification. The server can verify clients by using Apache's HTTPS Environment Variables.\n", "No. Use SSL. Reinvent...
[ 4, 3, 1 ]
[]
[]
[ "authentication", "cryptography", "encryption", "python", "security" ]
stackoverflow_0003205349_authentication_cryptography_encryption_python_security.txt
Q: Making HTTPS Requests in Twisted I am trying to write a client that can make both HTTP and HTTPS requests depending on how it is configured. For normal HTTP, I have been using twisted.web.client.Agent and using agent.request(METHOD, HOST, HEADERS, CONTENT) to make the requests. What I care about is that host field...
Making HTTPS Requests in Twisted
I am trying to write a client that can make both HTTP and HTTPS requests depending on how it is configured. For normal HTTP, I have been using twisted.web.client.Agent and using agent.request(METHOD, HOST, HEADERS, CONTENT) to make the requests. What I care about is that host field, when I do HTTP it works doing someth...
[ "HTTPS support was only recently added to twisted.web.client.Agent. If you can use Twisted 10.1, very recently released, then Agent will accept your HTTPS URLs.\n" ]
[ 5 ]
[]
[]
[ "client", "https", "python", "request", "twisted" ]
stackoverflow_0003204509_client_https_python_request_twisted.txt
Q: How do I implement something like Digg Swarm in PHP or Python? http://labs.digg.com/swarm/ A: http://raphaeljs.com/ For the Javascript data representation and i guess use PHP to talk with the API.
How do I implement something like Digg Swarm in PHP or Python?
http://labs.digg.com/swarm/
[ "http://raphaeljs.com/ For the Javascript data representation and i guess use PHP to talk with the API.\n" ]
[ 1 ]
[]
[]
[ "data_warehouse", "javascript", "php", "python" ]
stackoverflow_0003205157_data_warehouse_javascript_php_python.txt
Q: combining two string variables I'm a novice Python user trying to do something that I think should be simple but can't figure it out. I've got 2 variables defined: a = 'lemon' b = 'lime' Can someone tell me how to combine these in a new variable? If I try: >>> soda = "a" + "b" >>> soda 'ab' I want soda to be 'l...
combining two string variables
I'm a novice Python user trying to do something that I think should be simple but can't figure it out. I've got 2 variables defined: a = 'lemon' b = 'lime' Can someone tell me how to combine these in a new variable? If I try: >>> soda = "a" + "b" >>> soda 'ab' I want soda to be 'lemonlime'. How is this done? Thanks!...
[ "you need to take out the quotes:\nsoda = a + b\n\n(You want to refer to the variables a and b, not the strings \"a\" and \"b\")\n", "IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:\nthe_t...
[ 46, 21 ]
[]
[]
[ "python" ]
stackoverflow_0003205532_python.txt
Q: Next question about russian encoding, mssql and python Next question about russian encoding, mssql and python. I have this simple code: import pymssql import codecs conn=pymssql.connect(host='localhost:1433', user='sa', password='password', database='TvPgms') cur = conn.cursor() cur.execute('SELECT TOP 5 CAST( Na...
Next question about russian encoding, mssql and python
Next question about russian encoding, mssql and python. I have this simple code: import pymssql import codecs conn=pymssql.connect(host='localhost:1433', user='sa', password='password', database='TvPgms') cur = conn.cursor() cur.execute('SELECT TOP 5 CAST( Name AS nvarchar(400) ), CONVERT(nvarchar(400), idProgram) FRO...
[ "codecs.lookup takes an encoding name, not some random string, and you probably don't need it here anyway. I think at the moment you cannot reliably print Unicode strings from Python to the Windows console due to deep technical problems. Try writing to a file or using the WriteConsoleW function directly (via ctypes...
[ 2 ]
[]
[]
[ "console", "pymssql", "python", "unicode", "windows" ]
stackoverflow_0003205586_console_pymssql_python_unicode_windows.txt
Q: How to synchronize the output of Python subprocess I think I'm having issues to synchronize the output of two Popen running concurrently. It seems that the output from these two different command lines are interleaved with one another. I also tried using RLock to prevent this from happening but it didn't work. A s...
How to synchronize the output of Python subprocess
I think I'm having issues to synchronize the output of two Popen running concurrently. It seems that the output from these two different command lines are interleaved with one another. I also tried using RLock to prevent this from happening but it didn't work. A sample output would be: cmd1 cmd1 cmd2 cmd2 cmd2 cmd2 cmd...
[ "Maybe you are looking for the wait method\nhttp://docs.python.org/library/subprocess.html#subprocess.Popen.wait\n", "You're locking with a granularity of a line, so of course lines from one thread can and do alternate with lines from the other. As long as you're willing to wait until a process ends before showi...
[ 1, 1 ]
[]
[]
[ "popen", "python" ]
stackoverflow_0003205990_popen_python.txt
Q: Semantics of python loops and strings Consider: args = ['-sdfkj'] print args for arg in args: print arg.replace("-", '') arg = arg.replace("-", '') print args This yields: ['-sdfkj'] sdfkj ['-sdfkj'] Where I expected it to be ['sdfkj']. Is arg in the loop a copy? It behaves as if it is a copy (or perhaps...
Semantics of python loops and strings
Consider: args = ['-sdfkj'] print args for arg in args: print arg.replace("-", '') arg = arg.replace("-", '') print args This yields: ['-sdfkj'] sdfkj ['-sdfkj'] Where I expected it to be ['sdfkj']. Is arg in the loop a copy? It behaves as if it is a copy (or perhaps an immutable thingie, but then I expect an...
[ "\nIs arg in the loop a copy?\n\nYes, it contains a copy of the reference.\nWhen you reassign arg you aren't modifying the original array, nor the string inside it (strings are immutable). You modify only what the local variable arg points to. \nBefore assignment After assignment\n\nargs arg ...
[ 8, 1, 0, 0 ]
[]
[]
[ "python", "semantics" ]
stackoverflow_0003206375_python_semantics.txt
Q: matplotlib. How do I switch between subplots, rather than replotting them from scratch? I create a figure and fill it with a couple of subplots. As new data arrives, I'd like to draw it on a given subplot. How do I switch between subplots so that I don't have to create new subplot objects each time? Example: from ...
matplotlib. How do I switch between subplots, rather than replotting them from scratch?
I create a figure and fill it with a couple of subplots. As new data arrives, I'd like to draw it on a given subplot. How do I switch between subplots so that I don't have to create new subplot objects each time? Example: from matplotlib.pyplot import figure, figure() subplot(2,1,1) subplot(2,1,2) # now go back and p...
[ "Assign subplot to a variable:\nfig = matplotlib.pyplot.figure()\n\nplt1 = fig.add_subplot(2,1,1)\nplt2 = fig.add_subplot(2,1,2)\n\nThen you can draw lines and points and whatever else you want with references to plt1 and plt2\nTake a look at the reference for everything you can do with the plot.\n" ]
[ 8 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003206335_matplotlib_python.txt
Q: Cannot concatenate 'str' and 'list' objects I'm getting a TypeError: cannot concatenate 'str' and 'list' objects. I'm trying to pass an object from a list to create a new variable by concatenating it with another variable. Example: I want to take the value from the group list and concatenate it with "All.dbf" so i...
Cannot concatenate 'str' and 'list' objects
I'm getting a TypeError: cannot concatenate 'str' and 'list' objects. I'm trying to pass an object from a list to create a new variable by concatenating it with another variable. Example: I want to take the value from the group list and concatenate it with "All.dbf" so it will do something with that file for each value...
[ "\nI suppose I could add the \"All.dbf\" onto the values in the group list but thought there must be a better way to process this with a function or something that I don't know about...\n\nYou could use a list comprehension:\ngroup = [x + 'All.dbf' for x in group]\n\n", "dbname = [i+\"All.dbf\" for i in group]\n\...
[ 5, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003206601_python.txt
Q: .class file from jython with pydev My first attempt at jython is a java/jython project I'm writing in eclipse with pydev. I created a java project and then made it a pydev project by the RightClick project >> pydev >> set as... you get the idea. I then added two source folders, one for java and one for jython, and...
.class file from jython with pydev
My first attempt at jython is a java/jython project I'm writing in eclipse with pydev. I created a java project and then made it a pydev project by the RightClick project >> pydev >> set as... you get the idea. I then added two source folders, one for java and one for jython, and each source folder has a package. And I...
[ "Jythonc doesn't exist anymore, it has been forked off to another project called Clamp, but with that said...\n\n...you can pre-compile\n your python scripts to .class files\n using:\njython [jython home]/Lib/compileall.py\n [the directory where you keep your\n python code]\n\nSource - Jython Newsletter, March ...
[ 5, 0 ]
[]
[]
[ "eclipse", "java", "jython", "pydev", "python" ]
stackoverflow_0001075905_eclipse_java_jython_pydev_python.txt
Q: __bases__ doesn't work! What's next? The following code doesn't work in Python 3.x, but it used to work with old-style classes: class Extender: def extension(self): print("Some work...") class Base: pass Base.__bases__ += (Extender,) Base().extension() Question is simple: How can I add dynamica...
__bases__ doesn't work! What's next?
The following code doesn't work in Python 3.x, but it used to work with old-style classes: class Extender: def extension(self): print("Some work...") class Base: pass Base.__bases__ += (Extender,) Base().extension() Question is simple: How can I add dynamically (at runtime) a super class to a class ...
[ "It appears that it is possible to dynamically change Base.__bases__\nif Base.__base__ is not object. (By dynamically change, I mean in such a way that all pre-existing instances that inherit from Base also get dynamically changed. Otherwise see Mykola Kharechko's solution).\nIf Base.__base__ is some dummy class To...
[ 6, 5 ]
[]
[]
[ "multiple_inheritance", "python", "python_3.x", "runtime" ]
stackoverflow_0003193158_multiple_inheritance_python_python_3.x_runtime.txt
Q: How to use python build script with teamcity CI? I am currently researching using the TeamCity CI software for our comapanies CI automation needs but have had trouble finding information about using different build scripts with TeamCity. We have C++ projects that need to have build/test automation and we currently...
How to use python build script with teamcity CI?
I am currently researching using the TeamCity CI software for our comapanies CI automation needs but have had trouble finding information about using different build scripts with TeamCity. We have C++ projects that need to have build/test automation and we currently have licenses for TeamCity. I have looked into using ...
[ "We use TeamCity to run our acceptance test suite (which uses Robot Framework - done in python).\nGetting it to run was as simple as wrapping the python call with a very simple NAnt script. It does 2 things:\n\nUses an exec task to run python with the script as an argument.\nGets the xml output from the build and t...
[ 2 ]
[]
[]
[ "c++", "continuous_integration", "python", "teamcity" ]
stackoverflow_0003178165_c++_continuous_integration_python_teamcity.txt
Q: How to force using 64 bit python on Mac OS X? I got the following error when compiling sip with --arch x86_64 option. prosseek:siplib smcho$ python -c 'import sip; print sip' Traceback (most recent call last): File "", line 1, in ImportError: dlopen(./sip.so, 2): no suitable image found. Did find: ./...
How to force using 64 bit python on Mac OS X?
I got the following error when compiling sip with --arch x86_64 option. prosseek:siplib smcho$ python -c 'import sip; print sip' Traceback (most recent call last): File "", line 1, in ImportError: dlopen(./sip.so, 2): no suitable image found. Did find: ./sip.so: mach-o, but wrong architecture I found tha...
[ "Try using arch(1), and supply the specific version of Python:\narch -x86_64 /usr/bin/python2.6\n\nActually the system should choose the first suitable architecture for you. As\n$ file /usr/bin/python2.5\n/usr/bin/python2.5: Mach-O universal binary with 2 architectures\n/usr/bin/python2.5 (for architecture i386): M...
[ 6, 1 ]
[]
[]
[ "64_bit", "macos", "python", "python_sip" ]
stackoverflow_0003207324_64_bit_macos_python_python_sip.txt
Q: how do i set my python path for success with my import statements? I'm trying to install djangobb and when running manage.py syncdb it returns with Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import execute_manage ImportError: No module named django.c...
how do i set my python path for success with my import statements?
I'm trying to install djangobb and when running manage.py syncdb it returns with Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import execute_manage ImportError: No module named django.core.management I know that deep in my python installation there is djan...
[ "Make sure that the base directory for where django/ lives is on your $PYTHONPATH\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003207049_django_python.txt
Q: DTML: How to prevent formatting loss I have a DTML document which only contains: <dtml-var public_blast_results> and displays when i view it as: YP_001336283 100.00 345 0 0 23 367 23 367 0.0 688 When I edit the DTML page for example just adding a header like: <h3>Header</h3> <dtm...
DTML: How to prevent formatting loss
I have a DTML document which only contains: <dtml-var public_blast_results> and displays when i view it as: YP_001336283 100.00 345 0 0 23 367 23 367 0.0 688 When I edit the DTML page for example just adding a header like: <h3>Header</h3> <dtml-var public_blast_results> The "public_b...
[ "This is nothing to do with DTML - it's a basic issue with HTML, which is that it ignores whitespace. If you want to preserve it, you need to wrap the content with <pre>.\n<pre><dtml-var public_blast_results></pre>\n\n" ]
[ 2 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003206812_html_python.txt
Q: PyCrypto and GMP library not found error [Mac OS 10.6.3] I'm trying to install pycrypto-2.1.0 but attempt to do with 'python setup.py build' elicits: running build running build_py running build_ext warning: GMP library not found; Not building Crypto.PublicKey._fastmath. I installed GMP (gmp-4.3.2) and it's in: /...
PyCrypto and GMP library not found error [Mac OS 10.6.3]
I'm trying to install pycrypto-2.1.0 but attempt to do with 'python setup.py build' elicits: running build running build_py running build_ext warning: GMP library not found; Not building Crypto.PublicKey._fastmath. I installed GMP (gmp-4.3.2) and it's in: /usr/local/lib How do I get python/pycrypto to recognize that G...
[ "Looking at setup.py for pycrypto, it only searches for GMP in /lib and /usr/lib. To fix this, either change setup.py to also search /usr/local/lib by adding it to the list on line 155 (recommended), or reinstall GMP into /lib or /usr/lib (not recommended but would work).\nYou may also need to add self.__add_compi...
[ 3, 3, 2, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002709661_macos_python.txt
Q: AdaBoost ML algorithm python implementation Is there anyone that has some ideas on how to implement the AdaBoost (Boostexter) algorithm in python? Cheers! A: It looks as if the sdpy project has an AdaBoost implementation. Specifically look at the sdpy/cs/ml/cla/boosting.py file. Perhaps you can get some motivati...
AdaBoost ML algorithm python implementation
Is there anyone that has some ideas on how to implement the AdaBoost (Boostexter) algorithm in python? Cheers!
[ "It looks as if the sdpy project has an AdaBoost implementation. Specifically look at the sdpy/cs/ml/cla/boosting.py file.\nPerhaps you can get some motivation from there.\n", "Thanks a million Steve! In fact, your suggestion had some compatibility issues with MacOSX (a particular library was incompatible with th...
[ 3, 2 ]
[]
[]
[ "adaboost", "machine_learning", "python" ]
stackoverflow_0003193756_adaboost_machine_learning_python.txt
Q: Caching the results of a function with two parameters in Python I have a method with two parameters that does some complex computation. It is called very often with the same parameters, so I am using a dictionary for caching. Currently this looks something like this: def foo(self, a, b): params = frozenset([a,...
Caching the results of a function with two parameters in Python
I have a method with two parameters that does some complex computation. It is called very often with the same parameters, so I am using a dictionary for caching. Currently this looks something like this: def foo(self, a, b): params = frozenset([a, b]) if not params in self._cache: self._cache[params] = ...
[ "There's nothing particularly inefficient or complicated about how you implemented your caching; that's essentially what needs to happen. It isn't very general, however.\nYou can implement some sort of more generalized caching strategy, using decorators if you like, for convenience. One possible approach might be...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "caching", "python" ]
stackoverflow_0003207253_caching_python.txt
Q: Email to HTML in Python I am looking for a library which can take a raw email message and convert it to appropriate HTML in Python. Any help will be appreciated. A: Use the MIME package included in email http://docs.python.org/library/email Here some examples http://docs.python.org/library/email-examples.html A...
Email to HTML in Python
I am looking for a library which can take a raw email message and convert it to appropriate HTML in Python. Any help will be appreciated.
[ "Use the MIME package included in email\nhttp://docs.python.org/library/email\nHere some examples http://docs.python.org/library/email-examples.html\n", "Here's some Python code to convert text to HTML\n", "You have two choices, \nIf the email has a HTML payload, you can use that - maybe put a simple template t...
[ 1, 0, 0 ]
[]
[]
[ "email", "html", "python" ]
stackoverflow_0003206371_email_html_python.txt
Q: question about splitting a large file Hey I need to split a large file in python into smaller files that contain only specific lines. How do I do this? A: You're probably going to want to do something like this: big_file = open('big_file', 'r') small_file1 = open('small_file1', 'w') small_file2 = open('small_fil...
question about splitting a large file
Hey I need to split a large file in python into smaller files that contain only specific lines. How do I do this?
[ "You're probably going to want to do something like this:\nbig_file = open('big_file', 'r')\nsmall_file1 = open('small_file1', 'w')\nsmall_file2 = open('small_file2', 'w')\n\nfor line in big_file:\n if 'Charlie' in line: small_file1.write(line)\n if 'Mark' in line: small_file2.write(line)\n\nbig_file.close()\...
[ 5, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003207719_python.txt
Q: python: access multiple values in the value portion of a key:value pair I am trying to perform a calculation on multiple values in the value portion of a list of key:value pairs. So I have something like: [('apples', ['254', '234', '23', '33']), ('bananas', ['732', '28']), ('squash', ['3'])] I'm trying to create a...
python: access multiple values in the value portion of a key:value pair
I am trying to perform a calculation on multiple values in the value portion of a list of key:value pairs. So I have something like: [('apples', ['254', '234', '23', '33']), ('bananas', ['732', '28']), ('squash', ['3'])] I'm trying to create a list of y-values that are the averages of those integers above. What I'm t...
[ "Where pairs is your list of pairs:\naverages = [float(sum(values)) / len(values) for key, values in pairs]\n\nwill give you a list of average values.\nIf your numbers are strings, as in your example, replace sum(values) above with sum([int(i) for i in values]).\nEDIT: And if you rather want a dictionary then a lis...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "key_value", "python" ]
stackoverflow_0003208076_dictionary_key_value_python.txt
Q: Regex to match Domain.CCTLD Does anyone know a regular expression to match Domain.CCTLD? I don't want subdomains, only the "atomic domain". For example, docs.google.com doesn't get matched, but google.com does. However, this gets complicated with stuff like .co.uk, CCTLDs. Does anyone know a solution? Thanks in ad...
Regex to match Domain.CCTLD
Does anyone know a regular expression to match Domain.CCTLD? I don't want subdomains, only the "atomic domain". For example, docs.google.com doesn't get matched, but google.com does. However, this gets complicated with stuff like .co.uk, CCTLDs. Does anyone know a solution? Thanks in advance. EDIT: I've realized I also...
[ "It sounds like you are looking for the information available through the Public Suffix List project. \n\nA \"public suffix\" is one under which Internet users can directly register names. Some examples of public suffixes are \".com\", \".co.uk\" and \"pvt.k12.wy.us\". The Public Suffix List is a list of all known ...
[ 8, 3, 2 ]
[]
[]
[ "dns", "python", "regex", "subdomain", "tld" ]
stackoverflow_0003199343_dns_python_regex_subdomain_tld.txt
Q: Nested exceptions? Will this work? try: try: field.value = filter(field.value, fields=self.fields, form=self, field=field) except TypeError: field.value = filter(field.value) except ValidationError, e: field.errors += e.args field.value = revert valid = False break ...
Nested exceptions?
Will this work? try: try: field.value = filter(field.value, fields=self.fields, form=self, field=field) except TypeError: field.value = filter(field.value) except ValidationError, e: field.errors += e.args field.value = revert valid = False break Namely, if that fi...
[ "If the filter statement in the inner try raises an exception, it will first get checked against the inner set of \"except\" statements and then if none of those catch it, it will be checked against the outer set of \"except\" statements. \nYou can convince yourself this is the case just by doing something simple ...
[ 25, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003208566_python.txt
Q: Get Mac idle time C or Python How can i get system idle time (no keys pressed - mouse moved) in C or Python? EDIT: My program suspend a counter when idle time > 10 sec A: I don't have a Mac to test on at the moment, so cannot confirm this works, but this thread seems to offer the solution you're looking for: htt...
Get Mac idle time C or Python
How can i get system idle time (no keys pressed - mouse moved) in C or Python? EDIT: My program suspend a counter when idle time > 10 sec
[ "I don't have a Mac to test on at the moment, so cannot confirm this works, but this thread seems to offer the solution you're looking for:\nhttp://www.dssw.co.uk/sleepcentre/threads/system_idle_time_how_to_retrieve.html\nIn a nutshell, use the subprocess module and call:\nioreg -c IOHIDSystem\n\nThen parse the out...
[ 3, 0, 0, 0 ]
[]
[]
[ "c", "macos", "python", "python_idle" ]
stackoverflow_0003208450_c_macos_python_python_idle.txt
Q: Suggest category for a piece of text I've been searching for a opensource solution to suggest a category given a question or text. For example, "who is Lady Gaga?" would probably return 'Entertainment', 'Music', or 'Celebrity'. "How many strike out there are for baseball?" would give me 'Baseball', or 'Sport'. The...
Suggest category for a piece of text
I've been searching for a opensource solution to suggest a category given a question or text. For example, "who is Lady Gaga?" would probably return 'Entertainment', 'Music', or 'Celebrity'. "How many strike out there are for baseball?" would give me 'Baseball', or 'Sport'. The categorization doesn't have to be perfect...
[ "This is a document classification problem - your \"document\" is simply the query or text. \nYou'll first need to decide what the list of possible categories is. \"Who is Lady Gaga?\" could be Entertainment, Celebrity, Questions-In-English, Biography, People, etc. Next you'll apply a decision framework to assign a...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003208398_python.txt
Q: additional python installed upon installing matplotlib with macports I am having trouble installing matplotlib on mac os 10.6, so I used macports and installed all dependencies it needed, which is great, but on top of it a new python version. Now I have two python versions and that bothers me. The matplotlib is wo...
additional python installed upon installing matplotlib with macports
I am having trouble installing matplotlib on mac os 10.6, so I used macports and installed all dependencies it needed, which is great, but on top of it a new python version. Now I have two python versions and that bothers me. The matplotlib is working fine on the macport python, and the rest of my stuff is with the def...
[ "You should never remove or alter the system Python that Apple supplies with Mac OS X -- that's the specific build they've tested their OS with, and you really don't want to break that.\nIf you want to use handy macports-installed extensions, you need the macports version of Python for that purpose, so you can't re...
[ 1 ]
[]
[]
[ "macports", "matplotlib", "python" ]
stackoverflow_0003208803_macports_matplotlib_python.txt