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:
Get an IP adress of a client of a SOAP service
I'm writing a SOAP service using python and soaplib. I need to get IP adresses of all clients of the service to store them to the log file. How can I do that?
A:
One way to do this is to implement a "hook" which is called at different stages of the wsgi executation.... | Get an IP adress of a client of a SOAP service | I'm writing a SOAP service using python and soaplib. I need to get IP adresses of all clients of the service to store them to the log file. How can I do that?
| [
"One way to do this is to implement a \"hook\" which is called at different stages of the wsgi executation. See the section \"Hooks\" in the soaplib readme file for details and the example hook.py in that distribution. \nFor example, you could implement onMethodExec and then use the wsgi environ.get('REMOTE_ADDR'... | [
1
] | [] | [] | [
"python",
"soap"
] | stackoverflow_0003253036_python_soap.txt |
Q:
python 2.x or 3.x
Since there is a python 3.x, why don't we use it?
Why do we still use 2.x?What's the difference?
A:
Python 2.6 and 2.7 have been written to ease the transition to Python 3.
It will take some more time to port the more complex packages (i.e. those with many dependencies, or libraries written in ... | python 2.x or 3.x | Since there is a python 3.x, why don't we use it?
Why do we still use 2.x?What's the difference?
| [
"Python 2.6 and 2.7 have been written to ease the transition to Python 3.\nIt will take some more time to port the more complex packages (i.e. those with many dependencies, or libraries written in C).\nSo if you are starting new projects, and all the libraries you need are there, it makes sense to start with 3.1. O... | [
14,
8,
6,
5,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003253430_python_python_3.x.txt |
Q:
Need some advice regarding writing an reusable app for Django
I need to implement a finite-state-machine in order to keep track of a few of my Django project models. I already have a similar app doing that but it's heavily coupled with the others apps models and not reusable in any way. So I decided to re-factor i... | Need some advice regarding writing an reusable app for Django | I need to implement a finite-state-machine in order to keep track of a few of my Django project models. I already have a similar app doing that but it's heavily coupled with the others apps models and not reusable in any way. So I decided to re-factor it.
After a few hours, this is what I came up with:
class StateMachi... | [
"I implemented myself a finite-state machine in python ... The code of the machine module itself has no Django... However, this machine was used to manage a state attribute on a Django model.\nI think that the only field you really need to have is a state field. The rest should be only python declarations (unless y... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003253235_django_python.txt |
Q:
Pass list as argument to Python C module?
I found this nice example of a Python C Module, where a single integer is passed along as the only argument. How can I instead pass a python list as argument?
A:
From http://code.activestate.com/lists/python-list/31841/:
...
char * tok; /* delimiter tokens for st... | Pass list as argument to Python C module? | I found this nice example of a Python C Module, where a single integer is passed along as the only argument. How can I instead pass a python list as argument?
| [
"From http://code.activestate.com/lists/python-list/31841/:\n...\nchar * tok; /* delimiter tokens for strtok */\nint cols; /* number of cols to parse, from the left */\n\nint numLines; /* how many lines we passed for parsing */\nchar * line; /* pointer to the line as a string */\nchar... | [
16,
0
] | [] | [] | [
"arguments",
"c",
"integration",
"list",
"python"
] | stackoverflow_0003253563_arguments_c_integration_list_python.txt |
Q:
Django Test Client Like Tool?
I've got to know and love the Django Test client. I'd really like to use it to test external sites and URLs outside of the current project.
Is this possible?
If not, is there something similar I could use? (ideally in Python)
I don't need to do anything dramatic, just, say, grab a ... | Django Test Client Like Tool? | I've got to know and love the Django Test client. I'd really like to use it to test external sites and URLs outside of the current project.
Is this possible?
If not, is there something similar I could use? (ideally in Python)
I don't need to do anything dramatic, just, say, grab a URL and check the status code, chec... | [
"No, it doesn't work like that. It's not a real web client, it's just a piece of internal Django code that catches the request and returns the relevant response.\nThe best tool for the sort of testing you're talking about is something like Selenium.\n"
] | [
3
] | [] | [] | [
"django",
"python",
"testing"
] | stackoverflow_0003253747_django_python_testing.txt |
Q:
Eclipse using multiple Python interpreters with execnet
I'm using the execnet package to allow communication between Python scripts interpreted by different Python interpreters.
The following code (test_execnet.py):
import execnet
for python_version in ('python', 'python3'):
try:
gw = execn... | Eclipse using multiple Python interpreters with execnet | I'm using the execnet package to allow communication between Python scripts interpreted by different Python interpreters.
The following code (test_execnet.py):
import execnet
for python_version in ('python', 'python3'):
try:
gw = execnet.makegateway("popen//python="+python_version)
c... | [
"seems like pydev does site-customizations and particularly modifies things for interactive/console usage (judging from a very quick skim of http://github.com/aptana/Pydev/blob/master/plugins/org.python.pydev/pysrc/pydev_sitecustomize/sitecustomize.py ). This is not useful or fitting for execnet-mediated processes.... | [
3,
1
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0003248271_eclipse_pydev_python.txt |
Q:
Python copy : How to inherit the default copying behaviour?
Ok ... It might be a stupid question ... but I'm not finding the answer right now !
I need to realize the copy of an object, for which I want all the attributes to be copied, except one or two for which I want to fully control the copy.
Here is the standa... | Python copy : How to inherit the default copying behaviour? | Ok ... It might be a stupid question ... but I'm not finding the answer right now !
I need to realize the copy of an object, for which I want all the attributes to be copied, except one or two for which I want to fully control the copy.
Here is the standard copying behaviour for an object :
>>> class test(object):
... ... | [
"You could just do:\ndef __copy__(self):\n clone = copy.deepcopy(self)\n clone._b = some_op(clone._b)\n return clone\n\nThis will work because deepcopy avoids recursion. From the python docs:\n\nThe deepcopy() function avoids these problems by:\n keeping a “memo” dictionary of objects already copied duri... | [
5,
3,
2
] | [] | [] | [
"copy",
"python"
] | stackoverflow_0003253439_copy_python.txt |
Q:
How to get only text of a webpage with Python, just as Select-all & Copy in browser?
I want to get "Main content" instead of < tag> Main content , where the latter is html code and could be retrieved using urllib.urlopen(url).
Just as you open the url in browser, select all text and then copy&paste.
Is there a pos... | How to get only text of a webpage with Python, just as Select-all & Copy in browser? | I want to get "Main content" instead of < tag> Main content , where the latter is html code and could be retrieved using urllib.urlopen(url).
Just as you open the url in browser, select all text and then copy&paste.
Is there a possible way for this with Python?
Thanks.
| [
"Have a look at Beautiful Soup.\n\nBeautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:\n\nBeautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003254012_python.txt |
Q:
Having trouble with py.test remote
I love py.test and am trying to get the remote test execution feature to work so I can run tests on a remote machine. There is very little doc and I am getting frustrated with it. Any help figuring out what I am doing wrong is appreciated. Here is my command line on the main s... | Having trouble with py.test remote | I love py.test and am trying to get the remote test execution feature to work so I can run tests on a remote machine. There is very little doc and I am getting frustrated with it. Any help figuring out what I am doing wrong is appreciated. Here is my command line on the main server:
c:\Python26\Scripts\py.test --dis... | [
"Could you try to rerun with latest versions of pytest and pytest-xdist? \n"
] | [
0
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0002174238_pytest_python.txt |
Q:
Python string to attribute
How can I achieve such job:
def get_foo(someobject, foostring):
return someobject.foostring
IE:
if I do get_foo(obj, "name") it should be calling obj.name (see input as string but I call it as an attritube.
Thanks
A:
Use the builtin function getattr.
getattr(object, name[, defaul... | Python string to attribute | How can I achieve such job:
def get_foo(someobject, foostring):
return someobject.foostring
IE:
if I do get_foo(obj, "name") it should be calling obj.name (see input as string but I call it as an attritube.
Thanks
| [
"Use the builtin function getattr.\n\ngetattr(object, name[, default])\nReturn the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If th... | [
116,
50,
36
] | [] | [] | [
"attributes",
"python"
] | stackoverflow_0003253966_attributes_python.txt |
Q:
mod_python.publisher: nothing to publish
HI,
I get the following error on executing a script:
[Thu Jul 15 17:32:02 2010] [error] [client 127.0.0.1] mod_python.publisher: nothing to publish., referer: http://localhost/test/mptest.py/ff
What does this mean and how can I resolve this?
A:
here's some useful informa... | mod_python.publisher: nothing to publish | HI,
I get the following error on executing a script:
[Thu Jul 15 17:32:02 2010] [error] [client 127.0.0.1] mod_python.publisher: nothing to publish., referer: http://localhost/test/mptest.py/ff
What does this mean and how can I resolve this?
| [
"here's some useful information\nmod_python publisher\n"
] | [
0
] | [] | [] | [
"mod_python",
"python"
] | stackoverflow_0003254276_mod_python_python.txt |
Q:
Dumps and loads in django
from django.utils.simplejson import dumps, loads
# -*- coding: utf-8 -*-
def index(request):
return render_to_response('test2/index.html')
def add_lang(request):
logging.debug("Got request")
a = request.POST
logging.debug(a["lang"])
lang=dumps(a["lang"])
l = Lan... | Dumps and loads in django | from django.utils.simplejson import dumps, loads
# -*- coding: utf-8 -*-
def index(request):
return render_to_response('test2/index.html')
def add_lang(request):
logging.debug("Got request")
a = request.POST
logging.debug(a["lang"])
lang=dumps(a["lang"])
l = Language(code=lang)
l.save()
l... | [
"Not without writing a custom filter.\n"
] | [
1
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0003254381_django_django_templates_django_views_python.txt |
Q:
only() method in Python?
I have these lines in Python:
page = lxml.html.parse(URL).getroot()
table = only(page.cssselect('table[width=510]'))
What is the only method doing? I can't find it in the Python docs (though that might just be because it's very hard to search for!)
thanks.
A:
There is no only built-in f... | only() method in Python? | I have these lines in Python:
page = lxml.html.parse(URL).getroot()
table = only(page.cssselect('table[width=510]'))
What is the only method doing? I can't find it in the Python docs (though that might just be because it's very hard to search for!)
thanks.
| [
"There is no only built-in function, as you'll see if you type help(only) into your Python interpreter.\nIt must be pulled into the namespace with a from <module> import <only|*> instruction in that module. When you find this, you could try importing the module in your Python interpreter and using the help function... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003254363_python.txt |
Q:
i need to question my database about a word received from another aplication, my tables are related on a many to many relashionship
i have 2 tables one market, another brand , so when a client search for a brand i need to return all the markets where he can find that brand.
A:
assuming your dd looks like this:
m... | i need to question my database about a word received from another aplication, my tables are related on a many to many relashionship | i have 2 tables one market, another brand , so when a client search for a brand i need to return all the markets where he can find that brand.
| [
"assuming your dd looks like this:\nmarket(id, name)\nbrand(id, name)\nmarket_brand(fk_market_id, fk_brand_id)\nyour query would look something like this:\nselect m.name\n from brand b\n join market_brand mb on mb.fk_brand_id = b.id\n join market m on m.id = mb.fk_market_id\n where b.name = 'your_brand'\n\n"
] | [
0
] | [] | [] | [
"mysql",
"python",
"sql"
] | stackoverflow_0003254581_mysql_python_sql.txt |
Q:
Generating passwords in Python 3.1.1
I am looking to generate passwords using strings typed by the user, the book I am reading recommends using sha over md5 because it is considered stronger.
sha however has been deprecated and I am now using the hashlib module to encrypt me strings in a similar way to that shown ... | Generating passwords in Python 3.1.1 | I am looking to generate passwords using strings typed by the user, the book I am reading recommends using sha over md5 because it is considered stronger.
sha however has been deprecated and I am now using the hashlib module to encrypt me strings in a similar way to that shown here: http://docs.python.org/py3k/library/... | [
"There is no \"sha\" algorithm. The sha1 algorithm is much stronger than md5, since md5 is completely broken. I believe there is an algorithm that takes microseconds to generate a collision.\nSha1 has been considerably weakened by cryptanalysts, and the search is on for the next big thing, but it is still currently... | [
7
] | [
"Comparing the hash of the password with a saved hash is a suitable method for authentication.\n"
] | [
-1
] | [
"encryption",
"passwords",
"python",
"python_3.x"
] | stackoverflow_0003254713_encryption_passwords_python_python_3.x.txt |
Q:
Python Framework for Desktop Database Application
Is there a framework to develop Desktop Database applications (some screens with CRUD screens) for Python? I am looking for something similar to Windows Forms, with the ability to associate TextField, Combos and other UI metaphors with datasets connected to relatio... | Python Framework for Desktop Database Application | Is there a framework to develop Desktop Database applications (some screens with CRUD screens) for Python? I am looking for something similar to Windows Forms, with the ability to associate TextField, Combos and other UI metaphors with datasets connected to relational databases such as MySQL, SQLServer, Oracle or Postg... | [
"Camelot\n",
"PyQT should be able to do that, altough I never used it myself (See this article)\n"
] | [
5,
3
] | [] | [] | [
"database",
"desktop",
"frameworks",
"python"
] | stackoverflow_0003255665_database_desktop_frameworks_python.txt |
Q:
Implementing a SAML client in Python
I'd like to integrate a web site written in Python (using Pylons) with an existing SAML based authentication service. From reading about SAML, I believe that the IdP (which already exists in this scenario) will send an XML document (via browser post) to the Service Provider (w... | Implementing a SAML client in Python | I'd like to integrate a web site written in Python (using Pylons) with an existing SAML based authentication service. From reading about SAML, I believe that the IdP (which already exists in this scenario) will send an XML document (via browser post) to the Service Provider (which I am implementing). The Service Prov... | [] | [] | [
"I know you are looking for a Python based solution but there are quite a few \"server\" based solutions that would potentially solve your problem as well and require few ongoing code maintenance issues. \nFor example, using the Apache or IIS Integration kits in conjunction with the PingFederate server from www.pin... | [
-1
] | [
"authentication",
"python",
"saml",
"single_sign_on"
] | stackoverflow_0003198104_authentication_python_saml_single_sign_on.txt |
Q:
Is there any reasonable SSDP or DIDL Lib for java/groovy/python?
For a future project I am looking for a library to handle SSDP communication and messages in DIDL-Lite xml dialect. Is there any reasonable implementation of java, groovy or python?
I don't like to use implementations of existing UPnP stacks like cy... | Is there any reasonable SSDP or DIDL Lib for java/groovy/python? | For a future project I am looking for a library to handle SSDP communication and messages in DIDL-Lite xml dialect. Is there any reasonable implementation of java, groovy or python?
I don't like to use implementations of existing UPnP stacks like cybergarage or the frauenhofer UPnP stack because they are highly depend... | [
"http://teleal.org/projects/cling\nOpen Source DLNA/UPnP stack, libraries, and tools for Java and Android developers\nCling is very modular, so you could only use its SSDP functionality. You can integrate it with your existing code at any level (data transport, protocol execution, etc). \nThe Cling Support package ... | [
3
] | [] | [] | [
"groovy",
"java",
"python",
"upnp"
] | stackoverflow_0000630296_groovy_java_python_upnp.txt |
Q:
wx.ProgressDialog disappears
The progress dialog disappers rather then the cancel button changing to a close button when it is to be destroyed (and the PD_AUTO_HIDE flag is not set).
progressDlg = wx.ProgressDialog("Organizing music files",
"This may take some time..",
... | wx.ProgressDialog disappears | The progress dialog disappers rather then the cancel button changing to a close button when it is to be destroyed (and the PD_AUTO_HIDE flag is not set).
progressDlg = wx.ProgressDialog("Organizing music files",
"This may take some time..",
... | [
"Destroy() explicitly deletes the actual control. I'm pretty sure Destroy()ing a progressdialog behaves as every other control\n"
] | [
0
] | [] | [] | [
"progressdialog",
"python",
"wxpython"
] | stackoverflow_0003251721_progressdialog_python_wxpython.txt |
Q:
Linear interpolation on a numpy array
I have the following numpy array:
# A B C Y
my_arr = np.array([ [.20, .54, .26], # <0
[.22, .54, .24], # 1
[.19, .56, .25], # 2
[.19, .58, .23], # 3
... | Linear interpolation on a numpy array | I have the following numpy array:
# A B C Y
my_arr = np.array([ [.20, .54, .26], # <0
[.22, .54, .24], # 1
[.19, .56, .25], # 2
[.19, .58, .23], # 3
[.17, .62, .21] ]) # 4+
if a user ent... | [
"from scipy import array, ndimage\n\n# A B C Y\nm = array([ [.20, .54, .26], # 0\n [.22, .54, .24], # 1\n [.19, .56, .25], # 2\n [.19, .58, .23], # 3\n [.17, .62, .21] ]) # 4\n\ninputs = array([-1, 0, 0.2, 1, 1.5, 2, 2.5, 3, 4,... | [
6,
2
] | [] | [] | [
"interpolation",
"numpy",
"python",
"scipy"
] | stackoverflow_0003255816_interpolation_numpy_python_scipy.txt |
Q:
save gtk.DrawingArea to file
I want to save gtk.DrawingArea() object contents to jpeg file using PIL. Particularly I want add to this script possibility to make photo. I found how to save image to jpeg. All I need - get pixbuf object from gtk.DrawingArea() object. How can I do this?
A:
If you're not married to ... | save gtk.DrawingArea to file | I want to save gtk.DrawingArea() object contents to jpeg file using PIL. Particularly I want add to this script possibility to make photo. I found how to save image to jpeg. All I need - get pixbuf object from gtk.DrawingArea() object. How can I do this?
| [
"If you're not married to the idea of using gstreamer, you can use OpenCV instead. This post gives a great example using pygame.\nHowever, you can get the pixbuf this way (and you don't even need PIL):\ndef get_picture(self, event, data):\n drawable = self.movie_window.window\n colormap = drawable.get_colorma... | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003254499_gtk_pygtk_python.txt |
Q:
How to convert bytes in a string to integers? Python
I want to get a list of ints representing the bytes in a string.
A:
One option for Python 2.6 and later is to use a bytearray:
>>> b = bytearray('hello')
>>> b[0]
104
>>> b[1]
101
>>> list(b)
[104, 101, 108, 108, 111]
For Python 3.x you'd need a bytes object ... | How to convert bytes in a string to integers? Python | I want to get a list of ints representing the bytes in a string.
| [
"One option for Python 2.6 and later is to use a bytearray:\n>>> b = bytearray('hello')\n>>> b[0]\n104\n>>> b[1]\n101\n>>> list(b)\n[104, 101, 108, 108, 111]\n\nFor Python 3.x you'd need a bytes object rather than a string in any case and so could just do this:\n>>> b = b'hello'\n>>> list(b)\n[104, 101, 108, 108, 1... | [
14,
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0003255987_python.txt |
Q:
What other Language synergizes well with Python? Need Advice
Ok so I know the basics of programming languages, I've studied python and liked it a lot. I'm studying now the intermediate parts of python and I'm catching the concepts already. I'm working with a project and at the same time solving computer problems t... | What other Language synergizes well with Python? Need Advice | Ok so I know the basics of programming languages, I've studied python and liked it a lot. I'm studying now the intermediate parts of python and I'm catching the concepts already. I'm working with a project and at the same time solving computer problems that practices algorithm use. I've learned that python has limitati... | [
"What is wrong with IronPython or Jython? You can learn how to write libraries in Java or .Net to alleviate some of Python's speed problems. Learning to write your own Python libraries will certainly help you better understand and overcome the limitations you mentioned.\n",
"For me, the obvious choice to learn af... | [
1,
1,
1,
1,
0
] | [] | [] | [
"paradigms",
"python"
] | stackoverflow_0003255925_paradigms_python.txt |
Q:
Django-Haystack + Whoosh - Are misspelling suggestions possible?
I'm using Whoosh and Django-Haystack. I would like to make use of query suggestions for when users mistype words.
e.g. Maybe you meant "unicorn"
Is it necessary to use another search engine? Or can I successfully achieve this with Whoosh?
A:
Hays... | Django-Haystack + Whoosh - Are misspelling suggestions possible? | I'm using Whoosh and Django-Haystack. I would like to make use of query suggestions for when users mistype words.
e.g. Maybe you meant "unicorn"
Is it necessary to use another search engine? Or can I successfully achieve this with Whoosh?
| [
"Haystack lets you enable spelling suggestions, and that does work with Whoosh.\n",
"I have no experience with Whoosh, but comparing edit distance and rolling your own wouldn't be too complex, if necessary.\n"
] | [
4,
0
] | [] | [] | [
"django",
"django_haystack",
"full_text_search",
"python",
"whoosh"
] | stackoverflow_0003256177_django_django_haystack_full_text_search_python_whoosh.txt |
Q:
Parse a cron entry in Python
All. I am trying to find a python module that I can use to parse a cron entry and get the next time it will run. With perl I use the Schedule::Cron::Events module but I would like to convert to python. Thanks in advance.
A:
The documentation for python-crontab is in docstrings in the... | Parse a cron entry in Python | All. I am trying to find a python module that I can use to parse a cron entry and get the next time it will run. With perl I use the Schedule::Cron::Events module but I would like to convert to python. Thanks in advance.
| [
"The documentation for python-crontab is in docstrings in the source code, as is usual for python. You can also explore the documentation via the python interpreter with the built-in help() function. The full source for python-crontab is less than 500 lines anyway and is very readable.\nExample from the source code... | [
8,
4,
2
] | [] | [] | [
"cron",
"module",
"python"
] | stackoverflow_0001511854_cron_module_python.txt |
Q:
Python Deque appendleft with list
I am currently creating my deque object using the following,
self.CommandList = deque((['S', False, 60],['c'],['g16'],['i50'],['r30', True],['u320'],['o5000'],['b1'],['B4500'],['W1'],['l5154'],['!10'],['p2', True, 10],['e1'],['K20'],['U0'],['Y0']))
But I wish to add a similar lis... | Python Deque appendleft with list | I am currently creating my deque object using the following,
self.CommandList = deque((['S', False, 60],['c'],['g16'],['i50'],['r30', True],['u320'],['o5000'],['b1'],['B4500'],['W1'],['l5154'],['!10'],['p2', True, 10],['e1'],['K20'],['U0'],['Y0']))
But I wish to add a similar list to the queue later but using appendle... | [
"I think you want .extendleft here. This will \"extend the list\" instead of just appending the list as one element.\nz = collections.deque([1,2,3,4]) # [1, 2, 3, 4]\n\nz.appendleft(['bad', 'news']) # [ ['bad', 'news'], 1, 2, 3, 4 ]\nz.extendleft(['good', 'news']) # [ 'good', 'news', ['bad', 'news'], 1, 2, 3, ... | [
17
] | [] | [] | [
"deque",
"list",
"python"
] | stackoverflow_0003256377_deque_list_python.txt |
Q:
How to create a notification server which informs Delphi application when database changes?
We need to be able to inform a Delphi application in case there are changes to some of our tables in MySQL.
Delphi clients are in the Internet behind a firewall, and they have to be authenticated before connecting to the no... | How to create a notification server which informs Delphi application when database changes? | We need to be able to inform a Delphi application in case there are changes to some of our tables in MySQL.
Delphi clients are in the Internet behind a firewall, and they have to be authenticated before connecting to the notification server we need to implement. The server can be programmed using for example Java, PHP ... | [
"Answer to the First Question:\ncheck this question and answers on Stack Overflow:\nWhen a new row in database is added, an external command line program must be invoked\nIn theory, a simple user-defined function could be used to fire a 'row changed' message to a message broker / queue. But this involves external s... | [
5,
1,
0
] | [] | [] | [
"delphi",
"java",
"mysql",
"php",
"python"
] | stackoverflow_0003255330_delphi_java_mysql_php_python.txt |
Q:
Catching http errors
how can I catch the 404 and 403 errors for pages in python and urllib(2), for example?
Are there any fast ways without big class-wrappers?
Added info (stack trace):
Traceback (most recent call last):
File "test.py", line 3, in <module>
page = urllib2.urlopen("http://localhost:4444")
Fi... | Catching http errors | how can I catch the 404 and 403 errors for pages in python and urllib(2), for example?
Are there any fast ways without big class-wrappers?
Added info (stack trace):
Traceback (most recent call last):
File "test.py", line 3, in <module>
page = urllib2.urlopen("http://localhost:4444")
File "/usr/lib/python2.6/url... | [
"import urllib2 \ntry:\n page = urllib2.urlopen(\"some url\")\nexcept urllib2.HTTPError, err:\n if err.code == 404:\n print \"Page not found!\"\n elif err.code == 403:\n print \"Access denied!\"\n else:\n print \"Something happened! Error code\", err.code\nexcept urllib2.URLError, err:\n ... | [
23,
5
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0003256576_python_urllib.txt |
Q:
How do I redirect different domain names requests to the same ip in django
I have one ip for two domain name, e.g. "www.example.com" and "example.info", and I want each of them to be handled as a different domain (e.g. www.example.com/photos and example.info/photos will be ahndled each by its corresponding functio... | How do I redirect different domain names requests to the same ip in django | I have one ip for two domain name, e.g. "www.example.com" and "example.info", and I want each of them to be handled as a different domain (e.g. www.example.com/photos and example.info/photos will be ahndled each by its corresponding function). Is there an elegant way to do this in django?
| [
"You would do this by setting up different WSGI for each domain using a setting SITE_ID corresponding to the site id from the django.contrib.site app.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003256731_django_python.txt |
Q:
Call back in Python
Could some explain how call back methods work, and if possible, give me an example in Python? So as far as I understand them, they are methods which are provided by the user of an API, to the API, so that the user doesn't have to wait till that particular API function completes. So does the use... | Call back in Python | Could some explain how call back methods work, and if possible, give me an example in Python? So as far as I understand them, they are methods which are provided by the user of an API, to the API, so that the user doesn't have to wait till that particular API function completes. So does the user program continue execut... | [
"Callbacks are just user-supplied hooks. They allow you to specify what function to call in case of certain events. re.sub has a callback, but it sounds like you are dealing with a GUI, so I'll give a GUI example:\nHere is a very simple example of a callback:\nfrom Tkinter import *\n\nmaster = Tk()\n\ndef my_callba... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0003257093_python.txt |
Q:
Tweepy API: how to get a user's id from a status SearchResult object?
I'm trying to write a script to follow people on twitter. The tweepy API seems pretty good, but I'm running into some unintuitive behavior related to the mapping from user's ids to their screen names.
In [1]: import tweepy
In [2]: api = tweepy.... | Tweepy API: how to get a user's id from a status SearchResult object? | I'm trying to write a script to follow people on twitter. The tweepy API seems pretty good, but I'm running into some unintuitive behavior related to the mapping from user's ids to their screen names.
In [1]: import tweepy
In [2]: api = tweepy.API()
# get an arbitrary tweet
In [3]: tweet = api.search("anything")[0]
... | [
"Figured out the issue isn't a tweepy one:\nhttp://code.google.com/p/twitter-api/issues/detail?id=214\nUpdated for reference for any other tweepy users who run into the same issue.\n"
] | [
7
] | [] | [] | [
"python",
"tweepy",
"twitter"
] | stackoverflow_0003256981_python_tweepy_twitter.txt |
Q:
Copying files with Python under Windows
I'm trying to copy files inside a Python script using the following code:
inf,outf = open(ifn,"r"), open(ofn,"w")
outf.write(inf.read())
inf.close()
outf.close()
This works perfectly unedr OSX (and other UNIX flavors I suspect) but fails under Windows. Basically, the read()... | Copying files with Python under Windows | I'm trying to copy files inside a Python script using the following code:
inf,outf = open(ifn,"r"), open(ofn,"w")
outf.write(inf.read())
inf.close()
outf.close()
This works perfectly unedr OSX (and other UNIX flavors I suspect) but fails under Windows. Basically, the read() call returns far less bytes than the actual ... | [
"shutil is a better way to copy files anyway, but you need to open binary files in binary mode on Windows. It matters there. open(fname, 'rb')\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003257471_python.txt |
Q:
defining variable from string
I'm trying to define variable inside function. vars() shows variable is created, but gives me NameError: exception. What am I doing wrong?
def a(str1):
vars() [str1] = 1
print vars()
print b
a('b')
output:
{'str1': 'b', 'b': 1}
exception:
NameError: global name 'b' is ... | defining variable from string | I'm trying to define variable inside function. vars() shows variable is created, but gives me NameError: exception. What am I doing wrong?
def a(str1):
vars() [str1] = 1
print vars()
print b
a('b')
output:
{'str1': 'b', 'b': 1}
exception:
NameError: global name 'b' is not defined
| [
"You're invoking undefined behaviour. From the documentation of vars():\n\nNote The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.\n\nOther answers give possible solutions.\n",
"Your code works for me. Perhaps you should try an alternative approach:\nexec(... | [
4,
2,
1
] | [] | [] | [
"python",
"scope"
] | stackoverflow_0003257672_python_scope.txt |
Q:
How do I do threading in python?
I am trying to learn how to use threads with python. this is the code I have been studying:
import time
from threading import Thread
def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i
for i in range(10):... | How do I do threading in python? | I am trying to learn how to use threads with python. this is the code I have been studying:
import time
from threading import Thread
def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i
for i in range(10):
t = Thread(target=myfunc, args=(i... | [
"It sounds like a bug in IDLE, not a problem with Python. The error is coming from Tkinter, which is a Python GUI toolkit, and which IDLE probably uses. I would report it to whoever maintains IDLE.\n",
"Not everything runs properly under IDLE. This is because IDLE is a Python program in itself and has its own att... | [
1,
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003257834_multithreading_python.txt |
Q:
Single player 'pong' game
I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. I have the bas... | Single player 'pong' game | I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. I have the basic code, but the ball doesn't s... | [
"I can't help you because you did not post the complete code here. At least, I do not see where you're updating the positions of the sprites (self.x += self.dx somewhere?) and updating the draw to screen. You're also not utilising your classes in the main() function.\nThat said, I'm seeing\n def __init__(self, x=10... | [
1,
1
] | [] | [] | [
"livewires",
"pygame",
"python"
] | stackoverflow_0002674288_livewires_pygame_python.txt |
Q:
Dynamically add base class?
Let's say I have a base class defined as follows:
class Form(object):
class Meta:
model = None
method = 'POST'
Now a developer comes a long and defines his subclass like:
class SubForm(Form):
class Meta:
model = 'User'
Now suddenly the method attribute ... | Dynamically add base class? | Let's say I have a base class defined as follows:
class Form(object):
class Meta:
model = None
method = 'POST'
Now a developer comes a long and defines his subclass like:
class SubForm(Form):
class Meta:
model = 'User'
Now suddenly the method attribute is lost. How can I "get it back" ... | [
"As long as they won't override your __init__, or it will be called (ie by super), you can monkey-patch the Meta inner class:\nclass Form(object):\n class Meta:\n model = None\n method = \"POST\"\n\n def __init__(self, *args, **kwargs):\n if self.__class__ != Form:\n self.Meta.... | [
9,
4,
1,
1,
0
] | [] | [] | [
"inheritance",
"python",
"python_2.6",
"syntax"
] | stackoverflow_0003169502_inheritance_python_python_2.6_syntax.txt |
Q:
Executing Python program on web
Can I use os.system() or subprocess.call() to execute a Python program on a webserver?
I mean can I write these functions in a .py script and run it from a web browser and expect the program to be executed?
Thanks a lot.
EDIT:
Sorry for all the confusion, I am giving you more backgr... | Executing Python program on web | Can I use os.system() or subprocess.call() to execute a Python program on a webserver?
I mean can I write these functions in a .py script and run it from a web browser and expect the program to be executed?
Thanks a lot.
EDIT:
Sorry for all the confusion, I am giving you more background to my problem.
The reason I am t... | [
"You do not use os.system or subprocess.call to execute something as a cgi process.\nMaybe you should read the Python cgi tutorial here:\nhttp://www.cs.virginia.edu/~lab2q/\nIf you want your cgi process to communicate with another process on your local machine, you might want to look at \"REST frameworks\" for Pyth... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003257900_python.txt |
Q:
How much leeway do I have to leave myself to learn a new language?
I'm a relatively new hire, and I'm starting on a small, fairly simple project. The language that this project will be implemented in is still to be determined. The question basically boils down to - Java or Python?
Here's the dilemma: My manager w... | How much leeway do I have to leave myself to learn a new language? | I'm a relatively new hire, and I'm starting on a small, fairly simple project. The language that this project will be implemented in is still to be determined. The question basically boils down to - Java or Python?
Here's the dilemma: My manager would prefer it to be done in Python. I don't object to that, but I have ... | [
"I think it depends on the area of the project. While GUI is not hard in Python, any kind of GUI-framework will have a somewhat steep learning curve.\nIf it is a webapp, I'd say go for Python. The added time for learning is quickly gained back by easy of use of the many Python webframeworks.\nThe big risk is that y... | [
8,
7,
5,
4,
3,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"java",
"python"
] | stackoverflow_0002328230_java_python.txt |
Q:
Overcoming os.system() limitation in Python 2.3
I am having a problem converting one of my company's scripts from csh to Python. The csh script calls an aliased command, but when I call that same aliased command via os.system(), it does not work.
So, if foo is the aliased command:
CSH Script (this works, executes... | Overcoming os.system() limitation in Python 2.3 | I am having a problem converting one of my company's scripts from csh to Python. The csh script calls an aliased command, but when I call that same aliased command via os.system(), it does not work.
So, if foo is the aliased command:
CSH Script (this works, executes foo):
foo <argument>
Python (this does not work, er... | [
"What made you think os.system would use csh? It uses standard C function system, that on Unix system will call just basic /bin/sh. This will not be csh, but most probably bash, or some simpler version of it.\nBTW: note that what you do with shell environment in os.system will not affect subsequent calls to os.syst... | [
8,
0
] | [] | [] | [
"alias",
"csh",
"os.system",
"python",
"subprocess"
] | stackoverflow_0003258229_alias_csh_os.system_python_subprocess.txt |
Q:
Is there a folder layout structure for Django websites?
I am trying to get an overview of a Django website application structure. The way I have done this in the past with other frameworks (Symfony, RoR etc) is to look at the application folder structure, work out which bits go where, and then work my way on from ... | Is there a folder layout structure for Django websites? | I am trying to get an overview of a Django website application structure. The way I have done this in the past with other frameworks (Symfony, RoR etc) is to look at the application folder structure, work out which bits go where, and then work my way on from there onwards.
I have been searching online for similar info ... | [
"Take a look at the tutorial on djangoproject.com - the directory structure is pretty clearly stated.\n",
"Yes see \nFolder structure for a Django project\nalso see\nWriting your first Django app, part 1 - Creating a project\nstartproject script by default generates\nmysite/\n __init__.py\n manage.py\n s... | [
2,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003258332_django_python.txt |
Q:
pyinotify: Handling IN_MODIFY triggers
I am trying to watch a directory, and is looking for file modifications. Thinking of using pyinotify. Problem is that while using IN_MODIFY event to check for a file change, it triggers quite a number of events if I am copying even a small file of say 12 MB to the directory o... | pyinotify: Handling IN_MODIFY triggers | I am trying to watch a directory, and is looking for file modifications. Thinking of using pyinotify. Problem is that while using IN_MODIFY event to check for a file change, it triggers quite a number of events if I am copying even a small file of say 12 MB to the directory over a network.
I dont want to handle so many... | [
"Try changing IN_MODIFY to IN_CLOSE_WRITE.\nAn IN_CLOSE_WRITE event occurs when a writable file is closed. That should happen only once, unless the program that is copying the file chooses to close the file multiple times.\nThe above change is probably all you need, but if not, this basic code\ncan be a very useful... | [
3
] | [] | [] | [
"file",
"inotify",
"pyinotify",
"python"
] | stackoverflow_0003258066_file_inotify_pyinotify_python.txt |
Q:
How do I do threading in python?
using code from this site: http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/
The code is
import time
from threading import Thread
def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i
... | How do I do threading in python? | using code from this site: http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/
The code is
import time
from threading import Thread
def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i
for i in range(10):
t = Thread(ta... | [
"You've just discovered why programming with threads is hard :)\nWhat's happening is that all your threads are getting woken up at almost the same time. One thread starts printing out \"finished sleeping from thread 1\" and before it gets a chance to print that last \"\\n\", another thread comes and prints \"finis... | [
6,
5,
2,
0,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003258603_multithreading_python.txt |
Q:
Access native windows icons for custom wxDialogs
I want to subclass wx.Dialog to get a little more functionality than is provided by the wx.MessageDialog class but I would still like to be able to use the native windows icons (ie the ones used in the wx.MessageDialog that can be set by the flags such as wx.ICON_ER... | Access native windows icons for custom wxDialogs | I want to subclass wx.Dialog to get a little more functionality than is provided by the wx.MessageDialog class but I would still like to be able to use the native windows icons (ie the ones used in the wx.MessageDialog that can be set by the flags such as wx.ICON_ERROR etc.. )
Is there anyway to access these?
Update:
T... | [
"This should do the trick:\nwx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_CMN_DIALOG)\n\n",
"Not sure how you'd do in in wx, but here's a Microsoft article on how to do it with the native API:\nhttp://msdn.microsoft.com/en-us/magazine/cc188763.aspx\n"
] | [
2,
0
] | [] | [] | [
"customdialog",
"dialog",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003257464_customdialog_dialog_python_user_interface_wxpython.txt |
Q:
Writing bindings and wrappers
I keep seeing people writing wrappers for, say a module written in X language to use it in Y language. I wanted to know the basics of writing such wrappers. Where does one start from? My question here is more specific for libgnokii, how do I begin to write python bindings for it.
A:
... | Writing bindings and wrappers | I keep seeing people writing wrappers for, say a module written in X language to use it in Y language. I wanted to know the basics of writing such wrappers. Where does one start from? My question here is more specific for libgnokii, how do I begin to write python bindings for it.
| [
"You can start with reading this: extending python with c or c++ And then when you decide that it's too much hassle, you can check out swig or possibly Boost.Python.\nctypes may also be useful.\nI've done manual wrapping of c++ classes and I've used swig. swig was much easier to use, but in the end I wanted to do s... | [
7,
2
] | [] | [] | [
"binding",
"python"
] | stackoverflow_0003259033_binding_python.txt |
Q:
Perl's BEGIN{} block in Python
I have Python code that uses the "with" keyword (new in 2.6) and I want to check if the interpreter version is at least 2.6, so I use this code:
import sys
if sys.version < '2.6':
raise Exception( "python 2.6 required" )
However, the 2.4 interpreter chokes on the with keyword (l... | Perl's BEGIN{} block in Python | I have Python code that uses the "with" keyword (new in 2.6) and I want to check if the interpreter version is at least 2.6, so I use this code:
import sys
if sys.version < '2.6':
raise Exception( "python 2.6 required" )
However, the 2.4 interpreter chokes on the with keyword (later in the script) because it doesn... | [
"Take a look here:\nHow can I check for Python version in a program that uses new language features?\n",
"Perhaps someone has a better answer, but my first thought would be to have a separate script to perform the check, then import the \"real\" script once the check has passed. Python won't check the syntax unti... | [
4,
3
] | [] | [] | [
"perl",
"python",
"version"
] | stackoverflow_0003259060_perl_python_version.txt |
Q:
sorting a list of tuples
I have a list of tuples of the form (a,b,c,d) and I want to copy only those tuples with unique values of 'a' to a new list. I'm very new to python.
Current idea that isn't working:
for (x) in list:
a,b,c,d=(x)
if list.count(a)==1:
newlist.append(x)
A:
If you don't want to add... | sorting a list of tuples | I have a list of tuples of the form (a,b,c,d) and I want to copy only those tuples with unique values of 'a' to a new list. I'm very new to python.
Current idea that isn't working:
for (x) in list:
a,b,c,d=(x)
if list.count(a)==1:
newlist.append(x)
| [
"If you don't want to add any of the tuples that have duplicate a values (as opposed to adding the first occurrence of a given a, but none of the later ones):\nseen = {}\nfor x in your_list:\n a,b,c,d = x\n seen.setdefault(a, []).append(x)\n\nnewlist = []\nfor a,x_vals in seen.iteritems():\n if len(x_vals)... | [
3,
2,
2,
0
] | [] | [] | [
"list",
"python",
"sorting",
"tuples"
] | stackoverflow_0003259159_list_python_sorting_tuples.txt |
Q:
Django + mod_python + apache: admin panel and urls don't work
Whole this day I was trying to configure django on production server. I use mod_python. When I open http: //beta.example.com I see my site but http: //beta.example.com/admin and http: //beta.example.com/441/abc/ doesn't work:
Page not found (404)
Reques... | Django + mod_python + apache: admin panel and urls don't work | Whole this day I was trying to configure django on production server. I use mod_python. When I open http: //beta.example.com I see my site but http: //beta.example.com/admin and http: //beta.example.com/441/abc/ doesn't work:
Page not found (404)
Request Method: GET
Request URL: http://beta.example.com/admin
{'... | [
"Not sure if that will solve your problem but in my site.conf for django I had to comment the line:\nPythonOption django.root /\nto make it work.\n",
"You really don't want to be using mod_python for deployment. I highly suggest moving to mod_wsgi for Django depoyment. \n",
"I'm just throwing this out there, bu... | [
2,
2,
0
] | [] | [] | [
"django",
"mod_python",
"python"
] | stackoverflow_0003258511_django_mod_python_python.txt |
Q:
Get IP Adress from a connected Windows Network Share with Python
How can i manage to get the IP or path like \11.1.1.100\projects of a connected network share with a drive letter.
I only have the drive letter and want to get the IP of the Share with python.
Many Thanks...
Sashmo
A:
I don't know the python equiv... | Get IP Adress from a connected Windows Network Share with Python | How can i manage to get the IP or path like \11.1.1.100\projects of a connected network share with a drive letter.
I only have the drive letter and want to get the IP of the Share with python.
Many Thanks...
Sashmo
| [
"I don't know the python equivalent, but WNetGetConnection will give you the UNC path mapped to the drive letter:\nwchar_t szName[256];\nDWORD chName = 256;\nDWORD dwResult = WNetGetConnectionW(L\"Z:\", szName, &chName);\n\nI'm sure there is a python module that wraps this functionality. From the UNC path you can ... | [
2
] | [] | [] | [
"networking",
"python",
"windows"
] | stackoverflow_0003257975_networking_python_windows.txt |
Q:
Changing the size of a wx.ProgressDialog
The size of the ProgresDialog is too narrow to hold the text that I need to display...
I tryed to change the size of the dialog by calling the SetSize method on the dialog after it is created.
This fixed the size of the dialog but on creation of the dialog the gauge size ... | Changing the size of a wx.ProgressDialog | The size of the ProgresDialog is too narrow to hold the text that I need to display...
I tryed to change the size of the dialog by calling the SetSize method on the dialog after it is created.
This fixed the size of the dialog but on creation of the dialog the gauge size is initially smaller and then jumps in size to... | [
"As I understand it, the ProgressDialog wraps the native platform dialog, so there may not be much you can do to fix it. To get the most flexibility, you'll have to use wx.Dialog and maybe a wx.Gauge.\n\nMike Driscoll\nBlog: http://blog.pythonlibrary.org\n"
] | [
1
] | [] | [] | [
"progressdialog",
"python",
"wxpython"
] | stackoverflow_0003251927_progressdialog_python_wxpython.txt |
Q:
interactive console for my mainloop app
I have an little script which logs users that login to my Pidgin/MSN account
#!/usr/bin/env python
def log_names(buddy):
name = str(purple.PurpleBuddyGetName(buddy))
account = purple.PurpleAccountGetUsername(purple.PurpleBuddyGetAccount(buddy))
if account == u'... | interactive console for my mainloop app | I have an little script which logs users that login to my Pidgin/MSN account
#!/usr/bin/env python
def log_names(buddy):
name = str(purple.PurpleBuddyGetName(buddy))
account = purple.PurpleAccountGetUsername(purple.PurpleBuddyGetAccount(buddy))
if account == u'dummy_account@hotmail.com':
try: log... | [
"You should look in the direction of general GObject/GLib programming (this is where gobject.MainLoop() is coming from). You could use threads, you could use event callbacks, whatever. For example, this is a simple 'console' using event callbacks. Add this just before the loop.run():\nimport glib, sys, os, fcntl\n\... | [
3
] | [] | [] | [
"dbus",
"interactive",
"python"
] | stackoverflow_0003148264_dbus_interactive_python.txt |
Q:
Can a PyQt program consume a DBus interface that exposes custom C++ types (marhsalled via Qt's MetaType system)? If so, how?
I have a Qt/C++ application that exposes some custom C++ classes via DBus methods (by registering them as MetaTypes, and using annotations in the xml), and I want my PyQt program to consume ... | Can a PyQt program consume a DBus interface that exposes custom C++ types (marhsalled via Qt's MetaType system)? If so, how? | I have a Qt/C++ application that exposes some custom C++ classes via DBus methods (by registering them as MetaTypes, and using annotations in the xml), and I want my PyQt program to consume these methods.
The problem I see is that the exposed types are C++ classes, not python, so how can I make python aware of these cl... | [
"There is no such thing as 'C++ classes' in D-Bus, it is language-agnostic. All methods, functions, etc. have type signatures expressible in basic D-Bus types (see the spec). Just call those classes, and it should work.\n"
] | [
0
] | [] | [] | [
"c++",
"dbus",
"pyqt",
"python",
"qt"
] | stackoverflow_0003181156_c++_dbus_pyqt_python_qt.txt |
Q:
Numpy interconversion between multidimensional and linear indexing
I'm looking for a fast way to interconvert between linear and multidimensional indexing in Numpy.
To make my usage concrete, I have a large collection of N particles, each assigned 5 float values (dimensions) giving an Nx5 array. I then bin each ... | Numpy interconversion between multidimensional and linear indexing | I'm looking for a fast way to interconvert between linear and multidimensional indexing in Numpy.
To make my usage concrete, I have a large collection of N particles, each assigned 5 float values (dimensions) giving an Nx5 array. I then bin each dimension using numpy.digitize with an appropriate choice of bin boundar... | [
"You can simply calculate the index of each bin:\nbox_indices = numpy.dot(ndims**numpy.arange(ndims), binassign)\n\nThe scalar product simply does 1*x0 + 5*x1 + 5*5*x2 +… This is done very efficiently through NumPy's dot().\n",
"Although I very much like EOL's answer, I wanted to generalize it a bit for non-unif... | [
4,
3
] | [] | [] | [
"indexing",
"numpy",
"python"
] | stackoverflow_0003257619_indexing_numpy_python.txt |
Q:
Application is not working under raw system
I've an python GUI application, I use pyQt4.
I build binary with bbfreeze (before I was using py2exe but it didn't work with email module well).
On system where I build this app, everything works properly, but when I install it on raw windows (without all those vc_redis... | Application is not working under raw system | I've an python GUI application, I use pyQt4.
I build binary with bbfreeze (before I was using py2exe but it didn't work with email module well).
On system where I build this app, everything works properly, but when I install it on raw windows (without all those vc_redist and set of python libraries) binary does not wo... | [
"Get Dependency Walker, and run depends.exe on your executable. It will examine the full tree of DLL dependencies, and mark with a red error the ones that are missing.\nIt will likely be a MSCVRTxx.dll.\n"
] | [
1
] | [] | [] | [
"py2exe",
"pyqt",
"python",
"windows"
] | stackoverflow_0003259993_py2exe_pyqt_python_windows.txt |
Q:
Running a python script from ArcMap
running a python script from within ESRI's ArcMap and it calls another python script (or at least attempts to call it) using the subprocess module. However, the system window that it executes in (DOS window) comes up only very briefly and enough for me to see there is an error ... | Running a python script from ArcMap | running a python script from within ESRI's ArcMap and it calls another python script (or at least attempts to call it) using the subprocess module. However, the system window that it executes in (DOS window) comes up only very briefly and enough for me to see there is an error but goes away too quickly for me to actua... | [
"Try doing a raw_input() command at the end of your script (it's input() in Python 3). \nThis will pause the script and wait for keyboard input. If the script raises an exception, you will need to catch it and then issue the command.\nAlso, there are ways to read the stdout and stderr streams of your command, try l... | [
0,
0
] | [] | [] | [
"esri",
"python"
] | stackoverflow_0003259999_esri_python.txt |
Q:
Create multiple buttons with consecutive integers in name
I have the following python code and I was wondering if it's possible to create those buttons in a for loop instead? I was thinking of modifying the local namespace but I'm not sure if that's a good idea. I really want the buttons to be named so that it's n... | Create multiple buttons with consecutive integers in name | I have the following python code and I was wondering if it's possible to create those buttons in a for loop instead? I was thinking of modifying the local namespace but I'm not sure if that's a good idea. I really want the buttons to be named so that it's named consecutively.
self.todo1 = wx.TextCtrl(self, -1, "")
sel... | [
"I think the built-in setattr method is probably your best friend here. Something like this should work:\nfor i in range(1,6):\n setattr(self,'todo%d' % i,wx.TextCtrl(self, -1, \"\"))\n setattr(self,'timer_label%d' % i, wx.StaticText(self,-1,\"00:00\"))\n setattr(self,'set_timer%d' % i, wx.Button(self,-1,\"S... | [
3,
2,
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003231358_python_wxpython.txt |
Q:
Run a C# application from python script
I've just about finished coding a decently sized disease transmission model in C#. However, I'm fairly new to .NET and am unsure how to proceed. Currently I just double-click on the .exe file and the model imports config setting from text files, does its thing, and outputs... | Run a C# application from python script | I've just about finished coding a decently sized disease transmission model in C#. However, I'm fairly new to .NET and am unsure how to proceed. Currently I just double-click on the .exe file and the model imports config setting from text files, does its thing, and outputs the results into a text file.
What I would... | [
"As of Python 2.6+ you should be using the subprocess module: (Docs)\nimport subprocess\n\nfor v in range(1000):\n cmdLine = r\"c:\\path\\to\\my\\app.exe\"\n subprocess.Popen(subprocess)\n subprocess.Popen(r\"move output.txt ./acc/output-%d.txt\" % (v))\n\n",
"The answer to your problems can be found in ... | [
12,
3
] | [] | [] | [
"filesystems",
"python",
"simulation",
"subprocess"
] | stackoverflow_0003260015_filesystems_python_simulation_subprocess.txt |
Q:
How to check variable against 2 possible values?
I have a variable s which contains a one letter string
s = 'a'
Depending on the value of that variable, I want to return different things. So far I am doing something along the lines of this:
if s == 'a' or s == 'b':
return 1
elif s == 'c' or s == 'd':
return... | How to check variable against 2 possible values? | I have a variable s which contains a one letter string
s = 'a'
Depending on the value of that variable, I want to return different things. So far I am doing something along the lines of this:
if s == 'a' or s == 'b':
return 1
elif s == 'c' or s == 'd':
return 2
else:
return 3
Is there a better way to write ... | [
"if s in ('a', 'b'):\n return 1\nelif s in ('c', 'd'):\n return 2\nelse:\n return 3\n\n",
" d = {'a':1, 'b':1, 'c':2, 'd':2}\n return d.get(s, 3)\n\n",
"If you only return fixed values, a dictionary is probably the best approach.\n",
"if s in 'ab':\n return 1\nelif s in 'cd':\n return 2\nelse:\... | [
51,
15,
1,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003260057_python.txt |
Q:
socket.getaddrinfo fails on one machine; works on another apparently-identical one. Why?
I've got a laptop and a desktop, both running Ubuntu 10.04, both running the stock Python 2.6.5 that comes with Ubuntu.
On the laptop, the following program
#!/usr/bin/env python
import socket
print(socket.getaddrinfo("localho... | socket.getaddrinfo fails on one machine; works on another apparently-identical one. Why? | I've got a laptop and a desktop, both running Ubuntu 10.04, both running the stock Python 2.6.5 that comes with Ubuntu.
On the laptop, the following program
#!/usr/bin/env python
import socket
print(socket.getaddrinfo("localhost", 8025, 0, socket.SOCK_STREAM))
works -- i.e., it prints out some stuff without getting an... | [
"Check /etc/hosts on the box where it does not work. Is there an entry for localhost?\nAlso compare /etc/nsswitch.conf and see if there is anything suspicious, like missing 'hosts' line\n"
] | [
1
] | [] | [] | [
"networking",
"python",
"sockets"
] | stackoverflow_0003260469_networking_python_sockets.txt |
Q:
I'd like to know what's going on this Python program. I've included the code
Here's the code: http://paste.pocoo.org/show/238093/
My main questions right now are:
Is Line 37 mainly the gist of this program? And does it simply calculate this once and then print the result? Ex: self.start + key*self.step with start... | I'd like to know what's going on this Python program. I've included the code | Here's the code: http://paste.pocoo.org/show/238093/
My main questions right now are:
Is Line 37 mainly the gist of this program? And does it simply calculate this once and then print the result? Ex: self.start + key*self.step with start=1, key=4, step=2 [prints 9]
where does the variable 'value' actually come into pl... | [
"\nYes, more or less.\nThis is the exception. If someone assigns a value to a particular index, the sequence remembers that and will return that value instead of calculating it. Note that the code here does not actually use this function.\nRandom comment instead: the last 3 lines of the getitem function could be ... | [
3
] | [] | [] | [
"containers",
"python",
"types"
] | stackoverflow_0003260488_containers_python_types.txt |
Q:
Possible Google Riddle?
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.
t-shirt
So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.
My first guess is that each block represents a page ... | Possible Google Riddle? | My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.
t-shirt
So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.
My first guess is that each block represents a page layout, and the logo "You sho... | [
"I emailed the Website Optimizer Team, and they said \"There's no secret code, unless you find one. :)\"\n",
"I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best.\nWhich block do you like best?\n",
"I think it's ... | [
15,
5,
5,
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000252221_python.txt |
Q:
blocking socket client example
i need to connect to a blocking service using tcp ports (if someone here knows about it, it is a motorola digital wirelink protocol service) , i need a good starting point example, ideally in perl, python or php which are the languages i know better.
So far i have tried this basic ex... | blocking socket client example | i need to connect to a blocking service using tcp ports (if someone here knows about it, it is a motorola digital wirelink protocol service) , i need a good starting point example, ideally in perl, python or php which are the languages i know better.
So far i have tried this basic example with no luck.
import socket
im... | [
"You probably need \\r\\n instead of \\n. If you don't terminate properly, a response won't be sent.\n",
"I don't know about this specific protocol, but instead of managing sockets yourself, I would have to recommend the Twisted framework for networking in Python.\n\nTwisted is an event-driven networking engine ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003260995_python.txt |
Q:
How can I download files form web pages?
Some web pages, having their urls, have "Download" Text, which are hyperlinks.
How can I get the hyperlinks form the urls/pages by python or ironpython.
And can I download the files with these hyperlinks by python or ironpython?
How can I do that?
Are there any C# tools?
I ... | How can I download files form web pages? | Some web pages, having their urls, have "Download" Text, which are hyperlinks.
How can I get the hyperlinks form the urls/pages by python or ironpython.
And can I download the files with these hyperlinks by python or ironpython?
How can I do that?
Are there any C# tools?
I am not native english speaker, so sorry for my... | [
"You should be able to use the BeautifulSoup library with CPython (normal Python) and IronPython. Check out the findAll() method. This should pull out a list of all the links.\nsoup.findAll('a')\n\n",
"The easiest way would be to pass the HTML page into an XML/HTML parser, and then call getElementsByTagName(\"A\"... | [
2,
1
] | [] | [] | [
"c#",
"ironpython",
"python"
] | stackoverflow_0003261198_c#_ironpython_python.txt |
Q:
wxPython: Right-align the numbers in a wx.SpinCtrl
A primary reason to use wx.SpinCtrl is to restrict the user to input integers, therefore I think that the text inside it would look better if right-aligned.
Is there a way to do this in wxPython?
A:
Actually, there is a control you can use. It's called FloatSpin... | wxPython: Right-align the numbers in a wx.SpinCtrl | A primary reason to use wx.SpinCtrl is to restrict the user to input integers, therefore I think that the text inside it would look better if right-aligned.
Is there a way to do this in wxPython?
| [
"Actually, there is a control you can use. It's called FloatSpin, which is in the agw sub-library. If you don't already have it, download the wxPython demo and check it out!\n\nMike\n\n"
] | [
1
] | [] | [] | [
"alignment",
"python",
"spinner",
"wxpython"
] | stackoverflow_0003252671_alignment_python_spinner_wxpython.txt |
Q:
Django Error: No module named engine
I'm trying to implement this code but getting Error: No module named engine
http://github.com/robstyles/Massive-Coupon---Open-source-groupon-clone
Any thoughts?
A:
You probably don't have any module named "engine" on your PYTHONPATH anyplace. Either the installation went in t... | Django Error: No module named engine | I'm trying to implement this code but getting Error: No module named engine
http://github.com/robstyles/Massive-Coupon---Open-source-groupon-clone
Any thoughts?
| [
"You probably don't have any module named \"engine\" on your PYTHONPATH anyplace. Either the installation went in the wrong location, or your Django setup was not set to include that path.\n",
"In the github directory you point to, there's a module named \"engine\". The folder containing this module needs to be ... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003261075_django_python.txt |
Q:
Parsing XML response of bit.ly
I was trying out the bit.ly api for shorterning and got it to work. It returns to my script an xml document. I wanted to extract out the tag but cant seem to parse it properly.
askfor = urllib2.Request(full_url)
response = urllib2.urlopen(askfor)
the_page = response.read()
So the_p... | Parsing XML response of bit.ly | I was trying out the bit.ly api for shorterning and got it to work. It returns to my script an xml document. I wanted to extract out the tag but cant seem to parse it properly.
askfor = urllib2.Request(full_url)
response = urllib2.urlopen(askfor)
the_page = response.read()
So the_page contains the xml document. I tri... | [
"You don't provide an error message so I can't be sure this is the only error. But, xml.minidom.parse does not take a string. From the docstring for parse:\n\nParse a file into a DOM by filename or file object.\n\nYou should try:\nresponse = urllib2.urlopen(askfor)\ndoc = parse(response)\n\nsince response will be... | [
2,
1
] | [] | [] | [
"bit.ly",
"parsing",
"python",
"xml"
] | stackoverflow_0003261372_bit.ly_parsing_python_xml.txt |
Q:
Run a function each tick in Twisted
I'm using the twisted framework, and I need to keep track of how much time has passed since an event has started, and perform an action when a certain amount has passed.
The best way to do that seems to me to be to check against a time-stamp each tick of the reactor. If it is t... | Run a function each tick in Twisted | I'm using the twisted framework, and I need to keep track of how much time has passed since an event has started, and perform an action when a certain amount has passed.
The best way to do that seems to me to be to check against a time-stamp each tick of the reactor. If it is the best way, how do I do it? If it isn't,... | [
"You want to use callLater.\nHere's a complete, runnable example which does what you are asking, \"perform an action when a certain amount (of time) has passed since an event has started\".\nfrom twisted.internet import reactor\ncertainAmount = 0.73 # this is in seconds\ndef startedEvent():\n print 'started even... | [
2,
1
] | [] | [] | [
"python",
"timing",
"twisted"
] | stackoverflow_0003260949_python_timing_twisted.txt |
Q:
Python twisted asynchronous write using deferred
With regard to the Python Twisted framework, can someone explain to me how to write asynchronously a very large data string to a consumer, say the protocol.transport object?
I think what I am missing is a write(data_chunk) function that returns a Deferred. This is ... | Python twisted asynchronous write using deferred | With regard to the Python Twisted framework, can someone explain to me how to write asynchronously a very large data string to a consumer, say the protocol.transport object?
I think what I am missing is a write(data_chunk) function that returns a Deferred. This is what I would like to do:
data_block = get_lots_and_lot... | [
"As Jean-Paul says, you should use IProducer and IConsumer, but you should also note that the lack of deferredWrite is a somewhat intentional omission.\nFor one thing, creating a Deferred for potentially every byte of data that gets written is a performance problem: we tried it in the web2 project and found that it... | [
8,
1
] | [] | [] | [
"asynchronous",
"python",
"twisted"
] | stackoverflow_0003250327_asynchronous_python_twisted.txt |
Q:
Are there reasons to use get/put methods instead of item access?
I find that I have recently been implementing Mapping interfaces on classes which on the surface fit the model (they are essentially just key-value stores with no more meta-data), but underneath they are sometimes quite complex.
Here are a couple exa... | Are there reasons to use get/put methods instead of item access? | I find that I have recently been implementing Mapping interfaces on classes which on the surface fit the model (they are essentially just key-value stores with no more meta-data), but underneath they are sometimes quite complex.
Here are a couple examples of increasing severity:
An object which wraps another mapping c... | [
"It sounds like you are describing the standard anydbm module semantics. And just as anydbm can raise exception anydbm.error, so too could your subclass raise derivatives like MyDbmTimeoutError as needed. Whether you implement it as dictionary operations or function calls, the caller will still have to contend with... | [
2,
0
] | [] | [] | [
"interface",
"mapping",
"python"
] | stackoverflow_0003261030_interface_mapping_python.txt |
Q:
Translating Python into JavaScript — Lists?
octopusList = {"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]}
squidList = ["first", "second", "third"]
for i in range(1):
squid = random.choice(squidList)
octopus = random.choice(octopusL... | Translating Python into JavaScript — Lists? | octopusList = {"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]}
squidList = ["first", "second", "third"]
for i in range(1):
squid = random.choice(squidList)
octopus = random.choice(octopusList[squid])
print squid + " " + octopus
Can any... | [
"First of all, I'd like to say that that for i in range(1): line is useless. It'll only execute the contents once, and you're not using i.\nAnyway, the code you posted should work fine with a few tweaks in JavaScript. First you'll need to reimplement random.choice. You could use this:\nfunction randomChoice(list) {... | [
4,
1,
1,
1
] | [] | [] | [
"javascript",
"python",
"translation"
] | stackoverflow_0003261466_javascript_python_translation.txt |
Q:
Difference between binary and text I/O in python on Windows
I know that I should open a binary file using "rb" instead of "r" because Windows behaves differently for binary and non-binary files.
But I don't understand what exactly happens if I open a file the wrong way and why this distinction is even necessary. ... | Difference between binary and text I/O in python on Windows | I know that I should open a binary file using "rb" instead of "r" because Windows behaves differently for binary and non-binary files.
But I don't understand what exactly happens if I open a file the wrong way and why this distinction is even necessary. Other operating systems seem to do fine by treating both kinds of... | [
"Well this is for historical (or as i like to say it, hysterical) reasons. The file open modes are inherited from C stdio library and hence we follow it. \nFor Windows, there is no difference between text and binary files, just like in any of the Unix clones. No, i mean it! - there are (were) file systems/OSes in w... | [
28,
25,
1
] | [
"For reading files there should be no difference. When writing to text-files Windows will automatically mess up your line-breaks (it will add \\r's before the \\n's). That's why you should use \"wb\".\n"
] | [
-2
] | [
"file",
"file_io",
"python",
"windows"
] | stackoverflow_0003257869_file_file_io_python_windows.txt |
Q:
Getting the position of the gtk.StatusIcon on Windows
I am assisting with Windows support for a PyGTK app that appears as a system tray applet, but am not so strong on the GTK+ gooey stuff...
We have it so when you left-click the systray icon, the window appears right by your tray icon no matter where your system ... | Getting the position of the gtk.StatusIcon on Windows | I am assisting with Windows support for a PyGTK app that appears as a system tray applet, but am not so strong on the GTK+ gooey stuff...
We have it so when you left-click the systray icon, the window appears right by your tray icon no matter where your system tray is--and on Linux this works great, using the results o... | [
"Gtk provides function gtk_status_icon_position_menu that can be passed into gtk_menu_popup as a GtkPositionFunc.\nThis seems to provide the requested functionality.\n",
"The behavior i experienced in windows with gtk_status_icon_position_menu was that it spawns the window at the location the user clicked in the ... | [
1,
0,
0
] | [] | [] | [
"gtk",
"pygtk",
"python",
"windows"
] | stackoverflow_0001246552_gtk_pygtk_python_windows.txt |
Q:
dictionary in python problem
problem.getSuccessors(getStartState()) - it returns something like ( (4,5) , north, 1) - that means 3 things - tuple, direction,cost.
I'm using a dictionary ,closed = {}
Now I need to put the output of above function in the dictionary "closed" - how can I do that??
I need to use only... | dictionary in python problem | problem.getSuccessors(getStartState()) - it returns something like ( (4,5) , north, 1) - that means 3 things - tuple, direction,cost.
I'm using a dictionary ,closed = {}
Now I need to put the output of above function in the dictionary "closed" - how can I do that??
I need to use only dictionary because I need to retu... | [
"\nI need to put the output of above\n function in the dictionary \"closed\" -\n how can I do that??\n\nIt entirely depends on what you want to use as the key, and what as the value! If the key is something completely unrelated to the tuple ( (4,5) , north, 1) (I'm not sure what the north identifier is supposed ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003262226_python.txt |
Q:
How to decode JSON string to string, not unicode
I'm trying to decode a json of a dictionary with strings as keys. The result is a dictionary with unicode keys. What is the best way to decode to a dictionary with string keys? Better: how do I prevent that strings are decoded into unicode strings? Off course I can ... | How to decode JSON string to string, not unicode | I'm trying to decode a json of a dictionary with strings as keys. The result is a dictionary with unicode keys. What is the best way to decode to a dictionary with string keys? Better: how do I prevent that strings are decoded into unicode strings? Off course I can loop afterwards...
What happens:
>>> import simplejson... | [
"You can't. Encode the strings after loading. Or even better, fix the rest of the code so that it doesn't fall over when using unicode.\n"
] | [
2
] | [] | [] | [
"json",
"python"
] | stackoverflow_0003262850_json_python.txt |
Q:
High Dimension Nearest Neighbor Search and Locality Sensitivity Hashing
Here is the main problem. I have very large database (25,000 or so) of 48 dimensional vectors, each populated with values ranging from 0-255. The specifics are not so important but I figure it might help give context.
I don't need a nearest ... | High Dimension Nearest Neighbor Search and Locality Sensitivity Hashing | Here is the main problem. I have very large database (25,000 or so) of 48 dimensional vectors, each populated with values ranging from 0-255. The specifics are not so important but I figure it might help give context.
I don't need a nearest neighbor, so approximate neighbor searches that are within a degree of accura... | [
"Maby this is a little off topic but you can try using PCA http://en.wikipedia.org/wiki/Principal_component_analysis for reducing the dimensionality of the dataset. There should be plenty of PCA modules designed for numPy ( for example: http://folk.uio.no/henninri/pca_module/).\nThe method is rather simple and with... | [
2,
2
] | [] | [] | [
"math",
"python"
] | stackoverflow_0003262633_math_python.txt |
Q:
Python: Why does the tab character show up weird in Tkinter?
This a screenshot from a Tkinter Listbox in a program I'm writing:
Why does the \t character show up as a black bar?
On a Mac it shows up normally (as a tab), but on Windows I get this. I think it might have something to do with character encoding becau... | Python: Why does the tab character show up weird in Tkinter? | This a screenshot from a Tkinter Listbox in a program I'm writing:
Why does the \t character show up as a black bar?
On a Mac it shows up normally (as a tab), but on Windows I get this. I think it might have something to do with character encoding because strings are unicode by default in OS X but not Windows?
I tried... | [
"On Windows, the tab character is probably not interpreted by the Listbox rendering code but on Mac, it is. Hence, the difference. But I'm unsure about this since, IIRC, Tkinter uses its own rendering code so it should render the same on all platforms. Maybe this is part of the OS's font rendering code (which is mo... | [
0
] | [] | [] | [
"character_encoding",
"python",
"special_characters",
"tkinter"
] | stackoverflow_0003263227_character_encoding_python_special_characters_tkinter.txt |
Q:
sets in python problem
I want to use sets as data structure. how should i make it possible?
what are the commands I need?
Like closedset = set()
is this ok?
And in a set, if i want to get some value out, what is the command for that one?
A:
Correct. To create an empty set, write foo = set(). To retrieve values, ... | sets in python problem | I want to use sets as data structure. how should i make it possible?
what are the commands I need?
Like closedset = set()
is this ok?
And in a set, if i want to get some value out, what is the command for that one?
| [
"Correct. To create an empty set, write foo = set(). To retrieve values, you can iterate over the set: \nfor val in someset:\n print val\n\nYou can also write val in someset to check if an item is in a set.\nBe sure to read the documentation for how to do set operations.\n",
"You can saymySet = set(), which wi... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003263272_python.txt |
Q:
Creating a matrix from simple three column text fie
I'm trying to create a matrix or a contingency table from a file that has this format:
Species Date Data
1 Dec 3
2 Jan 4
2 Dec 6
2 Dec 3
Result
1 2
Dec 3 9
Jan 4
More that I'd like to know how to turn myfile into an arr... | Creating a matrix from simple three column text fie | I'm trying to create a matrix or a contingency table from a file that has this format:
Species Date Data
1 Dec 3
2 Jan 4
2 Dec 6
2 Dec 3
Result
1 2
Dec 3 9
Jan 4
More that I'd like to know how to turn myfile into an array that numpy will like. Basically I'm trying to recreate... | [
"When other people say \"Matrix\" you have a dictionary with a two-part key.\nThe problem is murky, but you have something like this.\nmatrix = {}\n# read input\n matrix[ (row,column) ] = data\n\nrow_keys = set( r for r,c in matrix.keys() )\ncol_keys = set( c for r,c in matrix.keys() )\n\nfor r in row_keys:\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003263759_python.txt |
Q:
How to make a python regex?
I am working on a loginMiddleware class for Django. This middleware class must send a user to the login page when it's not logedin. But there are a few exceptions.
Because i run the build-in django server i had to make a media url. But know is de problem that when the login page loads ... | How to make a python regex? | I am working on a loginMiddleware class for Django. This middleware class must send a user to the login page when it's not logedin. But there are a few exceptions.
Because i run the build-in django server i had to make a media url. But know is de problem that when the login page loads a javascript file, the javascript... | [
"Sure:\nDIRECT_ACCESS = re.compile(r'^/media/.*\\.(js|css|png|gif|jpg)$')\n\n...\n\nif DIRECT_ACCESS.match(url):\n ...\n\nHint: If you want to make sure your regexp works, write a couple of unit tests that execute it. That way, you won't get any nasty surprises.\n",
"You don't need a regex:\nif request.path.st... | [
3,
2,
1
] | [] | [] | [
"django",
"python",
"regex"
] | stackoverflow_0003263819_django_python_regex.txt |
Q:
reading from stdin, while consuming no more memory than needed
I am trying to create a line-by-line filter in python. However, stdin.readlines() reads all lines in before starting to process, and python runs out of memory (MemoryError).
How can I have just one line in memory at a time?
The kind of code I have:
fo... | reading from stdin, while consuming no more memory than needed | I am trying to create a line-by-line filter in python. However, stdin.readlines() reads all lines in before starting to process, and python runs out of memory (MemoryError).
How can I have just one line in memory at a time?
The kind of code I have:
for line in sys.stdin.readlines():
if( filter.apply( line ) ):
... | [
"for line in sys.stdin:\n ...\n\nOr call .readline() in a loop.\n",
"import sys\nwhile 1:\n line = sys.stdin.readline()\n if not line:\n break\n if (filter.apply(line)):\n print(line)\n\n"
] | [
13,
2
] | [] | [] | [
"line_by_line",
"pipe",
"python",
"stdin"
] | stackoverflow_0003263665_line_by_line_pipe_python_stdin.txt |
Q:
Multiple Python Installations of the same python version on a single computer
I want to install the new Python 2.7 on my Windows XP 32bit PC.
having CDO (thats OCD with initials sorted in alphabetical order) I want to install it multiple times on the same computer (to different TARGETDIRs).
how do i do that ? doub... | Multiple Python Installations of the same python version on a single computer | I want to install the new Python 2.7 on my Windows XP 32bit PC.
having CDO (thats OCD with initials sorted in alphabetical order) I want to install it multiple times on the same computer (to different TARGETDIRs).
how do i do that ? double clicking on the installer, or running msiexec multiple times did not work for me... | [
"If I understand correctly you want multiple independent copies of Python 2.7 running on Windows. I assume that is so you can install just the packages you need for each project and not have different projects fighting over conflicting versions.\nTry using virtualenv (http://pypi.python.org/pypi/virtualenv). You in... | [
1,
0
] | [] | [] | [
"installation",
"python",
"windows_installer"
] | stackoverflow_0003263769_installation_python_windows_installer.txt |
Q:
access memory mapped file created on .net via python
I made a memory mapped file using MemoryMappedFile.CreateNew(mapName, capacity) of .net 4
Can i access this mmf by the mapName from cpython ?
I tried like below.
import mmap
map = mmap.mmap(-1, 0, mapName, 1)
but it returns WindowsError [error 87] saying the p... | access memory mapped file created on .net via python | I made a memory mapped file using MemoryMappedFile.CreateNew(mapName, capacity) of .net 4
Can i access this mmf by the mapName from cpython ?
I tried like below.
import mmap
map = mmap.mmap(-1, 0, mapName, 1)
but it returns WindowsError [error 87] saying the parameter is incorrect.
I'm using windows vista.
| [
"I have absolutely no experience with C#, but I'll attempt to answer your question.\nCreateNew should create a mapping to a file that doesn't reside in the filesystem. Note that this isn't cross platform in any way. On Windows, the tagname parameter of mmap.mmap should allow you to map these tagged mappings. Since ... | [
1
] | [] | [] | [
".net",
"memory_mapped_files",
"python"
] | stackoverflow_0003257109_.net_memory_mapped_files_python.txt |
Q:
Any way to keep track of the last 5 data points in python
So I have an array that holds several numbers. As my script runs, more and more numbers are appended to this array. However, I am not interested in all the numbers but just want to keep track of the last 5 numbers.
Currently, I just store all the numbers in... | Any way to keep track of the last 5 data points in python | So I have an array that holds several numbers. As my script runs, more and more numbers are appended to this array. However, I am not interested in all the numbers but just want to keep track of the last 5 numbers.
Currently, I just store all the numbers in the array. However, this array gets really big and it's full o... | [
"Try using a deque:\nhttp://docs.python.org/library/collections.html#deque-objects\n\"If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number ... | [
14,
7,
4,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003261090_python.txt |
Q:
how to interact with an external script(program)
there is a script that expects keyboard input,
i can call that script with os.system('./script') in python,
how is it possible to send back an input to the script from another calling script?
update:
the script is:
$ cat script
#!/usr/bin/python
for i in range(4):
... | how to interact with an external script(program) | there is a script that expects keyboard input,
i can call that script with os.system('./script') in python,
how is it possible to send back an input to the script from another calling script?
update:
the script is:
$ cat script
#!/usr/bin/python
for i in range(4):
name=raw_input('enter your name')
prin... | [
"You can use subprocess instead of os.system:\np = subprocess.Popen('./script',stdin=subprocess.PIPE)\np.communicate('command')\n\nits not testet\n"
] | [
1
] | [
"In fact, os.system and os.popen are now deprecated and subprocess is the recommended way to handle all sub process interaction.\n"
] | [
-2
] | [
"bash",
"externalinterface",
"interaction",
"python"
] | stackoverflow_0003264257_bash_externalinterface_interaction_python.txt |
Q:
How to pass variable in exec statment in python
I am having two python files as 1.py and 2.py.
**1.py is as**
class A:
def __init__(self):
x = 5
y = 7
NUMBERS = self
fp = open(filePath)
temp = fp.read()
exec(temp)
... | How to pass variable in exec statment in python | I am having two python files as 1.py and 2.py.
**1.py is as**
class A:
def __init__(self):
x = 5
y = 7
NUMBERS = self
fp = open(filePath)
temp = fp.read()
exec(temp)
fp.close()
ADD_METHOD()
**2.py is... | [
"If these are both Python files that you wrote yourself, why not just create a function in 2.py that you can import and call in 1.py? This is a much easier and cleaner abstraction. It also avoids the creation of a new process. You could write something like this:\n# **1.py is as**\nfrom 2 import ADD_METHOD\nclass A... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003263656_python.txt |
Q:
Which python installation should I use?
I'm about to refresh myself in programming and I have decided on Python 2.6 for that. I have searched the net and it gave me two possible installers for download. One is from the Python site and another is from Activestate. Which one should I install on my Windows computer?
... | Which python installation should I use? | I'm about to refresh myself in programming and I have decided on Python 2.6 for that. I have searched the net and it gave me two possible installers for download. One is from the Python site and another is from Activestate. Which one should I install on my Windows computer?
| [
"ActiveState gives you paid support. While this may be very important / critical to some companies, most do just fine with python.org version, particularly those who experiment. \nThere are other crazy ones like Stackless Python, Google's implementation in C++, Cython, etc. I would say that those are not that impor... | [
6,
5,
5,
1,
1,
1,
0
] | [] | [] | [
"activepython",
"installation",
"python",
"windows"
] | stackoverflow_0002126001_activepython_installation_python_windows.txt |
Q:
does python multiplicative expression evaluates faster if finds a zero?
suppose i a have a multiplicative expression with lots of multiplicands (small expressions)
expression = a*b*c*d*....*w
where for example c is (x-1), d is (y**2-16), k is (xy-60)..... x,y are numbers
and i know that c,d,k,j maybe zero
Do... | does python multiplicative expression evaluates faster if finds a zero? | suppose i a have a multiplicative expression with lots of multiplicands (small expressions)
expression = a*b*c*d*....*w
where for example c is (x-1), d is (y**2-16), k is (xy-60)..... x,y are numbers
and i know that c,d,k,j maybe zero
Does the order i write the expression matters for faster evaluation?
Is it bett... | [
"Python v2.6.5 does not check for zero values.\ndef foo():\n a = 1\n b = 2\n c = 0\n return a * b * c\n\n>>> import dis\n>>> dis.dis(foo)\n 2 0 LOAD_CONST 1 (1)\n 3 STORE_FAST 0 (a)\n\n 3 6 LOAD_CONST 2 (2)\n 9 STO... | [
7,
5,
5,
2
] | [
"Probably not. Multiplication is one of the cheapest operations of all. If a 0 should be faster then it would be necessary to check for zeros before and that's probably slower than just doing the multiplication.\nThe fastest solution should be multiply.reduce()\n"
] | [
-1
] | [
"evaluation",
"math",
"optimization",
"python"
] | stackoverflow_0003264345_evaluation_math_optimization_python.txt |
Q:
Blocks within blocks
I'm having problems displaying nested blocks in a template.
eg.
{% for category in categories %}
//code to display category info
{% products = products.object.filter(category = category) %}
{% for product in products%}
//code to display product i... | Blocks within blocks | I'm having problems displaying nested blocks in a template.
eg.
{% for category in categories %}
//code to display category info
{% products = products.object.filter(category = category) %}
{% for product in products%}
//code to display product info
{% endfor %}
... | [
"You cannot assign to variables in the Django template system. Your two attempts:\n{% products = products.object.filter(category = category) %}\n\nand\n{% products = category.get_products %}\n\nare both invalid Django syntax.\nSome Python templating systems are PHP-like: they let you embed Python code into HTML fi... | [
1,
0,
0
] | [] | [] | [
"block",
"django",
"django_templates",
"python"
] | stackoverflow_0003264101_block_django_django_templates_python.txt |
Q:
Can modules be added to the Python search path (e.g site-packages dir) using symbolic links on Windows?
I tried to create a symbolic link in the Python site-packages directory using the mklink /D syntax (on a Windows 7 machine). Unfortunately the module is not found when using import clause. When I copy the module... | Can modules be added to the Python search path (e.g site-packages dir) using symbolic links on Windows? | I tried to create a symbolic link in the Python site-packages directory using the mklink /D syntax (on a Windows 7 machine). Unfortunately the module is not found when using import clause. When I copy the module physicaly to site-package directory, it works OK. Am I doing something wrong or is this just not possible on... | [
"I just did it on Windows 7 using Python 2.7, and it works. Here are the steps I followed.\n\nopen a windows command prompt with necessary privileges\ncd to the site-packages directory\ncd c:\\Python27\\Lib\\site-packages\ncreate the link\nmklink /D modulename c:\\path\\to\\module\\real\\location\\modulename\n\n"
] | [
1
] | [] | [] | [
"python",
"symlink",
"windows"
] | stackoverflow_0003155462_python_symlink_windows.txt |
Q:
Python Lists Beginner
I created a list in Python:
mylist=os.listdir("/User/Me/Folder")
now I have a list of files in a List.
What I would like to do is:
Take one file name after the other and add a URL to it:
/myurl/ + each item in mylist
And then I would like to write the result in a html template from Django.
S... | Python Lists Beginner | I created a list in Python:
mylist=os.listdir("/User/Me/Folder")
now I have a list of files in a List.
What I would like to do is:
Take one file name after the other and add a URL to it:
/myurl/ + each item in mylist
And then I would like to write the result in a html template from Django.
So that it display all the i... | [
"Using list comprehensions, you can transform your original list, \"mylist\", into a list with the URL prefix like so:\nurllist = ['/myurl/%s' % the_file for the_file in mylist]\n\nAnalysis:\na) the expression in the square brackets is the list comprehension. it says: iterate over each item in \"mylist\", temporari... | [
5,
3,
1
] | [] | [] | [
"django",
"list",
"python"
] | stackoverflow_0003264804_django_list_python.txt |
Q:
Type error in python!
closedset = set()
root = (5,6)
for u,v in root:
if v is not closedset:
closedset.add(root)
print closedset
Error:
for u,v in root:
TypeError: unpack non-sequence
What should i do with type of error?
A:
root = [(5,6)]
...should work.
for iterates through a list o... | Type error in python! | closedset = set()
root = (5,6)
for u,v in root:
if v is not closedset:
closedset.add(root)
print closedset
Error:
for u,v in root:
TypeError: unpack non-sequence
What should i do with type of error?
| [
"root = [(5,6)]\n\n...should work.\nfor iterates through a list or set, returning first u, then v. If you want to return both parts of the set, you'll have to add itself to a list.\n",
"I'm not sure I understand what you're trying to do. Maybe:\nroots = [(5, 6), (2, 3)]\n\nfor u, v in roots:\n if f not in closed... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003263057_python.txt |
Q:
Changing C variables from python?
I have an embedded python interpreter in my program. I'd like to export a module with values defined in my program and be able to change them from a python script. e.g.
in c:
int x = 1;
in python:
import embedded
embedded.x = 2
in c:
printf("%d",x);
output:
2
Is this possib... | Changing C variables from python? | I have an embedded python interpreter in my program. I'd like to export a module with values defined in my program and be able to change them from a python script. e.g.
in c:
int x = 1;
in python:
import embedded
embedded.x = 2
in c:
printf("%d",x);
output:
2
Is this possible or do I have to export functions to ... | [
"There's no need to export functions, but the easiest way to do this would be to use PyModule_GetDict() with PyDict_GetItemString() to get the value assigned to the x attribute.\n",
"If you don't want to actively check the value of a PyObject in your C code, I think you need to export functions to modify the repr... | [
0,
0
] | [] | [] | [
"api",
"c",
"python"
] | stackoverflow_0003265232_api_c_python.txt |
Q:
Django Abstract Models vs simple Python mixins vs Python ABCs
This is a question prompted by another question from me.
Django provides Abstract base classes functionality (which are not to same as ABC classes in Python?) so that one can make a Model (Django's models.Model) from which one can inherit, but without t... | Django Abstract Models vs simple Python mixins vs Python ABCs | This is a question prompted by another question from me.
Django provides Abstract base classes functionality (which are not to same as ABC classes in Python?) so that one can make a Model (Django's models.Model) from which one can inherit, but without that Model having an actual table in the database. One triggers this... | [
"I'll try to be reasonably brief, since this can easily turn into a lengthy diatribe:\nABCs are out because they were only introduced in Python 2.6, and the Django developers have a set roadmap for Python version support (2.3 support was only dropped in 1.2).\nAs for object-inheriting mixins, they would be less Pyt... | [
14,
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003263417_django_python.txt |
Q:
Unpickling a Python class
I have a problem trying to unpickle subclasses of this class. When I unpickle it, the stuff isn't there. What gives?
class Account:
def __init__(self, server, port, smtp_server, smtp_port):
self.server = server
self.port = port
self.smtp_server = smtp_serve... | Unpickling a Python class | I have a problem trying to unpickle subclasses of this class. When I unpickle it, the stuff isn't there. What gives?
class Account:
def __init__(self, server, port, smtp_server, smtp_port):
self.server = server
self.port = port
self.smtp_server = smtp_server
self.smtp_port = smtp... | [
"Does your class inherit object?\nEither way, you can specify what you want to pickle by overwriting __getstate__. Otherwise it should normally copy __dict__ if you're inheriting object.\n",
"So, Here's how I just figured it out- i moved the ugly pickle stuff (see comment) to the unpickling class, imported the cl... | [
1,
0
] | [] | [] | [
"class",
"pickle",
"python"
] | stackoverflow_0003265454_class_pickle_python.txt |
Q:
how to write a program to validate another program/script?
How to write a program to test another program/script?
I need to test a ruby script that is an echo server; how should I write a program to validate the correct working of the echo server script ?
A:
You might be interested in Expect and dejaGnu.
A:
Yo... | how to write a program to validate another program/script? | How to write a program to test another program/script?
I need to test a ruby script that is an echo server; how should I write a program to validate the correct working of the echo server script ?
| [
"You might be interested in Expect and dejaGnu.\n",
"You could start with something like this for a TCP echo server:\nrequire \"socket\"\n\nhostname = \"localhost\"\nport = 2000\n\ns = TCPSocket.open(hostname, port)\n\ns.print \"something\\n\" # was \"something\"\n\nline = s.gets\nline.chop!\n\nif line == \"s... | [
1,
1,
0
] | [] | [] | [
"python",
"ruby",
"testing",
"validation"
] | stackoverflow_0003263663_python_ruby_testing_validation.txt |
Q:
importing from parent directory
I have this kind of path architecture :
>main_path/
__init__.py
config/
__init__.py
common.py
app_1/
__init__.py
config.py
index.py
>
I'd like to be able to do so in config.py :
>from main_path.config import co... | importing from parent directory | I have this kind of path architecture :
>main_path/
__init__.py
config/
__init__.py
common.py
app_1/
__init__.py
config.py
index.py
>
I'd like to be able to do so in config.py :
>from main_path.config import common
>
Though it does not work. Pyt... | [
"According to the Modules documentation a module has to be in your PYTHONPATH environment variable to be imported. You can modify this within your program with something like:\nimport sys\nsys.path.append('PATH_TO/config')\nimport common\n\nFor more information, you may want to see Modifying Python's Search Path i... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003265631_python.txt |
Q:
Dynamically add instance variables via decorator to a class in Python
I want to instrument a class via a decorator, to add some instance variables that are specified by the author of the class.
I started with the following code, but this just adds class variables and I want instance variables (those that are norma... | Dynamically add instance variables via decorator to a class in Python | I want to instrument a class via a decorator, to add some instance variables that are specified by the author of the class.
I started with the following code, but this just adds class variables and I want instance variables (those that are normally 'declared' in __ init __)
What is a pythonic way to do this, while allo... | [
"You would have to wrap __init__() in a separate function that would call the original method, then add its own attributes to the first argument.\n",
"You can do this by wrapping the __init__ method to do your bidding, and then call the original __init__:\ndef add_list_attributes(klass):\n old_init = klass.__i... | [
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003265770_python.txt |
Q:
Making a LazilyEvaluatedConstantProperty class in Python
There's a little thing I want to do in Python, similar to the built-in property, that I'm not sure how to do.
I call this class LazilyEvaluatedConstantProperty. It is intended for properties that should be calculated only once and do not change, but they sho... | Making a LazilyEvaluatedConstantProperty class in Python | There's a little thing I want to do in Python, similar to the built-in property, that I'm not sure how to do.
I call this class LazilyEvaluatedConstantProperty. It is intended for properties that should be calculated only once and do not change, but they should be created lazily rather than on object creation, for perf... | [
"I implemented it:\nclass CachedProperty(object):\n '''\n A property that is calculated (a) lazily and (b) only once for an object.\n\n Usage:\n\n class MyObject(object):\n\n # ... Regular definitions here\n\n def _get_personality(self):\n print('Calculating pers... | [
1
] | [] | [] | [
"attributes",
"properties",
"python"
] | stackoverflow_0003265221_attributes_properties_python.txt |
Q:
Validation on ManyToManyField before Save in Models.py
I have the following models:
class Application(models.Model):
users = models.ManyToManyField(User, through='Permission')
folder = models.ForeignKey(Folder)
class Folder(models.Model):
company = models.ManyToManyField(Compnay)
class UserProfile(models.Mode... | Validation on ManyToManyField before Save in Models.py | I have the following models:
class Application(models.Model):
users = models.ManyToManyField(User, through='Permission')
folder = models.ForeignKey(Folder)
class Folder(models.Model):
company = models.ManyToManyField(Compnay)
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile... | [
"Because I didn't get a reply from Botondus I decided to ask a new question in the Django Users Google Group and finally got the answer from jaymz.\nI figured that Botondus method was the right way of doing it, it just wasn't quite working. The reason that it doesn't work in this case is because I'm using a Through... | [
1,
0
] | [] | [] | [
"admin",
"django",
"python",
"validation"
] | stackoverflow_0003052427_admin_django_python_validation.txt |
Q:
GAE is any good ? if yes then JAVA or Python?
Basically I am coding websites in PHP from last year.
But now I want to use something else and GAE looks a good option.
So I want to know if GAE is good for making a little website to share favorite youtube videos ?
I have done single website in Python+Django few month... | GAE is any good ? if yes then JAVA or Python? | Basically I am coding websites in PHP from last year.
But now I want to use something else and GAE looks a good option.
So I want to know if GAE is good for making a little website to share favorite youtube videos ?
I have done single website in Python+Django few months back, it looks good to me.
But JAVA is the langua... | [
"Java and Python are both excellent languages. It is a matter of taste and believe which you choose. \n\nIf you prefer a lightweight solution, use Python.\nIf you have enterprise needs, whatever that means, use Java.\n\nIf you ask for my personal believe, my subjective stand-of-point is:\n\nUse Python wherever poss... | [
3,
3,
2,
2,
1,
1
] | [] | [] | [
"google_app_engine",
"java",
"python"
] | stackoverflow_0003263847_google_app_engine_java_python.txt |
Q:
Get thumbnail image for Yahoo video? (python)
The question has a similar intent as this question:
Get img thumbnails from Vimeo?
but that one was for vimeo.
So, I have a url for the yahoo video, is there any way I could get the standard thumbnail using the url?
Thanks
A:
Well, Yahoo supports oembed. So, you can... | Get thumbnail image for Yahoo video? (python) | The question has a similar intent as this question:
Get img thumbnails from Vimeo?
but that one was for vimeo.
So, I have a url for the yahoo video, is there any way I could get the standard thumbnail using the url?
Thanks
| [
"Well, Yahoo supports oembed. So, you can take the video url e.g., \nhttp://video.yahoo.com/watch/5202550/13742849 and pass it on to their oembed service like this:\nhttp://video.yahoo.com/services/oembed?url=http://video.yahoo.com/watch/5202550/13742849\nThe response to that will contain the thumbnail image url.\n... | [
1
] | [] | [] | [
"python",
"video",
"yahoo"
] | stackoverflow_0003262532_python_video_yahoo.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.