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 subtracting floats I have the following code embeded in a class.Whenever I run distToPoint it gives the error 'unsupported operand type(s) for -: 'NoneType' and 'float'' I don't know why it's returning with NoneType and how do I get the subtraction to work? Both self and p are supposed to be pairs. def __in...
Python subtracting floats
I have the following code embeded in a class.Whenever I run distToPoint it gives the error 'unsupported operand type(s) for -: 'NoneType' and 'float'' I don't know why it's returning with NoneType and how do I get the subtraction to work? Both self and p are supposed to be pairs. def __init__(self, x, y): self.x = ...
[ "You should check what value of p you are sending to the function, so that it has an x and y that are floats.\nOld post (on second thought, I don't think you were trying to use distToPoint this way):\ndistToPoint doesn't return a value, this is probably the problem.\n", "For sake of comparison,\nimport math\n\ncl...
[ 1, 1 ]
[]
[]
[ "class", "floating_point", "python", "subtraction" ]
stackoverflow_0005615764_class_floating_point_python_subtraction.txt
Q: Python using Beautiful Soup for HTML processing on specific content So when I decided to parse content from a website. For example, http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx I want to parse the ingredients into a text file. The ingredients are located in: < div class="ingredients" sty...
Python using Beautiful Soup for HTML processing on specific content
So when I decided to parse content from a website. For example, http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx I want to parse the ingredients into a text file. The ingredients are located in: < div class="ingredients" style="margin-top: 10px;"> and within this, each ingredient is stored betwe...
[ "import urllib2\nimport BeautifulSoup\n\ndef main():\n url = \"http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx\"\n data = urllib2.urlopen(url).read()\n bs = BeautifulSoup.BeautifulSoup(data)\n\n ingreds = bs.find('div', {'class': 'ingredients'})\n ingreds = [s.getText().strip() for...
[ 4, 2 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python" ]
stackoverflow_0005615647_beautifulsoup_html_parsing_python.txt
Q: Get charset attribute of meta element in (X)HTML document with xpath I am doing some web scraping stuff with python. But as you know some web pages has different charsets. I need to get those web pages charset. So long story short, for lxml, What is xpath pattern? Thank you. A: This: /html/head/meta[@http-equiv=...
Get charset attribute of meta element in (X)HTML document with xpath
I am doing some web scraping stuff with python. But as you know some web pages has different charsets. I need to get those web pages charset. So long story short, for lxml, What is xpath pattern? Thank you.
[ "This:\n/html/head/meta[@http-equiv='Content-Type']/@content\n\nHTML5:\n/html/head/meta/@charset\n\n" ]
[ 3 ]
[]
[]
[ "lxml", "python", "xpath" ]
stackoverflow_0005615848_lxml_python_xpath.txt
Q: Regular Expressions in Python - match all that does not contain... (App Engine) Just started using App Engine's webapp framework, but I can't figure out what's wrong with this: My URL structure is set up to where any pages are prefixed with /x/ . For example.. http://site.com/x/my_account http://site.com/x/profil...
Regular Expressions in Python - match all that does not contain... (App Engine)
Just started using App Engine's webapp framework, but I can't figure out what's wrong with this: My URL structure is set up to where any pages are prefixed with /x/ . For example.. http://site.com/x/my_account http://site.com/x/profile http://site.com/x/admin etc etc.... Now I want to be able to match NOT prefixed wi...
[ "It should be like this: '^/(?!x/|x$).*$'\n", "URLs are matched in order, from first to last. Simply add a .* regular expression after all URL patterns that match /x.\n" ]
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python", "regex" ]
stackoverflow_0005608508_google_app_engine_python_regex.txt
Q: For-loop over several variables from a single list I'm trying to create a loop like this newList = [a + b for a,b in list[::2], list[1::2]] meaning, take two consecutive entries from a list, do something with them and put the into a new list. How would that work? A: You want to zip your two newly created lists...
For-loop over several variables from a single list
I'm trying to create a loop like this newList = [a + b for a,b in list[::2], list[1::2]] meaning, take two consecutive entries from a list, do something with them and put the into a new list. How would that work?
[ "You want to zip your two newly created lists:\nnewList = [a + b for a,b in zip(list[::2], list[1::2])]\n\nYou also do this in a somewhat more memory-efficient manner by using an iterator:\nit = iter(list)\nnewList = [a + b for a, b in zip(it, it)]\n\nor even more efficiently* by using the izip function, which retu...
[ 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005615898_python.txt
Q: Do I need Google App Engine to make and run a Facebook App? I set up the Google App Engine on my computer to work with Python , so I could make my first "Hello World" App at http://localhost:8080/. In the developers section of facebook it says I need Google App Engine and Python to test an app. But my question i...
Do I need Google App Engine to make and run a Facebook App?
I set up the Google App Engine on my computer to work with Python , so I could make my first "Hello World" App at http://localhost:8080/. In the developers section of facebook it says I need Google App Engine and Python to test an app. But my question is, can I just host the files(the .yaml and the .py) on my server ...
[ "You do not specifically need Google app engine, that i believe is just a sample app. The main thing that you need is a globally accessible web server. So that FB can reach your pages/application from their servers. So depending on the language, get a small/free hosting account and test your application from there....
[ 5, 3 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0005615868_facebook_google_app_engine_python.txt
Q: Write a python Client to pass xs:anyType argument to a webservice method in Java I have written a small webservice[Axis2/Java] which exposes a method public String Fill(String cacheName Object... varArgs) { return "Sample return "+varArgs[0].toString()+" "+(new Integer(varArgs[1])); } My client is ...
Write a python Client to pass xs:anyType argument to a webservice method in Java
I have written a small webservice[Axis2/Java] which exposes a method public String Fill(String cacheName Object... varArgs) { return "Sample return "+varArgs[0].toString()+" "+(new Integer(varArgs[1])); } My client is a python suds client. import suds; import suds.client; url="http://localhost:8989/p...
[ "Have you tried passing your varArgs as a python list? See if something like this works:\nclient.service.Fill(\"level1\",[\"Immediate\",123123])\n\n", "The problem is at the axis2 side. The Axis2 is unable to deserialize Object and mistakes it as a DataHandler. I have decided to pass in my Object as OMElement an...
[ 0, 0 ]
[]
[]
[ "axis2", "java", "python", "suds", "web_services" ]
stackoverflow_0005374972_axis2_java_python_suds_web_services.txt
Q: What does this syntax mean in Python? What does the comma in the declaration below mean? Does it define two variables at once? resp, content = client.request(request_token_url, "GET") A: It creates a tuple. In this case, the tuple is of two variables, which get assigned the result from request(). request() retur...
What does this syntax mean in Python?
What does the comma in the declaration below mean? Does it define two variables at once? resp, content = client.request(request_token_url, "GET")
[ "It creates a tuple. In this case, the tuple is of two variables, which get assigned the result from request().\nrequest() returns a tuple, which is then automatically unpacked into the left-hand tuple during assignment.\nIf you had just\nresult = client.request(request_token_url, \"GET\")\n\nthat would assign the ...
[ 4, 2 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0005616377_python_syntax.txt
Q: Methods decorated with a decorator class do not have the "self" argument frozen I have a decorator declared as a class: class predicated(object): def __init__(self, fn): self.fn = fn self.fpred = lambda *args, **kwargs: True def predicate(self, predicate): self.fpred = predicate ...
Methods decorated with a decorator class do not have the "self" argument frozen
I have a decorator declared as a class: class predicated(object): def __init__(self, fn): self.fn = fn self.fpred = lambda *args, **kwargs: True def predicate(self, predicate): self.fpred = predicate return self def validate(self, *args, **kwargs): return self.fpred...
[ "Figured it out - needed to define a __get__ method in order to create a MethodType binding like so:\ndef __get__(self, obj, objtype=None):\n return MethodType(self, obj, objtype)\n\nwhich creates a MethodType object when invoking the method on an object that freezes the self argument.\n" ]
[ 4 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0005616409_decorator_python.txt
Q: file upload with django I am newbie working with django, I am trying to create a form that permits the user to upload a file. The code I used is pretty much the same as from the djangoproject tutorial but it didn't work. my code is as follows: for views: from django import forms from django.shortcuts import rend...
file upload with django
I am newbie working with django, I am trying to create a form that permits the user to upload a file. The code I used is pretty much the same as from the djangoproject tutorial but it didn't work. my code is as follows: for views: from django import forms from django.shortcuts import render_to_response from django.h...
[ "Make sure that your form follows these rules http://docs.djangoproject.com/en/1.2/ref/forms/api/#binding-uploaded-files-to-a-form\n", "The error is a simple python error. UploadFileForm is not defined\nAccording to what you've pasted, you've only imported stuff from django.\nYou have to import your UploadFileFor...
[ 1, 1, 1 ]
[]
[]
[ "django", "file_upload", "python" ]
stackoverflow_0005615577_django_file_upload_python.txt
Q: Does python's setuptools support the `__name__ == "__main__"` style of execution? I'm just getting into packaging with setuptools, and it seems that the recommended way to install a python script along with one's module is to specify a script name that calls the name of a function, like this: setup( # ... ...
Does python's setuptools support the `__name__ == "__main__"` style of execution?
I'm just getting into packaging with setuptools, and it seems that the recommended way to install a python script along with one's module is to specify a script name that calls the name of a function, like this: setup( # ... entry_points = { "console_scripts": [ "script_name": "project.main:...
[ "It is: \"script_name = project.main:do_stuff with setuptools\nSetuptools creates scripts named script_name that imports and runs the function project.main:do_stuff, not run the script directly. You should re-read this part (alternate link, if you use Distribute) of the setuptools docs again to understand why it'...
[ 9 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0005615292_python_setuptools.txt
Q: Django NoReverseMatch Error in blog tutorial modification I just did the Django blog tutorial found here: Blog tutorial I am now trying to add a functionality that will count the number of views a blog post has received. To do that I added the following to views.py (note that views.py is completely empty in the tu...
Django NoReverseMatch Error in blog tutorial modification
I just did the Django blog tutorial found here: Blog tutorial I am now trying to add a functionality that will count the number of views a blog post has received. To do that I added the following to views.py (note that views.py is completely empty in the tutorial because it uses Django generic views): def detail_view(r...
[ "Try:\n<a href=\"{% url post object_id=object.id %}\">{{ object.title }}</a>\n\nYou need to provide the name for the parameter to make the reverse happy. Also, you should quote the URL.\nP.S. Your original code would have worked if your URL entry was:\nurl('^(\\d+)/$', 'posts.views.detail_view', name=\"post\")\n\nb...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005616774_django_python.txt
Q: Django: how to serve user-submitted images & thumbnails from separate, multiple servers? For my Django site, I'd like to: Accept images submitted by users Generate thumbnails from those images Put both the original images and the thumbnails onto separate, multiple servers that are dedicated to serving images I n...
Django: how to serve user-submitted images & thumbnails from separate, multiple servers?
For my Django site, I'd like to: Accept images submitted by users Generate thumbnails from those images Put both the original images and the thumbnails onto separate, multiple servers that are dedicated to serving images I need multiple, separate servers to serve the images/thumbnails to ensure I have enough IO perfo...
[ "This sounds like a job for distributed task queues. My personal favorite is Beanstalkd b/c it is so lightweight and easy to use. \nServer: https://github.com/kr/beanstalkd\nClient Library: https://github.com/PeterScott/beanstalkc\nDjango Helper: https://github.com/jonasvp/django-beanstalkd \nThe way it would work ...
[ 4 ]
[]
[]
[ "django", "file_upload", "infrastructure", "python", "thumbnails" ]
stackoverflow_0005615654_django_file_upload_infrastructure_python_thumbnails.txt
Q: Mid-line comment in Python? I'm wondering if there is any way to comment out part of a line, like you can do in c++ with /*this*/. The only comments I know about are # this which always goes to the end of the line and the """these""" ones, which do not work mid-line. Example use-case: using subprocess and need ...
Mid-line comment in Python?
I'm wondering if there is any way to comment out part of a line, like you can do in c++ with /*this*/. The only comments I know about are # this which always goes to the end of the line and the """these""" ones, which do not work mid-line. Example use-case: using subprocess and need to temporarily comment out an arg...
[ "Actually if you break your statement into multiple lines you can.\nSomething like:\n['../some/guy', '-m', '10',\n# '-p', '0',\n '-n', '100', '-f', '/dev/stdout']\n\nshould work.\n", "You are correct, the answer is a big fat NO.\n" ]
[ 77, 66 ]
[]
[]
[ "comments", "python", "syntax" ]
stackoverflow_0005617159_comments_python_syntax.txt
Q: FB not defined Error on implementing Facebook logout in Django app I was trying to implement facebook logout functionality for my django app. In my app, users can log in using app username or with FB username. Now i want to implement logout functionality also. For doing that i put this code in my html page, but i ...
FB not defined Error on implementing Facebook logout in Django app
I was trying to implement facebook logout functionality for my django app. In my app, users can log in using app username or with FB username. Now i want to implement logout functionality also. For doing that i put this code in my html page, but i am getting 'FB is not defined' error. Can somebody help me to solve this...
[ "i got it working with this \n<a href=\"http://m.facebook.com/logout.php?confirm=1&next=http://10.1.0.90:8080/registrationForm\" >Sign Out</a> \n\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "html", "javascript", "python" ]
stackoverflow_0005580002_django_facebook_html_javascript_python.txt
Q: Implementing Facebook logout functionality for Django App I have created a django app where users can be looged in with both django app username or facebook username. Now i want to implement a logout functionality while logging in through facebook . Can somebody help me to do this.Please help me to find any tutori...
Implementing Facebook logout functionality for Django App
I have created a django app where users can be looged in with both django app username or facebook username. Now i want to implement a logout functionality while logging in through facebook . Can somebody help me to do this.Please help me to find any tutorials which explains these. I will paste my code here. html face...
[ "this is a tutorial for RoR but the concepts are the same ...\nhttp://madebymany.com/blog/tutorial-for-restful-authentication-on-rails-with-facebook-connect-in-15-minutes\n", "i got it working with this\n<a href=\"http://m.facebook.com/logout.php?confirm=1&next=http://10.1.0.90:8080/registrationForm\" >Sign Out<...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "facebook", "python" ]
stackoverflow_0005578500_django_django_models_facebook_python.txt
Q: setting call back url for facebook login in django app i have created a django app, which has a facebook login option also. For doing it i was following this link django-facebook connect with ajax. I did everything as said by the link, and i am getting the user signed in with facebook connect. But after the user l...
setting call back url for facebook login in django app
i have created a django app, which has a facebook login option also. For doing it i was following this link django-facebook connect with ajax. I did everything as said by the link, and i am getting the user signed in with facebook connect. But after the user logs in from 'registrationForm'(FB log in button given) page,...
[ "i got it working..the call back url is set at the facebook app settings.\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "facebook_graph_api", "python" ]
stackoverflow_0005564620_django_facebook_facebook_graph_api_python.txt
Q: Using celery/RabbitMQ (queues) hitting APIs in Django Request/Response cycle I am working on a product, that requires crawling APIs and computing and returning results. I am currently using Django as product. I had a detailed look at Documentation of Celery and RabbitMQ and queues in general. What I want to achi...
Using celery/RabbitMQ (queues) hitting APIs in Django Request/Response cycle
I am working on a product, that requires crawling APIs and computing and returning results. I am currently using Django as product. I had a detailed look at Documentation of Celery and RabbitMQ and queues in general. What I want to achieve is: 1. Monitoring / administration of each API called for different vendor. 2...
[ "I've used Beanstalk for a while now with great success. \nServer: https://github.com/kr/beanstalkd\nClient Library: https://github.com/PeterScott/beanstalkc\nDjango Helper: https://github.com/jonasvp/django-beanstalkd\nDjango Admin App: https://github.com/humanfromearth/django-beanstalk \nI think Beanstalk has man...
[ 1 ]
[]
[]
[ "celery", "django", "message_queue", "python", "rabbitmq" ]
stackoverflow_0005429955_celery_django_message_queue_python_rabbitmq.txt
Q: How to enable caching with GAE I want to enable public caching with google app engine. I've got the following response where performance significantly increased when starting to use the Cache-Control: HTTP/1.0 200 OK => Cache-Control => public,max-age=86400 Content-Type => application/vnd.google-earth.kml+xml Expi...
How to enable caching with GAE
I want to enable public caching with google app engine. I've got the following response where performance significantly increased when starting to use the Cache-Control: HTTP/1.0 200 OK => Cache-Control => public,max-age=86400 Content-Type => application/vnd.google-earth.kml+xml Expires => Thu, 01 Dec 1994 16:00:00 GMT...
[ "Yes, this enables caching - though you shouldn't be setting an expires header yourself at all unless it's accurate - just set the max-age, and let the caches and/or browser to determine the expiry date.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "header", "http_headers", "python" ]
stackoverflow_0005617322_google_app_engine_header_http_headers_python.txt
Q: Removing every occurrence of some value from a Python list? This is my code: a = [1,2,3,43,43,43] count = a.count(43) if count > 0: for i in range(count): a.remove(43) print a Is there a simpler way to achieve this? A: Try a = [x for x in a if x != 43] A: Try itertools: >>> import itertools >>>...
Removing every occurrence of some value from a Python list?
This is my code: a = [1,2,3,43,43,43] count = a.count(43) if count > 0: for i in range(count): a.remove(43) print a Is there a simpler way to achieve this?
[ "Try\na = [x for x in a if x != 43] \n\n", "Try itertools:\n>>> import itertools\n>>> a = [1, 2, 3, 43, 43, 45]\n>>> iter = itertools.ifilter(lambda x: x != 43, a)\n>>> list(iter)\n[1, 2, 3]\n\n", "Note that all the solutions above (except the one using remove, but that one has non linear execution time) will c...
[ 8, 3, 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005617547_list_python.txt
Q: python and DB connection abstraction? Is there some module to allow for easy DB provider configuration via connection string, similar to PHP's PDO where I can nicely say "psql://" or "mysql://" or, in this python project, am I just going to have to code some factory classes that use MySQLdb, psycopg2, etc? A: ht...
python and DB connection abstraction?
Is there some module to allow for easy DB provider configuration via connection string, similar to PHP's PDO where I can nicely say "psql://" or "mysql://" or, in this python project, am I just going to have to code some factory classes that use MySQLdb, psycopg2, etc?
[ "http://www.sqlalchemy.org/docs/core/connections.html\n", "There's something not quite as nice in logilab.database, but which works quite well (http://www.logilab.org/project/logilab-database). Supports sqlite, mysql, postgresql and some versions of mssql, and some abstraction mechanisms on the SQL understood by ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005617246_python.txt
Q: How to send data generated from python to jquery datatable for rendering A] Summary of the problem: Using jquery datatable (http://www.datatables.net/) on the html page, Want to send data generated by query from python to javascript, so that it can be printed in the table. If someone can provide a sample implement...
How to send data generated from python to jquery datatable for rendering
A] Summary of the problem: Using jquery datatable (http://www.datatables.net/) on the html page, Want to send data generated by query from python to javascript, so that it can be printed in the table. If someone can provide a sample implementation for this or a starter link, it would be awesome. B] Models structure: Th...
[ "In the DataTables documentation, they show an example of returning data \"server-side\". In their example they are using PHP on the server, but how it's returned is by encoding with JSON. This is easily done with Python as well.\nEDITS\nThe key is how the data is returned from the server:\n$(document).ready(func...
[ 2, 2 ]
[]
[]
[ "datatable", "google_app_engine", "jquery", "python" ]
stackoverflow_0005615110_datatable_google_app_engine_jquery_python.txt
Q: Why is this program faster in Python than Objective-C? I got interested in this small example of an algorithm in Python for looping through a large word list. I am writing a few "tools" that will allow my to slice a Objective-C string or array in a similar fashion as Python. Specifically, this elegant solution ca...
Why is this program faster in Python than Objective-C?
I got interested in this small example of an algorithm in Python for looping through a large word list. I am writing a few "tools" that will allow my to slice a Objective-C string or array in a similar fashion as Python. Specifically, this elegant solution caught my attention for executing very quickly and it uses a s...
[ "Keep in mind that the Python version has been written to move a lot of the heavy lifting down into highly optimised C code when executed on CPython (especially the file input buffering, string slicing and the hash table lookups to check whether even and odd are in words).\nThat said, you seem to be decoding the fi...
[ 9, 2, 2, 1, 0 ]
[]
[]
[ "nsstring", "objective_c", "python" ]
stackoverflow_0005616847_nsstring_objective_c_python.txt
Q: 404 error with python on apache2 I have a file test.py at /var/www and I am using apache2 on ubuntu 10.10. I have mod_python installed and /etc/apache2/sites-available/default configured as <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride AuthConfig Order allow,deny al...
404 error with python on apache2
I have a file test.py at /var/www and I am using apache2 on ubuntu 10.10. I have mod_python installed and /etc/apache2/sites-available/default configured as <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride AuthConfig Order allow,deny allow from all AddHandler mod_pytho...
[ "mod_python looks for method def index(req) by default when it tries to handle your requests, otherwise you can specify the function which you want to call in the URL. Note that function has to return a specific value.\nSo you can do something like\ns =\"\"\"\\\n<html>\n<body>\n<h2>Hello World!</h2>\n</body>\n</ht...
[ 2, 1 ]
[]
[]
[ "apache2", "python" ]
stackoverflow_0005617897_apache2_python.txt
Q: dll load error in python due to insufficient stack size? I have a python code which imports dll's created by f2py (from fortran routines). Now the python program crashes if the arrays in fortran are too large. How do I manage with this? By increasing stack size? Or heap? I've tried to study the matter, but I still...
dll load error in python due to insufficient stack size?
I have a python code which imports dll's created by f2py (from fortran routines). Now the python program crashes if the arrays in fortran are too large. How do I manage with this? By increasing stack size? Or heap? I've tried to study the matter, but I still do not understand how I can increase the stack or should I us...
[ "Your basic problem is that you are storing large arrays of data on the stack. This is bad design and is probably due to the way the Fortran code is implemented.\nLarge arrays need to be stored on the heap and dynamically allocated there. To solve this problem you will need to understand and modify your Fortran co...
[ 2, 1 ]
[]
[]
[ "fortran", "python" ]
stackoverflow_0005617641_fortran_python.txt
Q: comparing int float python problem I have this code: def fit(self,p1,p2,w): p=p1 m=self.bit(p,w) if p1.y!=p2.y: if m&0x30: p.y=w.y1 if m&0x10 else w.y2-1 try: p.x=int((p.y-p2.y)*(p1.x-p2.x)/(p1.y-p2.y)+p2.x) except Exception,e: ...
comparing int float python problem
I have this code: def fit(self,p1,p2,w): p=p1 m=self.bit(p,w) if p1.y!=p2.y: if m&0x30: p.y=w.y1 if m&0x10 else w.y2-1 try: p.x=int((p.y-p2.y)*(p1.x-p2.x)/(p1.y-p2.y)+p2.x) except Exception,e: print e print p1.y!...
[ "You are dividing 0/0!\n# (p.y-p2.y)*(p1.x-p2.x)\nx = p.y - p2.y\nx = 199 - 199.0 = 0\nx1 = p1.x-p2.x\n0 * x1 = 0* p1.x - 0* p2.x\n\nThis means \n(p.y-p2.y)*(p1.x-p2.x) = 0\n\nNow we are devising 0 by this:\n#(p1.y-p2.y)\np1.y-p2.y\nx = p.y - p2.y\nx = 199 - 199.0 = 0\n\nSo in this case you are trying to do 0/0\nTh...
[ 1 ]
[]
[]
[ "divide_by_zero", "python" ]
stackoverflow_0005616628_divide_by_zero_python.txt
Q: Python network programming project? I was wondering if you guys know any websites or have any ideas on beginner-intermediate level Python network programming projects/practice problems to practice Python network programming? I just finished reading "Foundations of Python Network Programming" and am looking for pra...
Python network programming project?
I was wondering if you guys know any websites or have any ideas on beginner-intermediate level Python network programming projects/practice problems to practice Python network programming? I just finished reading "Foundations of Python Network Programming" and am looking for practice assignments that aren't too difficu...
[ "My first Python networking project was to write a GUI chat client for the NFC Chat server https://sourceforge.net/projects/nfcchat/. This was 5-6 years ago - so I'm not sure how much the project has changed.... But the command set was very IRC-ish. It's not even necessary to dive into the Java codebase to figure...
[ 0, 0 ]
[]
[]
[ "networking", "project", "python" ]
stackoverflow_0005083701_networking_project_python.txt
Q: Django request.user is empty Using django, I am authenticating the user through Google. I get the initial request tokens & redirect the user to google for auth. After which google redirects the user back to my website (using the redirect_url I provide). At this point the request.user.id is None so is request.user....
Django request.user is empty
Using django, I am authenticating the user through Google. I get the initial request tokens & redirect the user to google for auth. After which google redirects the user back to my website (using the redirect_url I provide). At this point the request.user.id is None so is request.user.username why is this happening? I ...
[ "If you are using oauth api from google. To get the user you have to do something like this\nfrom google.appengine.api import oauth\n\n# ...\n try:\n # Get the db.User that represents the user on whose behalf the\n # consumer is making this request.\n user = oauth.get_current...
[ 1, 1 ]
[]
[]
[ "django", "django_authentication", "django_validation", "django_views", "python" ]
stackoverflow_0005497509_django_django_authentication_django_validation_django_views_python.txt
Q: pygtk: how to manually emit signal I have an gtk.Entry() object, and I would like to manually emit the focus-out-event. What is the second parameter that I need to pass to the emit method? In [10]: d.emit('focus-out-event') TypeError: 1 parameters needed for signal focus-out-event; 0 given In [11]: d.emit('focus-...
pygtk: how to manually emit signal
I have an gtk.Entry() object, and I would like to manually emit the focus-out-event. What is the second parameter that I need to pass to the emit method? In [10]: d.emit('focus-out-event') TypeError: 1 parameters needed for signal focus-out-event; 0 given In [11]: d.emit('focus-out-event', d) TypeError: could not conv...
[ "You need a gtk.gdk.Event as the second parameter.\nHere's how you create one: (disclaimer, I didn't test this)\nevent = gtk.gdk.Event(gtk.gdk.FOCUS_CHANGE)\nevent.window = entry.get_window() # the gtk.gdk.Window of the widget\nevent.send_event = True # this means you sent the event explicitly\nevent.in_ = False ...
[ 5 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0005614144_gtk_pygtk_python.txt
Q: How should I read and write a file format using 1 definition? I want to modify quicktime files, so I'm working with quicktime.py but it only parses information. It doesn't know how to write/modify things. In C, struct records are actually very powerful - you get 4 things for the cost of 1 readable definition: Def...
How should I read and write a file format using 1 definition?
I want to modify quicktime files, so I'm working with quicktime.py but it only parses information. It doesn't know how to write/modify things. In C, struct records are actually very powerful - you get 4 things for the cost of 1 readable definition: Define names for each variable. Define serializable types and order fo...
[ "Maybe try Hachoir ?\n", "Try Construct, it does exactly what you want.\n" ]
[ 2, 2 ]
[]
[]
[ "binary", "parsing", "python", "serialization" ]
stackoverflow_0005618471_binary_parsing_python_serialization.txt
Q: Django AJAX increment I am simply trying to create a button or link in Django that when clicked will increment a model.IntegerField, but so far have been awfully confused. I understand that I must AJAX-ify this process. I tried using Dajaxice but ended up running into many troubles. What is the accepted way to do...
Django AJAX increment
I am simply trying to create a button or link in Django that when clicked will increment a model.IntegerField, but so far have been awfully confused. I understand that I must AJAX-ify this process. I tried using Dajaxice but ended up running into many troubles. What is the accepted way to do this? Thanks! So far I'm j...
[ "Remember to do it atomicly:\n# models.py\nclass Page(models.Model):\n hits = models.PositiveIntegerField()\n\n# views.py\ndef hit(request, page_pk):\n Page.objects.filter(pk=page_pk).update(hits=F('hits')+1)\n return HttpResponse()\n\n…or use a transaction:\n# views.py\nfrom django.db.decorators import co...
[ 2 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0005618739_ajax_django_python.txt
Q: How to convert list to string How can I convert a list to a string using Python? A: Use ''.join: xs = ['1', '2', '3'] s = ''.join(xs) If the list contains integers, convert the elements to string before joining them: xs = [1, 2, 3] s = ''.join(str(x) for x in xs) A: >>> xs = [1, 2, 3] >>> " ".join(str(...
How to convert list to string
How can I convert a list to a string using Python?
[ "Use ''.join:\nxs = ['1', '2', '3']\ns = ''.join(xs)\n\n\nIf the list contains integers, convert the elements to string before joining them:\nxs = [1, 2, 3]\ns = ''.join(str(x) for x in xs)\n\n", ">>> xs = [1, 2, 3] \n>>> \" \".join(str(x) for x in xs)\n'1 2 3'\n\n", "xs = ['L', 'O', 'L']\nlol_string = ''...
[ 1852, 411, 123 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0005618878_list_python_string.txt
Q: Django NameError during ManyToMany field referencing I am having a table named PlayCat. which basically stores al the category names of playful activities. such as disco,pool n stuff. So i want these categories to b referenced(ManyToMany) when a user creates a Play arena where he/she can select al the categories i...
Django NameError during ManyToMany field referencing
I am having a table named PlayCat. which basically stores al the category names of playful activities. such as disco,pool n stuff. So i want these categories to b referenced(ManyToMany) when a user creates a Play arena where he/she can select al the categories it belongs to. Play : class Play(models.Model): shopname...
[ "I guess it's because you have a model PlayCat defined after a model Play. So it can't resolve it.\nYou can either put model PlayCat before Play or use a string for reference\ncategory = models.ManyToManyField('PlayCat')\n\n" ]
[ 15 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0005618720_django_django_models_many_to_many_python.txt
Q: How to add space How to add space to string. example: "Hiwatsup?" or "hi,hello" return "hi hello" or "hi" "hello" A: For "hi,hello" you can just replace the "," for a whitespace: hi = "hi,hello" print hi.replace(",", " ") you can also obtain a list of substrings split by a certain character: print hi.split(',')...
How to add space
How to add space to string. example: "Hiwatsup?" or "hi,hello" return "hi hello" or "hi" "hello"
[ "For \"hi,hello\" you can just replace the \",\" for a whitespace:\nhi = \"hi,hello\"\nprint hi.replace(\",\", \" \")\n\nyou can also obtain a list of substrings split by a certain character:\nprint hi.split(',')\n\nbut what I really advise doing is looking at the documentation for str:\nhelp(str)\n\n", "Like thi...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005619192_python.txt
Q: Django: change pdf file name using pisa reportlab I have a Django application which prints out a pdf file. I would like to know how to change the pdf file output name. Here is my views. def write_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html...
Django: change pdf file name using pisa reportlab
I have a Django application which prints out a pdf file. I would like to know how to change the pdf file output name. Here is my views. def write_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.Stri...
[ "You have a bug in your code because you return a bit too early:\nif not pdf.err:\n response = HttpResponse(result.getvalue(), mimetype='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=Client_Summary.pdf'\n return response\n\n" ]
[ 6 ]
[]
[]
[ "django", "pdf", "pisa", "python", "views" ]
stackoverflow_0005619239_django_pdf_pisa_python_views.txt
Q: IntegrityError + django I have created a django application. The application has a registration form. I inserted a jQuery plugin for birthday picker. But now when i fill the registration form and save it throws this error "IntegrityError at /registrationForm/ (1048, "Column 'birthday' cannot be null") " . I will p...
IntegrityError + django
I have created a django application. The application has a registration form. I inserted a jQuery plugin for birthday picker. But now when i fill the registration form and save it throws this error "IntegrityError at /registrationForm/ (1048, "Column 'birthday' cannot be null") " . I will paste my code here. registrati...
[ "field birthday must have an input to be submitted with the form.\nSo either use:\n<td>Birthday</td>\n<td><input type=\"text\" id=\"picker1\" name=\"birthday\" value=\"\" \n maxlength=\"100\" class=\"picker\" />\n\nor use a hidden input for birthday and fill it with javascript when submitting.\nAlso, you ...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "django_templates", "jquery", "python" ]
stackoverflow_0005619416_django_django_models_django_templates_jquery_python.txt
Q: array except other I have 2 arrays: arr1 = [a,b,c,d,e] arr2 = [c,d,e] I want to give array arr1 except arr2. A: Mathematically, you're looking for a difference between two sets represented in lists. So how about using the Python set, which has a builtin difference operation (overloaded on the - operator)? >>> ...
array except other
I have 2 arrays: arr1 = [a,b,c,d,e] arr2 = [c,d,e] I want to give array arr1 except arr2.
[ "Mathematically, you're looking for a difference between two sets represented in lists. So how about using the Python set, which has a builtin difference operation (overloaded on the - operator)?\n>>> \n>>> arr = [1, 2, 3, 4, 5]\n>>> arr2 = [3, 4, 9]\n>>> set(arr) - set(arr2)\n>>> sdiff = set(arr) - set(arr2)\n>>> ...
[ 3, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005619483_python.txt
Q: datepicker not defined - jQuery I have created a django application. In my application i have a registration from which has a date field.For that i was using jQuery datepicker. It was working fine before, but today when i started my application its not working for some unknown reason. I am not able to understand w...
datepicker not defined - jQuery
I have created a django application. In my application i have a registration from which has a date field.For that i was using jQuery datepicker. It was working fine before, but today when i started my application its not working for some unknown reason. I am not able to understand why its not working in my code, but wo...
[ "I don't know if it is related to your issue or not, but you have some invalid HTML in the code snippet you've posted. I would start by making sure all of your tags are balanced, you have a second form tag that doesn't get closed. Also, you have several bold tags in your table that are not closed as well.\n", "I ...
[ 2, 0 ]
[]
[]
[ "datepicker", "django", "javascript", "jquery", "python" ]
stackoverflow_0005616570_datepicker_django_javascript_jquery_python.txt
Q: Getting GeoDjango working on RHEL I'm working through dependency problems while installing GeoDjango dependencies on RHEL. I would love step-by-step instructions from anyone who has done this before. I'm transferring a working app from my Ubuntu development machine (where everything installed easily from packages)...
Getting GeoDjango working on RHEL
I'm working through dependency problems while installing GeoDjango dependencies on RHEL. I would love step-by-step instructions from anyone who has done this before. I'm transferring a working app from my Ubuntu development machine (where everything installed easily from packages) to a RHEL testing/staging server (pack...
[ "I recently installed it on fedora (quite similar to RHEL) using yum packages and POSTGIS, check http://invisibleroads.com/tutorials/geodjango-install.html . If the required packages are not available for RHEL, you're stuck with installing everything from source. This is a bit harder in my opinion.\nLooking at your...
[ 0 ]
[]
[]
[ "django", "geodjango", "python", "spatialite" ]
stackoverflow_0005477835_django_geodjango_python_spatialite.txt
Q: How to output a graph from Matplotlib in Django templates? Given this example taken from here: def simple(request): import random from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter fig=Fig...
How to output a graph from Matplotlib in Django templates?
Given this example taken from here: def simple(request): import random from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter fig=Figure() ax=fig.add_subplot(111) x=[] y=[] now=date...
[ "When I had a similar situation, I used two views. One used matplotilb to generate a PNG, while the other used used django templates to create an HTML page that presented the PNG (and some other data). The param sent to the template was just the PNG filename. The other view is then attached to he appropriate .pn...
[ 2 ]
[]
[]
[ "django", "django_templates", "graph", "matplotlib", "python" ]
stackoverflow_0005619534_django_django_templates_graph_matplotlib_python.txt
Q: Regular expression parsing a binary file? I have a file which mixes binary data and text data. I want to parse it through a regular expression, but I get this error: TypeError: can't use a string pattern on a bytes-like object I'm guessing that message means that Python doesn't want to parse binary files. I'm ope...
Regular expression parsing a binary file?
I have a file which mixes binary data and text data. I want to parse it through a regular expression, but I get this error: TypeError: can't use a string pattern on a bytes-like object I'm guessing that message means that Python doesn't want to parse binary files. I'm opening the file with the "rb" flags. How can I pa...
[ "I think you use Python 3 .\n\n1.Opening a file in binary mode is simple but subtle. The only difference\n from opening it in text mode is that\n the mode parameter contains a 'b'\n character.\n........\n4.Here’s one difference, though: a binary stream object has no encoding\n attribute. That makes sense, right...
[ 37, 35 ]
[ "This is working for me for python 2.6 \n>>> import re\n>>> r = re.compile(\".*(ELF).*\")\n>>> f = open(\"/bin/ls\")\n>>> x = f.readline()\n>>> r.match(x).groups()\n('ELF',)\n\n" ]
[ -3 ]
[ "binary", "parsing", "python", "python_3.x", "regex" ]
stackoverflow_0005618988_binary_parsing_python_python_3.x_regex.txt
Q: How to filter records before executing annotation on those records in django models? In documentation is example: Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1) How can I filter authors, before executing annotation on authors? For example I want Count only those authors that have na...
How to filter records before executing annotation on those records in django models?
In documentation is example: Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1) How can I filter authors, before executing annotation on authors? For example I want Count only those authors that have name "John".
[ "I don't believe you can make this selective count with the Django database-abstraction API without including some SQL. You make additions to a QuerySet's SQL using the extra method.\nAssuming that the example in the documention is part an app called \"inventory\" and using syntax that works with postgresql (you di...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005597166_django_django_models_python.txt
Q: xmpp: 2 clients with same account is it possible to connect to the same server (ejabberd) with same account 2 or more clients? if yes - how to do this with pyxmpp? A: It is perfectly possible to connect to an XMPP account from multiple clients (unless this is explicitly turned off on the server). They just need ...
xmpp: 2 clients with same account
is it possible to connect to the same server (ejabberd) with same account 2 or more clients? if yes - how to do this with pyxmpp?
[ "It is perfectly possible to connect to an XMPP account from multiple clients (unless this is explicitly turned off on the server). They just need to make their resource field distinct. Something like (not tested):\nFirst client:\npyxmpp.jabber.client.JabberClient(jid=pyxmpp.jid.JID(\"johny\", \"example.com\", \"ho...
[ 3 ]
[]
[]
[ "ejabberd", "python", "xmpp" ]
stackoverflow_0005619376_ejabberd_python_xmpp.txt
Q: How to run excel formulas from python script? I have an excel spreadsheet with some complicated calculations implemented. Is there a way I can feed the spreadsheet with input data, run the calculations and get the results from the python script level? A: http://www.pythonexcels.com/2009/10/python-excel-mini-coo...
How to run excel formulas from python script?
I have an excel spreadsheet with some complicated calculations implemented. Is there a way I can feed the spreadsheet with input data, run the calculations and get the results from the python script level?
[ "http://www.pythonexcels.com/2009/10/python-excel-mini-cookbook/\nhttp://oreilly.com/catalog/pythonwin32/chapter/ch12.html\nDriving Excel from Python in Windows\n..doable using the win32 python API\n" ]
[ 1 ]
[]
[]
[ "api", "excel", "python", "xlrd", "xlwt" ]
stackoverflow_0005620518_api_excel_python_xlrd_xlwt.txt
Q: Trouble using PIL with Google Appengine SDK I have a Windows Server 2008 R2 (64bits) machine on which I wanted to develop a google AppEngine app. So I installed Python 2.5.4 from python.org (because the Google SDK said I needed 2.5 and 2.5.6 didn't have any MSI's) Then I installed PIL from http://www.pythonware.c...
Trouble using PIL with Google Appengine SDK
I have a Windows Server 2008 R2 (64bits) machine on which I wanted to develop a google AppEngine app. So I installed Python 2.5.4 from python.org (because the Google SDK said I needed 2.5 and 2.5.6 didn't have any MSI's) Then I installed PIL from http://www.pythonware.com/products/pil/ I used version 1.1.7 for python ...
[ "This happens when Python can't find ICCProfile module.\nApperently when using trough GAE instead of an ImportError the importer throws a SystemError, and the function fails.\nWhat i did was to change line 567 in ...\\Python25\\Lib\\site-packages\\PIL\\PngImagePlugin.py\nfrom \nexcept ImportError:\nto:\nexcept Exce...
[ 2, 2, 0 ]
[]
[]
[ "google_app_engine", "python", "python_imaging_library", "windows_server_2008" ]
stackoverflow_0002287966_google_app_engine_python_python_imaging_library_windows_server_2008.txt
Q: Compilation warning in Python when a python file is compiled in linux machine the following warning is seen but the same file compiled in Solaris machine, warning is not seen /opt/swe/tools/ext/gnu/python-2.3.5_p1/i686-linux2.4/lib/python2.3/config/libpython2.3.a(posixmodule.o)(.text+0x3e9a): In function `posix_tm...
Compilation warning in Python
when a python file is compiled in linux machine the following warning is seen but the same file compiled in Solaris machine, warning is not seen /opt/swe/tools/ext/gnu/python-2.3.5_p1/i686-linux2.4/lib/python2.3/config/libpython2.3.a(posixmodule.o)(.text+0x3e9a): In function `posix_tmpnam': ./Modules/posixmodule.c:6138...
[ "You are using an older version of python. \nSince then it became clear that the tmpnam function is not safe, and the libraries / headers shipping with linux have been updated to give you a warning. But it should compile, as backwards compatibility is pretty important.\nPython 2.3 was developed in a time it was not...
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002020317_python.txt
Q: how to add comment or label to the graph in RDFLib? I'm trying to add names of datasets to the graph object and later retrieve them, pretty sure there must be easy way to accomplish it, but could not find anything so far ... thanks A: I think that what you are looking for is to attach a context to a graph. It's ...
how to add comment or label to the graph in RDFLib?
I'm trying to add names of datasets to the graph object and later retrieve them, pretty sure there must be easy way to accomplish it, but could not find anything so far ... thanks
[ "I think that what you are looking for is to attach a context to a graph. It's like creating a graph out parsing subgraphs in it, each subgraph with a name - a URIRef in case of rdflib.\nImagine you have to graphs represented by the two following files:\ndataA.nt\n<http://data.org/inst1> <http://xmlns.com/foaf/0.1/...
[ 3 ]
[]
[]
[ "python", "rdf", "rdflib" ]
stackoverflow_0005620038_python_rdf_rdflib.txt
Q: [Python]: Double backslashes in command SUMMARY: I want to execute a pskill.exe command in python. Tried it in a dos-prompt: C:\Users\JohanSA\Documents\EclipseWorkspace\ProdataATFBASE\src\resources\pskill.exe \localhost -t 11780 --> work nice! ==> But I want to run the same command via Python. prodataOSLib.execut...
[Python]: Double backslashes in command
SUMMARY: I want to execute a pskill.exe command in python. Tried it in a dos-prompt: C:\Users\JohanSA\Documents\EclipseWorkspace\ProdataATFBASE\src\resources\pskill.exe \localhost -t 11780 --> work nice! ==> But I want to run the same command via Python. prodataOSLib.executeCmd("pskill.exe -t 11780", True, True) --...
[ "Make your string as raw string by prefixing r. I am unable to understand the code and the description, but what are you looking for is called raw_string and it is obtained by prefixing r. Like this r'c:\\localhost\\nyprogram'\n" ]
[ 1 ]
[]
[]
[ "backslash", "escaping", "python" ]
stackoverflow_0005620760_backslash_escaping_python.txt
Q: Keeps only one entry instead of appending to the dictionary I want to take person's name and their phone number from the end user and append to a dictionary. I started with an empty dictionary. After first user inputs the data, the program will say a new entry is added and display what is inside the updated dictio...
Keeps only one entry instead of appending to the dictionary
I want to take person's name and their phone number from the end user and append to a dictionary. I started with an empty dictionary. After first user inputs the data, the program will say a new entry is added and display what is inside the updated dictionary. It works fine so far. When the second user inputs the data ...
[ "I think you seriously messed up what should be an attribute of the class and what should not. Think of it this way: your phonebook class has a dictionary in it, hence a dictionary should be an attribute. The name and phone of the person you're adding should be parameters to adddata, not instance vars of the class....
[ 3, 1, 0 ]
[]
[]
[ "append", "dictionary", "python" ]
stackoverflow_0005619226_append_dictionary_python.txt
Q: Does Python's multiprocessing.Pool support remote subprocesses? I have recently discovered how awesome Pool.map() is for simple multiprocessing tasks, but my local machine only has two processors and I was hoping to take advantage of some remote computing resources. Can a processing pool be constructed to use remo...
Does Python's multiprocessing.Pool support remote subprocesses?
I have recently discovered how awesome Pool.map() is for simple multiprocessing tasks, but my local machine only has two processors and I was hoping to take advantage of some remote computing resources. Can a processing pool be constructed to use remote machines as well as the local machines in a transparent way? What ...
[ "multiprocessing.Pool seems not designed for distributed processing -- if that's what you want to do, I suggest you check out the execnet package instead. That works over SSH pipes and sends code along to the remote Python interpreter if necessary.\n" ]
[ 2 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0005618609_multiprocessing_python.txt
Q: Python PostgreSQL Transaction Error I'm trying to use Django's ORM to do some data processing with a PostgreSQL backend. Given a primary record, generate hundreds of records in a related table, but if any errors occur, I want to rollback all record creations. Therefore, I have the entire process wrapped in a manua...
Python PostgreSQL Transaction Error
I'm trying to use Django's ORM to do some data processing with a PostgreSQL backend. Given a primary record, generate hundreds of records in a related table, but if any errors occur, I want to rollback all record creations. Therefore, I have the entire process wrapped in a manual transaction. @transaction.commit_manual...
[ "If you're not running this on the development server, then the error is most likely from your \"print\" statements. When running from Apache via mod_wsgi, for example, the stdout file descriptors are closed, so you cannot \"print\" as normal.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "django_orm", "postgresql", "python" ]
stackoverflow_0005621166_django_django_models_django_orm_postgresql_python.txt
Q: Debugging Android App crash hello I am trying to debug the crash of an Android app an outdated android app that I have been working on. The app is the Jython Interpreter for Android so far I have managed to compile a debug binary and am hoping some one could shed some light on this error message of logcat thank yo...
Debugging Android App crash
hello I am trying to debug the crash of an Android app an outdated android app that I have been working on. The app is the Jython Interpreter for Android so far I have managed to compile a debug binary and am hoping some one could shed some light on this error message of logcat thank you I/ActivityManager( 51): Start...
[ "One problem looks like you are adding a child view to another view - but that child view has already been added. Are you dynamically adding a view or building a layout?E/AndroidRuntime( 190): at org.python.util.Jythonroid.onCreate(Jythonroi\nd.java:251)\n\n", "This call seems to be out of place\nsetConte...
[ 0, 0 ]
[]
[]
[ "android", "java", "jython", "python" ]
stackoverflow_0005616325_android_java_jython_python.txt
Q: Loading SVG files with python and pygame Possible Duplicate: SVG rendering in a PyGame application Can I load .svg files created by inkscape to python via pygame? And if so, how I can do it? A: No you cannot, PyGame supports following image formats: JPG PNG GIF (non animated) BMP PCX TGA (uncompressed) T...
Loading SVG files with python and pygame
Possible Duplicate: SVG rendering in a PyGame application Can I load .svg files created by inkscape to python via pygame? And if so, how I can do it?
[ "No you cannot, PyGame supports following image formats:\n\nJPG \nPNG \nGIF (non animated) \nBMP \nPCX\nTGA (uncompressed) \nTIF \nLBM (and PBM)\nPBM (and PGM, PPM) \nXPM\n\nYou can however rasterize that SVG using Cairo RSVG library. \nThere is some documentation for that on PyGame's web.\n" ]
[ 3 ]
[]
[]
[ "inkscape", "pygame", "python", "svg" ]
stackoverflow_0005622259_inkscape_pygame_python_svg.txt
Q: Attaching file to an email in python leads to a blank file name? The following snipit of code works fine, except for the fact that the resulting attachment file name is blank in the email (the file opens as 'noname' in gmail). What am I doing wrong? file_name = RecordingUrl.split("/")[-1] file_name=fil...
Attaching file to an email in python leads to a blank file name?
The following snipit of code works fine, except for the fact that the resulting attachment file name is blank in the email (the file opens as 'noname' in gmail). What am I doing wrong? file_name = RecordingUrl.split("/")[-1] file_name=file_name+ ".wav" urlretrieve(RecordingUrl, file_name) ...
[ "You need to add a Content-Disposition header to the audio part of the message using the add_header method:\nfile = open(file_name, 'rb')\naudio = MIMEAudio(file.read())\nfile.close()\naudio.add_header('Content-Disposition', 'attachment', filename=file_name)\nmsg.attach(audio)\n\n" ]
[ 13 ]
[]
[]
[ "attachment", "email", "filenames", "python" ]
stackoverflow_0005622660_attachment_email_filenames_python.txt
Q: Django settings outside of project I have a Django project that uses SQLAlchemy to use some legacy ORM objects. This application also hits up an ldap server for user authentication. I was getting sick of moving from development to production servers for both ldap and the database. I was hoping to create a IS_DEVEL...
Django settings outside of project
I have a Django project that uses SQLAlchemy to use some legacy ORM objects. This application also hits up an ldap server for user authentication. I was getting sick of moving from development to production servers for both ldap and the database. I was hoping to create a IS_DEVELOPMENT variable in the settings.py. One ...
[ "\"Standalone Django Scripts\"\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005622885_django_python.txt
Q: Hybrid Application with Python GUI with C++ background modules I want to write a hybrid application which uses python as GUI component, and C++ module as background services. I know how to program with Python, and C++, but I don't find a mature/nice way to make them work together smoothly. Could you guys shed som...
Hybrid Application with Python GUI with C++ background modules
I want to write a hybrid application which uses python as GUI component, and C++ module as background services. I know how to program with Python, and C++, but I don't find a mature/nice way to make them work together smoothly. Could you guys shed some light on this for me? A good document/tutorial is also very apprec...
[ "I like to use cython for writing glue code between those two worlds, or if I want stronger separation for any reason I like the ctypes approach.\n", "If you are comfortable with using boost, go for boost python. (Tutorial)\nOtherwise, use the CPython API directly.\nWith either of these, you can create Python mod...
[ 4, 3, 0 ]
[]
[]
[ "boost", "c++", "python", "wxpython" ]
stackoverflow_0005618613_boost_c++_python_wxpython.txt
Q: How can I retrieving a timestamp from a dictionary and converting it to datetime object? I have a dictionary of timestamps in this form 2011-03-01 17:52:49.728883 and ids. How can I retrieve the latest timestamp and represent it in python datetime object? The point is to be able to use the latest date of the times...
How can I retrieving a timestamp from a dictionary and converting it to datetime object?
I have a dictionary of timestamps in this form 2011-03-01 17:52:49.728883 and ids. How can I retrieve the latest timestamp and represent it in python datetime object? The point is to be able to use the latest date of the timestamp instead of the currnt date in above code. latest = datetime.now()
[ "The structure of your dictionary is not entirely clear from your question, so I'll assume the keys are strings containing timestamps like the one in your question.\nIf d is the dictionary:\ndatetime.strptime(max(d.keys()),'%Y-%m-%d %H:%M:%S.%f')\nThe above code uses the fact that the lexicographical ordering of yo...
[ 2 ]
[]
[]
[ "datetime", "python", "timestamp" ]
stackoverflow_0005622884_datetime_python_timestamp.txt
Q: Question Regarding API Design I am in the process of researching the best "design-pattern" a web API. I am currently using Django as my web framework. I created a non-ajax interface that causes the entire page to reload at each request. Now, I am starting incorporate ajax into the interface. For the sake of this ...
Question Regarding API Design
I am in the process of researching the best "design-pattern" a web API. I am currently using Django as my web framework. I created a non-ajax interface that causes the entire page to reload at each request. Now, I am starting incorporate ajax into the interface. For the sake of this discussion, two example pieces of f...
[ "Yes, you seem to be on the right track. One quibble: to check if an email address exists in the db, you should ideally use a GET rather than a POST, as no information is being updated - you are simply asking if something exists.\nOne alternative to returning JSON is to return pre-rendered HTML which you can inject...
[ 3, 2 ]
[]
[]
[ "api", "django", "json", "python" ]
stackoverflow_0005623075_api_django_json_python.txt
Q: Destructor and python I have some Base class in c++. I export it into python using boost::python. But what about virtual destructor? Any base class should have virtual destructor to avoid wrong memory freeing, right? I forget about that and wrote Base without destructor. Everything works, but with a lot of memory ...
Destructor and python
I have some Base class in c++. I export it into python using boost::python. But what about virtual destructor? Any base class should have virtual destructor to avoid wrong memory freeing, right? I forget about that and wrote Base without destructor. Everything works, but with a lot of memory leaks. Now I've added: clas...
[ "The missing symbol error is probably caused by you failing to define the destructor (you're declaring the destructor, but it's unclear from your question whether you're defining it):\nclass Base\n{\n public:\n virtual ~Base() {}\n // Other members...\n};\n\n(note the added curly braces)\nAs to your que...
[ 2, 0 ]
[]
[]
[ "boost", "c++", "python", "virtual_destructor" ]
stackoverflow_0005623287_boost_c++_python_virtual_destructor.txt
Q: How to mock a class in Python? I'm new to Python, but I used to work with ruby. I'm trying to do some tests with Python but I can't figure out how I mock a class for my test. Let's say I have this real class: from database import DB class Foo: def do_it(self): x = {'key': 'value'} DB.save(x) # do oth...
How to mock a class in Python?
I'm new to Python, but I used to work with ruby. I'm trying to do some tests with Python but I can't figure out how I mock a class for my test. Let's say I have this real class: from database import DB class Foo: def do_it(self): x = {'key': 'value'} DB.save(x) # do other stuff with x return x Now, I...
[ "The answer is, don't write your classes like that. It's a strange way to do so anyway - there shouldn't really be any executable code at the class level, other than attribute and method definitions. You should setup the connection in the __init__ method.\nclass Foo(object):\n def __init__(self, *args, **kwargs)...
[ 7, 4 ]
[]
[]
[ "python", "testing" ]
stackoverflow_0005622980_python_testing.txt
Q: problem in executable created with py2exe I have an application written in python which uses pygtk to built GUI, also some glade files are included for window building. My problem is my application works fine when i run it from cmd, but when i create an exe with py2exe the application doesn't start, but it creat...
problem in executable created with py2exe
I have an application written in python which uses pygtk to built GUI, also some glade files are included for window building. My problem is my application works fine when i run it from cmd, but when i create an exe with py2exe the application doesn't start, but it creates the empty log file which i am writing in app...
[ "I had problems like this too quite a few times when using tools like py2exe and py2app.\nIIRC, many times it was caused by the Python process's working directory being something very different when the .exe is double-clicked. You may want to add some code to the startup of your Python program that logs the value o...
[ 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0005623378_pygtk_python.txt
Q: Pythonic way to parse list of dictionaries for a specific attribute? I want to cross reference a dictionary and django queryset to determine which elements have unique dictionary['name'] and djangoModel.name values, respectively. The way I'm doing this now is to: Create a list of the dictionary['name'] values ...
Pythonic way to parse list of dictionaries for a specific attribute?
I want to cross reference a dictionary and django queryset to determine which elements have unique dictionary['name'] and djangoModel.name values, respectively. The way I'm doing this now is to: Create a list of the dictionary['name'] values Create a list of djangoModel.name values Generate the list of unique valu...
[ "vctestNames = dict((vctest['name'], vctest) for vctest in vcdict['tests'])\ndbtestNames = dict((dbtest.name, dbtest) for dbtest in alldbTests)\n\nobsoleteTests = [vctestNames[key]\n for key in set(vctestNames.keys()) - set(dbtestNames.keys())]\n\nnewTests = [dbtestNames[key]\n for key in...
[ 4, 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005623760_django_python.txt
Q: Program hangs when using "matplotlib.mlab.griddata" I have written a script (Python 2.6) to grid data in x,y,z (.csv format), and display a contour plot of the data. The script works for some datasets but not others - even though both datasets were created using the same script. The datasets to be plotted are crea...
Program hangs when using "matplotlib.mlab.griddata"
I have written a script (Python 2.6) to grid data in x,y,z (.csv format), and display a contour plot of the data. The script works for some datasets but not others - even though both datasets were created using the same script. The datasets to be plotted are created by sub-sampling from a master dataset. Here is an exa...
[ "It's failing because you're trying to interpolate over a very strange region.\nLook at your input coordinates, your data is all in a line, but you're trying to interpolate in 2D. Your yi coordinates are all the same!\n\nIf you want 1D interpolation, then just use one of the many 1D interpolation routines... (numpy...
[ 4 ]
[]
[]
[ "contour", "grid", "matplotlib", "python" ]
stackoverflow_0005615978_contour_grid_matplotlib_python.txt
Q: for loop to insert things into a tkinter window I have Tkinter program that has to add a significant amount of data to the window so I tried to write a for loop to take care of it but since I have to use a string variable for the name of the object that Tkinter is running .insert() on the object. I didn't explain ...
for loop to insert things into a tkinter window
I have Tkinter program that has to add a significant amount of data to the window so I tried to write a for loop to take care of it but since I have to use a string variable for the name of the object that Tkinter is running .insert() on the object. I didn't explain it very well here is the method def fillWindow(self)...
[ "It looks like you have a conceptual error there: inside this method, the variable \"name\" does not exist up to the last line on the first listing. Then it is created, and points to an ordinary Python string -- if you are using a \"name\" variable elsewhere on your class that variable does not exist inside this me...
[ 1 ]
[]
[]
[ "for_loop", "python", "tkinter", "user_interface" ]
stackoverflow_0005623679_for_loop_python_tkinter_user_interface.txt
Q: replicating borders in 2d numpy arrays I am trying to replicate the border of a 2d numpy array: >>> from numpy import * >>> test = array(range(9)).reshape(3,3) array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) Is there an easy way to replicate a border in any direction? for example: >>>> replicate(test, idx=...
replicating borders in 2d numpy arrays
I am trying to replicate the border of a 2d numpy array: >>> from numpy import * >>> test = array(range(9)).reshape(3,3) array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) Is there an easy way to replicate a border in any direction? for example: >>>> replicate(test, idx=0, axis=0, n=3) array([[0, 1, 2], [0...
[ "You can use np.repeat:\nIn [5]: np.repeat(test, [4, 1, 1], axis=0)\nOut[5]: \narray([[0, 1, 2],\n [0, 1, 2],\n [0, 1, 2],\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]])\n\nBut for larger/variable arrays it will be more difficult to define the repeats argument ([4, 1, 1], which is in this cas...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005624355_numpy_python.txt
Q: extract a substring from an array of strings in python Is there a way how to extract an array (or list) of substrings (all characters from position 1 to position 2) from all elements of a string array (or a list of strings) without making a loop? For example, I have: aa=['ab1cd','ab2ef'] , and I want my output to ...
extract a substring from an array of strings in python
Is there a way how to extract an array (or list) of substrings (all characters from position 1 to position 2) from all elements of a string array (or a list of strings) without making a loop? For example, I have: aa=['ab1cd','ab2ef'] , and I want my output to be: out=['b1','b2'] For a single string variable I would do ...
[ "You will definitely need some kind of loop. A list comprehension is the easiest way:\nout = [x[1:3] for x in aa]\n\n" ]
[ 17 ]
[]
[]
[ "python" ]
stackoverflow_0005624523_python.txt
Q: In python, how would I sort a list of strings where the location of the string comparison changes? I have a list of strings that have 2 dashes separating text like: Wednesday-Morning-Go bowling Sunday-Really late at night-Sleep July-Noon-BBQ I'd like to sort the list in alphabetical order in python by the last pa...
In python, how would I sort a list of strings where the location of the string comparison changes?
I have a list of strings that have 2 dashes separating text like: Wednesday-Morning-Go bowling Sunday-Really late at night-Sleep July-Noon-BBQ I'd like to sort the list in alphabetical order in python by the last part of the string--the 2nd dash and on. Is there a way to do this in python? E.g. this is what I would ...
[ "You can use the key attribute to list.sort():\na = [\"Wednesday-Morning-Go bowling\", \"Sunday-Really late at night-Sleep\",\n \"July-Noon-BBQ\"]\na.sort(key=lambda x: x.split(\"-\", 2)[-1])\nprint a\n\nprints\n['July-Noon-BBQ', 'Wednesday-Morning-Go bowling', 'Sunday-Really late at night-Sleep']\n\nNote that ...
[ 8, 1, 1, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0005624757_python_sorting.txt
Q: python validate Oracle username/passwords without using cx_Oracle I need to validate that user provided data for oracle account information is correct. I tried to use cx_Oracle but the version of OCI.DLL that is on my servers (which I can't upgrade) seems to not be the correct version for cx_Oracle. How can I val...
python validate Oracle username/passwords without using cx_Oracle
I need to validate that user provided data for oracle account information is correct. I tried to use cx_Oracle but the version of OCI.DLL that is on my servers (which I can't upgrade) seems to not be the correct version for cx_Oracle. How can I validate username/passwords without using cx_Oracle?
[ "If you can't compile cx_Oracle, you have two options:\n\nuse ODBC (for example PyODBC);\nuse subprocess to interact with sqlplus. \n\n", "The problem is most likely the version of your cx_Oracle module. \nYou have to be extremely careful when you install the module, to choose the appropriate version for your ora...
[ 3, 1, 1 ]
[]
[]
[ "oracle", "python" ]
stackoverflow_0005565899_oracle_python.txt
Q: Where can I find a pluggable blog app for Django? Where can I find an open source pluggable blog app for Django? It should support: RSS/Atom Comments the built-in Django authentication system Markdown (optional) Akismet or other spam protection (optional) Plus, I'd like to have to ability to embed the blog front...
Where can I find a pluggable blog app for Django?
Where can I find an open source pluggable blog app for Django? It should support: RSS/Atom Comments the built-in Django authentication system Markdown (optional) Akismet or other spam protection (optional) Plus, I'd like to have to ability to embed the blog front page into another page, maybe in another app. I'd lik...
[ "Check out django packages' grid for blog applications.\nI would find find one that looks close to what you are looking for and edit it to fit your needs. That's the great thing about django, the ability to customize.\n", "I've used Django Basic Blog as the base, and customized it to suit my needs, it is part of ...
[ 1, 1, 1, 0 ]
[]
[]
[ "blogs", "django", "django_apps", "python" ]
stackoverflow_0005624750_blogs_django_django_apps_python.txt
Q: Using VBOs in python Im trying to optimize my opengl app using VBOs, right now it works perfectly using vertex arrays but when I use VBOs in doesn't render anything neither throws any exception. All the tutorials I've seen use similar approaches. Here is the code to upload and to render those VBOs. def uploadT...
Using VBOs in python
Im trying to optimize my opengl app using VBOs, right now it works perfectly using vertex arrays but when I use VBOs in doesn't render anything neither throws any exception. All the tutorials I've seen use similar approaches. Here is the code to upload and to render those VBOs. def uploadToVRAM(self): usage = G...
[ "By looking over your code I notice one possible and one probable problem:\n\nIn your data upload you don't use the ARB variants of GL constants (like you do for rendering)\nYou unbind your array buffer before you call glDrawArrays\n\nIf this doesn't help try making a minimal runnable example we can play with to ma...
[ 0 ]
[]
[]
[ "opengl", "python" ]
stackoverflow_0005619450_opengl_python.txt
Q: How to preserve case using re.IGNORECASE and .sub? import re def bold_partial(long_string, partial): replacer = re.compile(partial, re.IGNORECASE) new_long_string = replacer.sub('<b>' + partial + '</b>', long_string) print new_long_string bold_partial('My name is Roger the Shrubber. I arrange, desi...
How to preserve case using re.IGNORECASE and .sub?
import re def bold_partial(long_string, partial): replacer = re.compile(partial, re.IGNORECASE) new_long_string = replacer.sub('<b>' + partial + '</b>', long_string) print new_long_string bold_partial('My name is Roger the Shrubber. I arrange, design, and sell shrubberies.', 'roger the shrubber') Retur...
[ "def bold_partial_rep(matchobj):\n return '<b>' + matchobj.group(0) + '</b>'\n\ndef bold_partial(long_string, partial):\n replacer = re.compile(partial, re.IGNORECASE)\n new_long_string = replacer.sub(bold_partial_rep, long_string)\n print new_long_string\n\nOr if you want to shorten code you can get ri...
[ 4, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005625317_python_regex.txt
Q: how to increment tuple values and search a string in a loop in python I have this code. arfffile = [] inputed = raw_input("Enter Evaluation for name including file extension...") reader = open(inputed, 'r') verses = [] for line in reader: verses.append(line) for line in verses: if line.split('@') ==...
how to increment tuple values and search a string in a loop in python
I have this code. arfffile = [] inputed = raw_input("Enter Evaluation for name including file extension...") reader = open(inputed, 'r') verses = [] for line in reader: verses.append(line) for line in verses: if line.split('@') == "@": verses.pop(line) numclusters = int(raw_input("Enter the num...
[ "import collections\n\ninputed = raw_input(\"Enter Evaluation for name including file extension...\")\n\nreader = open(inputed, 'r')\n\nverses = [ line.strip() for line in reader.readlines() if line[0] != '@' ]\n\nreader.close()\n\ncluster_count = collections.defaultdict(int)\nyes_count = collections.defaultdict(in...
[ 1 ]
[]
[]
[ "dictionary", "python", "tuples" ]
stackoverflow_0005625248_dictionary_python_tuples.txt
Q: python csv module error When I use Pythons csv module, it shows me "delimiter" must be an 1-character string" My code is like this sep = "," srcdata = cStringIO.StringIO(wdata[1]) data = csv.reader(srcdata, delimiter=sep) wdata[1] is a string source. How do I fix this problem? A: You most likely have from...
python csv module error
When I use Pythons csv module, it shows me "delimiter" must be an 1-character string" My code is like this sep = "," srcdata = cStringIO.StringIO(wdata[1]) data = csv.reader(srcdata, delimiter=sep) wdata[1] is a string source. How do I fix this problem?
[ "You most likely have from __future__ import unicode_literals at the top of your module or you are using python 3.x+ You need to do something like this:\nsep=b\",\" # notice the b before the \"\nsrcdata=cStringIO.StringIO(wdata[1])\ndata = csv.reader(srcdata,delimiter=sep)\n\nThis tells Python that you want to rep...
[ 31 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005625412_csv_python.txt
Q: Generating python data structures from parsed text without eval() I'm trying to build a tool to generate datastructures from a text config. I usepyparsing to parse the commands... CONFIG FILE: add Iteration name = "Cisco 10M/half" append Observation name = "packet loss" assign Observation results_text...
Generating python data structures from parsed text without eval()
I'm trying to build a tool to generate datastructures from a text config. I usepyparsing to parse the commands... CONFIG FILE: add Iteration name = "Cisco 10M/half" append Observation name = "packet loss" assign Observation results_text = 0.0 assign Observation results_bool = True append Da...
[ "Judging from your eval() call, it looks like the classes you are trying to instantiate are in your current global scope. You can simply look them up yourself and create an instance:\nobj = globals()[txtobj]()\n\nNote that this will call any global object named by txtobj, so you should not use this for untrusted d...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0005625481_python.txt
Q: Reusing data in python Im tring to pull data once from Mysql into "c." Then create an NUMPY array and a dict from the data. It seems that once I zip 'c' it no longer stay in orig form. Can this be done? import csv, pyodbc#, from numpy import * import numpy as np csr = cxn.cursor() c = csr.execute("Select * f...
Reusing data in python
Im tring to pull data once from Mysql into "c." Then create an NUMPY array and a dict from the data. It seems that once I zip 'c' it no longer stay in orig form. Can this be done? import csv, pyodbc#, from numpy import * import numpy as np csr = cxn.cursor() c = csr.execute("Select * from p.s") s = zip(*c) data ...
[ "zip(*c) uses up the c iterator so you need to recreate it later by rerunning c = csr.execute(\"Select * from p.s\")\n or save its contents before zip like c = list(c)\n", "A few more comments:\n\nThis code\nfor each in data:\n v= dict((each, []) for each in data)\nprint v\n\ncreates the same dictionary over a...
[ 2, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005616373_numpy_python.txt
Q: if __ and __ in ___ then I am trying to create a script that loops through a list. I need to look through a finite list (400) of competency identifiers (e.g. 124, 129 etc - normal ints ) I then have a dictionary that records what competencies each user has. The Key is the user name and the value for each key is a ...
if __ and __ in ___ then
I am trying to create a script that loops through a list. I need to look through a finite list (400) of competency identifiers (e.g. 124, 129 etc - normal ints ) I then have a dictionary that records what competencies each user has. The Key is the user name and the value for each key is a list of integers (i.e. which c...
[ "You're misinterpreting how and works. To test if two values are in a list, use:\nif comp1 in d1[person] and comp2 in d1[person]:\n ...\n\nYour version does something else. It binds like this: if (comp1) and (comp2 in d1[person]). In other words, it interprets comp1 as a truth value, and then does a boolean and wi...
[ 8, 3, 0 ]
[]
[]
[ "dictionary", "if_statement", "list", "python" ]
stackoverflow_0005625013_dictionary_if_statement_list_python.txt
Q: Using PyLucene as a K-NN Classifier I have a dataset composed of millions of examples, where each example contains 128 continuous-value features classified with a name. I'm trying to find a large robust database/index to use to use as a KNN classifier for high-dimensional data. I tried Weka's IBk classifier, but i...
Using PyLucene as a K-NN Classifier
I have a dataset composed of millions of examples, where each example contains 128 continuous-value features classified with a name. I'm trying to find a large robust database/index to use to use as a KNN classifier for high-dimensional data. I tried Weka's IBk classifier, but it chokes on this much data, and even then...
[ "Lucene doesn't seem like the right choice given what you've told us. Lucene would give you a way to store the data, but in terms of retrieval, it's not designed to do anything but search over textual strings. \nSince K-NN is so simple, you might be better off creating your own data store in a typical RDBMS or so...
[ 1, 0 ]
[]
[]
[ "data_mining", "lucene", "machine_learning", "pylucene", "python" ]
stackoverflow_0005571339_data_mining_lucene_machine_learning_pylucene_python.txt
Q: Python port listner application / tool Hi All I would like to keep a Python application in to a port listener. The structure is like : when ever data comes to a port it has to analyse it and return data + associated value determined by the program. Is there any good tools / modules available for this A: Take a...
Python port listner application / tool
Hi All I would like to keep a Python application in to a port listener. The structure is like : when ever data comes to a port it has to analyse it and return data + associated value determined by the program. Is there any good tools / modules available for this
[ "Take a look at twisted:\n\nTwisted is an event-driven networking\n engine written in Python and licensed\n under the MIT license.\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005626310_python.txt
Q: Design of virtual trial room As a part of my masters project I proposed to build a virtual trial room application intended for retail clothing stores. Currently its meant to be used directly in store though it may be extended for online stores as well. This application will show customers how a selected apparel wo...
Design of virtual trial room
As a part of my masters project I proposed to build a virtual trial room application intended for retail clothing stores. Currently its meant to be used directly in store though it may be extended for online stores as well. This application will show customers how a selected apparel would look on them by showing it on ...
[ "Theoretically this can be achieved in real time. Many usefull algorithms for video tracking, stereo vision and 3d recostruction are available in OpenCV library. But it's very difficult to build robust solution. For example, you'll probably need to track human body which moves frame to frame and perform pose estima...
[ 1 ]
[]
[]
[ "blender", "c++", "graphics", "opengl", "python" ]
stackoverflow_0005624936_blender_c++_graphics_opengl_python.txt
Q: syntax error in python function definitions sorry if I sound like a complete idiot when asking this, I'm very new to Python. When I create a function like this : def load_content(name, colorkey=None, datatype): It tells me there is a syntax error. From what I can tell, this is the right way to write a function. ...
syntax error in python function definitions
sorry if I sound like a complete idiot when asking this, I'm very new to Python. When I create a function like this : def load_content(name, colorkey=None, datatype): It tells me there is a syntax error. From what I can tell, this is the right way to write a function. Like I said, I'm very new. Does anyone know what'...
[ "You can't have default arguments between non-default arguments\ndef load_content(name, colorkey=None, datatype=None):\n\nor\ndef load_content(name, datatype, colorkey=None):\n\n", "Default arguments must be at the end of the argument list, but before *args and **kwargs.\n", "Default parameter MUST be the last ...
[ 3, 2, 0 ]
[]
[]
[ "function", "python", "syntax_error" ]
stackoverflow_0005626552_function_python_syntax_error.txt
Q: Python parse DNS response headers i want to know if there is a way to generate dns queries via python and get the dns responses as well as their headers so as to see things in the dns response as NXDomain, connection refused, server failure etc.. thanks in advance A: Sure, there is a library called dnspython tha...
Python parse DNS response headers
i want to know if there is a way to generate dns queries via python and get the dns responses as well as their headers so as to see things in the dns response as NXDomain, connection refused, server failure etc.. thanks in advance
[ "Sure, there is a library called dnspython that does exactly that.\n" ]
[ 6 ]
[]
[]
[ "dns", "header", "python" ]
stackoverflow_0005626597_dns_header_python.txt
Q: where does a django file upload is stored? If I create a django form that permits a user to upload a file, where does the file get stored or where do I configure it from. I am using the development server porvided by django. Could you please help me with this? A: All the answers can be found in the documentation...
where does a django file upload is stored?
If I create a django form that permits a user to upload a file, where does the file get stored or where do I configure it from. I am using the development server porvided by django. Could you please help me with this?
[ "All the answers can be found in the documentation.\nIf the file is small enough, it's stored in memory. If not, it's saved under the FILE_UPLOAD_TEMP_DIR directory (/tmp by default on Unix systems).\nYou can completely customize the upload process by writing your own upload handlers (once again, it's in the link a...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005626601_django_python.txt
Q: List lookup faster than tuple? In the past, when I've needed array-like indexical  lookups in a tight loop, I usually use tuples, since they seem to be generally extremely performant (close to using just n-number of variables). However, I decided to question that assumption today and came up with some surprising r...
List lookup faster than tuple?
In the past, when I've needed array-like indexical  lookups in a tight loop, I usually use tuples, since they seem to be generally extremely performant (close to using just n-number of variables). However, I decided to question that assumption today and came up with some surprising results: In [102]: l = range(1000) In...
[ "Tuples are primarily faster for constructing lists, not for accessing them.\nTuples should be slightly faster to access: they require one less indirection. However, I believe the main benefit is that they don't require a second allocation when constructing the list.\nThe reason lists are slightly faster for looku...
[ 23, 12 ]
[]
[]
[ "list", "performance", "python", "python_internals", "tuples" ]
stackoverflow_0005626164_list_performance_python_python_internals_tuples.txt
Q: Test specific models in Django Is it possible to have a set of models just for testing purposes? The idea is that I've written an app that contains some helper abstract model HelperBase. Now I'd like to provide some models that would inherit from it in order to test it, say DerivedTest1, DerivedTest2. However I wo...
Test specific models in Django
Is it possible to have a set of models just for testing purposes? The idea is that I've written an app that contains some helper abstract model HelperBase. Now I'd like to provide some models that would inherit from it in order to test it, say DerivedTest1, DerivedTest2. However I wouldn't really like those test models...
[ "You could try creating a whole new app that you only use on your development server.\nE.g., if your app is called myapp you would call your testing app myapp_test.\nThen in myapp_test's models.py you would from myapp import models and then subclass your models in there.\nThen in your settings.py you either just tr...
[ 0 ]
[]
[]
[ "django", "django_models", "django_testing", "python", "testing" ]
stackoverflow_0005626672_django_django_models_django_testing_python_testing.txt
Q: Import variables in python I ran a python script to create a dict variable based on a database, and then I pickled this variable into disk file for later usage. Now I have a lot of feature classes which all need that variable to create different features. The thing is the dict variable is so large that cannot affo...
Import variables in python
I ran a python script to create a dict variable based on a database, and then I pickled this variable into disk file for later usage. Now I have a lot of feature classes which all need that variable to create different features. The thing is the dict variable is so large that cannot afford to import multiple times. I a...
[ "Python will only import the module once. Any code that executes at load time will only be executed the first time a file imports the module.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0005626845_python.txt
Q: return outside function, or unexpected indent I have this: if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() It tells me that "return" is outside the function. When I change it to this: if colorkey is n...
return outside function, or unexpected indent
I have this: if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() It tells me that "return" is outside the function. When I change it to this: if colorkey is not None: if colorkey is -1: colork...
[ "In python, scopes are defined by the same level of indentation instead of braces (i.e. {}) as in other languages.\nIf you write a function, you need to ensure that all function body is at the same level of indentation - be it the same amount of spaces or the same amount of tabs (mixing spaces and tabs can result i...
[ 4, 0 ]
[]
[]
[ "indentation", "python", "return" ]
stackoverflow_0005626889_indentation_python_return.txt
Q: transforming coordinates in matplotlib I'm trying to plot a series of rectangles and lines based on a tab delimited text file in matplotlib. The coordinates are quite large in the data and shown be drawn to scale -- except scaled down by some factor X -- in matplotlib. What's the easiest way to do this in matplo...
transforming coordinates in matplotlib
I'm trying to plot a series of rectangles and lines based on a tab delimited text file in matplotlib. The coordinates are quite large in the data and shown be drawn to scale -- except scaled down by some factor X -- in matplotlib. What's the easiest way to do this in matplotlib? I know that there are transformations,...
[ "If you simply use matplotlib's plot function, the plot will fit into one online window, so you don't really need to 'rescale' explicitly. Linearly rescaling is pretty easy, if you include some code sample to show your formatting of the data, somebody can help you in translating the origin and scaling the coordinat...
[ 0 ]
[]
[]
[ "matplotlib", "numpy", "python", "scipy" ]
stackoverflow_0005463924_matplotlib_numpy_python_scipy.txt
Q: python print statement with utf-8 and nohup I have a some python code that prints log messages. When run at the command line, it does fine with utf-8. Log messages that contain special characters print out fine. However, when run in the background under nohup, it barfs on utf-8 characters. nohup python2.7 myPro...
python print statement with utf-8 and nohup
I have a some python code that prints log messages. When run at the command line, it does fine with utf-8. Log messages that contain special characters print out fine. However, when run in the background under nohup, it barfs on utf-8 characters. nohup python2.7 myProgram.py & The error I see is the usual "try to e...
[ "Use PYTHONIOENCODING:\nexport PYTHONIOENCODING=utf-8\nnohup python2.7 myProgram.py &\n\n\nFor example, if \nmyProgram.py:\nunicode_obj=u'\\N{INFINITY}'\nprint(unicode_obj) \n\nthen running\nnohup python2.7 myProgram.py > /tmp/test &\n\nproduces\n/tmp/test:\nUnicodeEncodeError: 'ascii' codec can't encode charact...
[ 23 ]
[]
[]
[ "nohup", "python", "utf_8" ]
stackoverflow_0005626960_nohup_python_utf_8.txt
Q: Convert Python 3 to "simple" python that can be read by autodoc I have a written a program in Python 3 and are using Sphinx to document it. Sphinx's autodoc is great, however it only works with Python 2. Some modules work fine in autodoc, however modules don't. Some examples: Python 2 complains about Python 3 styl...
Convert Python 3 to "simple" python that can be read by autodoc
I have a written a program in Python 3 and are using Sphinx to document it. Sphinx's autodoc is great, however it only works with Python 2. Some modules work fine in autodoc, however modules don't. Some examples: Python 2 complains about Python 3 style metaclasses, and some modules which don't exist anymore in Python 2...
[ "You can just install the development version of sphinx, which supports python 3.\npip-3.2 install hg+https://bitbucket.org/birkenfeld/sphinx\n\nI tested the autodoc feature on your class and it worked.\n", "What tends to be the solution is sprinkling try/except clauses in your code.\nPython 2.6 has configparser ...
[ 5, 1, 0 ]
[]
[]
[ "autodoc", "python", "python_sphinx" ]
stackoverflow_0005605851_autodoc_python_python_sphinx.txt
Q: Write PDF file from URL using urllib2 I'm trying to save a dynamic pdf file generated from a web server using python's module urllib2. I use following code to get data from server and to write that data to a file in order to store the pdf in a local disk.: import urllib2 import cookielib theurl = 'https://myweb.c...
Write PDF file from URL using urllib2
I'm trying to save a dynamic pdf file generated from a web server using python's module urllib2. I use following code to get data from server and to write that data to a file in order to store the pdf in a local disk.: import urllib2 import cookielib theurl = 'https://myweb.com/?pdf&var1=1' cj = cookielib.CookieJar() ...
[ "Try changing,\nFILE = open('report.pdf', \"w\")\n\nto\nFILE = open('report.pdf', \"wb\")\n\nThe extra 'b' indicates to write in binary mode. Currently you are writing a binary file in ASCII/text mode.\n" ]
[ 17 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0005627083_python_urllib2.txt
Q: How can I avoid type checking a python object if its attributes aren't used? I've come across answers here for type checking in general, type checking for numbers, and type checking for strings. Most people seem to respond by saying that type checking should never be performed in python (< 2.6) due to duck typing...
How can I avoid type checking a python object if its attributes aren't used?
I've come across answers here for type checking in general, type checking for numbers, and type checking for strings. Most people seem to respond by saying that type checking should never be performed in python (< 2.6) due to duck typing. My (limited) understanding of duck typing is that type is determined by use of ...
[ "A common duck-typish Python solution to this problem is to (try to) convert what you got to what you need. For example, if you need an integer:\ndef getconstants(arg):\n try:\n arg = int(arg)\n except:\n raise TypeError(\"expected integer, or something that can be converted to one, but got \" +...
[ 6, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005626815_python.txt
Q: Storing interesting words from a sentence I have a sentence like the cat sat on the mat stored as a single sql field. I want to periodically search for keywords which are not not in a stop list, in this case cat sat mat What's the best way to store them in an SQL table for quick searching? As far as I can see it...
Storing interesting words from a sentence
I have a sentence like the cat sat on the mat stored as a single sql field. I want to periodically search for keywords which are not not in a stop list, in this case cat sat mat What's the best way to store them in an SQL table for quick searching? As far as I can see it I see the following options Up to [n] additio...
[ "I would suggest giving your sentences a key, likely IDENTITY. I would then create a second table linking to your sentence table, with a row for each interesting word. \nIf you'd like to search for say, words starting with ca- if you stored these words in a comma delimited you'd have to wildcard the start and end, ...
[ 1, 1, 1 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0005627140_python_sql_sqlite.txt
Q: python: library behavior on failed import Is there any standard practice on how a library should behave, when certain module can't be imported? Should it just let an exception fly or should it rather catch it and exit elegantly with a proper information? For example I have something like this: try: from argpars...
python: library behavior on failed import
Is there any standard practice on how a library should behave, when certain module can't be imported? Should it just let an exception fly or should it rather catch it and exit elegantly with a proper information? For example I have something like this: try: from argparse import ArgumentParser except ImportError: ...
[ "A library should always raise an ImportError instead of exiting; the program may want to conditionally include it (perhaps replacing it when it is not available).\nIf a lower-level module raises ImportError, your best shot is to re-raise it with extra information attached.\n", "If you can, distribute the module ...
[ 4, 2, 0 ]
[]
[]
[ "import", "importerror", "python" ]
stackoverflow_0005627578_import_importerror_python.txt
Q: Libsvm python error I'm trying to figure out what is the proper format of a python list to be given as input to a svm_problem function in python. I got the following program from the web, stackoverflow. I have the following: from svm import * x=[ [1,0,1],[-1,0,-1],[1,0,0]] #x=[ [1,0,1],[-1,0,-1]] prob = svm_proble...
Libsvm python error
I'm trying to figure out what is the proper format of a python list to be given as input to a svm_problem function in python. I got the following program from the web, stackoverflow. I have the following: from svm import * x=[ [1,0,1],[-1,0,-1],[1,0,0]] #x=[ [1,0,1],[-1,0,-1]] prob = svm_problem( [1,-1],x ) param = sv...
[ "svm_problem() takes two parameters: the first parameter of a vector of labels, and the second is a matrix of features. You get this assertion error because you are only specifying 2 labels, [1, -1], as the first parameter in your call to svm_problem.\nExample:\ny = [1,-1,1,1]\nx = [[1,0,1], [-1,0,-1], [1,2,3], [4,...
[ 2, 0 ]
[]
[]
[ "libsvm", "python" ]
stackoverflow_0005627551_libsvm_python.txt
Q: Need to assign value to a dictionary, whose name is stored in a variable (Python) I have 2 questions pertaining to following code: data = csv.DictReader(open('dc_sample.csv'), delimiter=',') device_names = ['dev1', 'dev2', 'dev3'] # for row in data: for word in device_names: # name = wo...
Need to assign value to a dictionary, whose name is stored in a variable (Python)
I have 2 questions pertaining to following code: data = csv.DictReader(open('dc_sample.csv'), delimiter=',') device_names = ['dev1', 'dev2', 'dev3'] # for row in data: for word in device_names: # name = word + '_data' # To create dictionaries with variable names (eg. dev1_data) ...
[ "Things like word + 'data' = ... do not work. You don't need to do that at all. Why would you want \"to create dictionaries with variable names\"? You should simply use a dictionary:\noutput = {}\nfor row in data:\n for word in device_names: \n name = word + '_data' # To create dictionaries with variable ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005613882_python.txt
Q: Test if a class is inherited from another This question is more Python related than Django related. I want to test write a test for this function that I am using to get a Django form dynamically with the fields I set. def quiz_form_factory(question): properties = { 'question': forms.IntegerField(widge...
Test if a class is inherited from another
This question is more Python related than Django related. I want to test write a test for this function that I am using to get a Django form dynamically with the fields I set. def quiz_form_factory(question): properties = { 'question': forms.IntegerField(widget=forms.HiddenInput, initial=question.id), ...
[ "Use issubclass(myclass, parentclass).\nIn your case:\nself.assertTrue( issubclass(QuizForm, forms.Form) )\n\n", "Use the built-in issubclass function. e.g.\nissubclass(QuizForm, forms.Form)\n\nIt returns a bool so you can use it directly in self.assertTrue()\n" ]
[ 151, 13 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0005628084_python_unit_testing.txt
Q: Using components in Javascript I'm relatively new to Javascript. I was wondering if it supports components and objects like Python does. If it does, what would the syntax look like? For instance, I know an object look like this: function Foo(a, b) { this.a = a; this.b = b; } Now, is there a way to declare...
Using components in Javascript
I'm relatively new to Javascript. I was wondering if it supports components and objects like Python does. If it does, what would the syntax look like? For instance, I know an object look like this: function Foo(a, b) { this.a = a; this.b = b; } Now, is there a way to declare some components, pick one of those,...
[ "I have no idea what you mean by components. The term is too generalized. In Delphi, a component is a non-visible code module which introduces some special functionality to the application. A \"timer\" is one such example of a component (in Delphi).\nGuessing from your description, you seem to want to add propertie...
[ 1, 1, 0, 0 ]
[]
[]
[ "components", "javascript", "python" ]
stackoverflow_0005627874_components_javascript_python.txt
Q: Manipulating Dictionary Values Python I have a dictionary with the following values. d = {'a': 0, 'b': 1, 'c': 2} print d['c'] This would print 2. How would I go about changing the value for a given key word? So that when the keyword 'c' was given it would return something besides 2. A: Just set it using...
Manipulating Dictionary Values Python
I have a dictionary with the following values. d = {'a': 0, 'b': 1, 'c': 2} print d['c'] This would print 2. How would I go about changing the value for a given key word? So that when the keyword 'c' was given it would return something besides 2.
[ "Just set it using the key:\n>>> d = {'a': 0, 'b': 1, 'c': 2}\n>>> print d['c']\n2\n>>> d['c'] = 9000\n>>> print d['c']\n9000\n\n" ]
[ 6 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005628458_dictionary_python.txt
Q: Screen-Scraping: Processing a POST Login I'm somewhat new to screen-scraping and I'm trying to automate logging into my bank. I figured that I could essentially do the following: Using the source of the bank's web page, some tools, and some clever hackery, determine where they're posting the login data to and ho...
Screen-Scraping: Processing a POST Login
I'm somewhat new to screen-scraping and I'm trying to automate logging into my bank. I figured that I could essentially do the following: Using the source of the bank's web page, some tools, and some clever hackery, determine where they're posting the login data to and how it's formatted. Mimick this in Python. World...
[ "It may be useful for you to check out mechanize for complex browser automation such as this.\nAlso, have you heard of Charles Proxy? It's essentially like Wireshark, but tailored for web development, and I suspect it will help you enormously during development.\n", "Try replicating all those headers listed, par...
[ 3, 0 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0005591379_python_screen_scraping.txt
Q: Image compositing I have an album title of some music band. I want to draw it with some mask which will round the corners of image. So, I've prepared such mask in gimp: I'm using white mask, but it's invisible at white background here. So, here is the code of rendering: # Draw album image img = cairo.ImageSurface...
Image compositing
I have an album title of some music band. I want to draw it with some mask which will round the corners of image. So, I've prepared such mask in gimp: I'm using white mask, but it's invisible at white background here. So, here is the code of rendering: # Draw album image img = cairo.ImageSurface.create_from_png('image...
[ "You need to share your surface creation code as well, here's some code I extended from your example:\nimport cairo\n\nsurface = cairo.ImageSurface (cairo.FORMAT_ARGB32, 128, 128)\nctx = cairo.Context (surface)\n\nposX = posY = 0\n\nimg = cairo.ImageSurface.create_from_png('sample.png') \nctx.set_source_surface(im...
[ 8 ]
[]
[]
[ "cairo", "composite", "image", "python" ]
stackoverflow_0005541582_cairo_composite_image_python.txt