content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
|---|---|---|---|---|---|---|---|---|
Q:
Python: unable to inherit from a C extension
I am trying to add a few extra methods to a matrix type from the pysparse library. Apart from that I want the new class to behave exactly like the original, so I chose to implement the changes using inheritance. However, when I try
from pysparse import spmatrix
class ll_mat(spmatrix.ll_mat):
pass
this results in the following error
TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
What is this causing this error? Is there a way to use delegation so that my new class behaves exactly the same way as the original?
A:
ll_mat is documented to be a function -- not the type itself. The idiom is known as "factory function" -- it allows a "creator callable" to return different actual underlying types depending on its arguments.
You could try to generate an object from this and then inherit from that object's type:
x = spmatrix.ll_mat(10, 10)
class ll_mat(type(x)): ...
be aware, though, that it's quite feasible for a built-in type to declare it won't support being subclassed (this could be done even just to save some modest overhead); if that's what that type does, then you can't subclass it, and will rather have to use containment and delegation, i.e.:
class ll_mat(object):
def __init__(self, *a, **k):
self.m = spmatrix.ll_mat(*a, **k)
...
def __getattr__(self, n):
return getattr(self.m, n)
etc, etc.
|
Python: unable to inherit from a C extension
|
I am trying to add a few extra methods to a matrix type from the pysparse library. Apart from that I want the new class to behave exactly like the original, so I chose to implement the changes using inheritance. However, when I try
from pysparse import spmatrix
class ll_mat(spmatrix.ll_mat):
pass
this results in the following error
TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
What is this causing this error? Is there a way to use delegation so that my new class behaves exactly the same way as the original?
|
[
"ll_mat is documented to be a function -- not the type itself. The idiom is known as \"factory function\" -- it allows a \"creator callable\" to return different actual underlying types depending on its arguments.\nYou could try to generate an object from this and then inherit from that object's type:\nx = spmatrix.ll_mat(10, 10)\nclass ll_mat(type(x)): ...\n\nbe aware, though, that it's quite feasible for a built-in type to declare it won't support being subclassed (this could be done even just to save some modest overhead); if that's what that type does, then you can't subclass it, and will rather have to use containment and delegation, i.e.:\nclass ll_mat(object):\n def __init__(self, *a, **k):\n self.m = spmatrix.ll_mat(*a, **k)\n ...\n def __getattr__(self, n):\n return getattr(self.m, n)\n\netc, etc.\n"
] |
[
10
] |
[] |
[] |
[
"inheritance",
"python"
] |
stackoverflow_0002573519_inheritance_python.txt
|
Q:
Django: A Result Specific Numeration for Pagination
Simply put I want what http://www.reddit.com/ and http://news.ycombinator.com/ have to the left of every link. A numerated link starting with 1 and continuing to the next page by means of pagination.
I really enjoy using generic views and their built-in pagination for Django and it seems to allow me access to these values if I was on page 3 with 2 items per page.
{'MEDIA_URL': ''}
{'LANGUAGES': '<<languages>>',
'LANGUAGE_BIDI': False,
'LANGUAGE_CODE': 'en-us'}
{'debug': True, 'sql_queries': '<<sql_queries>>'}
{'messages': [],
'perms': <django.core.context_processors.PermWrapper object at 0xadedeec>,
'user': <User: thelizardking>}
{'first_on_page': 5,
'has_next': True,
'has_previous': True,
'hits': 7,
'is_paginated': True,
'last_on_page': 6,
'links_list': [<Link: Funky Town>, <Link: Apple Jax>],
'next': 4,
'page': 3,
'page_obj': <Page 3 of 4>,
'page_range': [1, 2, 3, 4],
'pages': 4,
'paginator': <django.core.paginator.Paginator object at 0xadf914c>,
'previous': 2,
'results_per_page': 2}
I know there is an add filter for templates but that's as close as I think I can get and that really doesn't do what I want. Am I going to have to use a custom template filter here or is there something I am not seeing?
A:
As far as I understand, this number for each item on page is computable from 'first_on_page' and number of current item on the page. Maybe you can get number of current item on the page from cycle data, but if not — you can somewhat easily write an incrementing template tag, possibly with using 'first_on_page' inside.
|
Django: A Result Specific Numeration for Pagination
|
Simply put I want what http://www.reddit.com/ and http://news.ycombinator.com/ have to the left of every link. A numerated link starting with 1 and continuing to the next page by means of pagination.
I really enjoy using generic views and their built-in pagination for Django and it seems to allow me access to these values if I was on page 3 with 2 items per page.
{'MEDIA_URL': ''}
{'LANGUAGES': '<<languages>>',
'LANGUAGE_BIDI': False,
'LANGUAGE_CODE': 'en-us'}
{'debug': True, 'sql_queries': '<<sql_queries>>'}
{'messages': [],
'perms': <django.core.context_processors.PermWrapper object at 0xadedeec>,
'user': <User: thelizardking>}
{'first_on_page': 5,
'has_next': True,
'has_previous': True,
'hits': 7,
'is_paginated': True,
'last_on_page': 6,
'links_list': [<Link: Funky Town>, <Link: Apple Jax>],
'next': 4,
'page': 3,
'page_obj': <Page 3 of 4>,
'page_range': [1, 2, 3, 4],
'pages': 4,
'paginator': <django.core.paginator.Paginator object at 0xadf914c>,
'previous': 2,
'results_per_page': 2}
I know there is an add filter for templates but that's as close as I think I can get and that really doesn't do what I want. Am I going to have to use a custom template filter here or is there something I am not seeing?
|
[
"As far as I understand, this number for each item on page is computable from 'first_on_page' and number of current item on the page. Maybe you can get number of current item on the page from cycle data, but if not — you can somewhat easily write an incrementing template tag, possibly with using 'first_on_page' inside.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"pagination",
"python"
] |
stackoverflow_0002573504_django_pagination_python.txt
|
Q:
How to extract a couple marked strings from a line (python)
My Friends,
I spent quite some time on this one... but cannot yet figure out a better way to do it. I am coding in python, by the way.
So, here is a line of text in a file I am working with, for example:
">ref|ZP_01631227.1| 3-dehydroquinate synthase [Nodularia spumigena CCY9414]..."
How can I extract the two strings "ZP_01631227.1" and "Nodularia spumigena CCY9414" from the line?
The pairs of "| |" and brackets are like markers so we know we want to get the strings in between the two...
I guess I can probably loop over all the characters in the line and do it the hard way. It just takes so much time... Wondering if there is a python library or other smart ways to do it nicely?
Thanks to all!
A:
One concise alternative is a regular expression (for some reason they have a bad rep in the Python community, but they do provide conciseness and power for simple text handling):
import re
s = ">ref|ZP_01631227.1| 3-dehydroquinate synthase [Nodularia spumigena CCY9414]..."
mo = re.search(r'\|(.*?)\|/*\[(.*?)\]', s)
if mo:
thefirst, thesecond = mo.groups()
A:
>>> for line in open("file"):
... if "|" in line:
... whatiwant_1=line.split("|")[1]
... if "[" in line:
... whatiwant_2=line.split("[")[1].split("]")[0]
...
>>> print whatiwant_1 , whatiwant_2
ZP_01631227.1 Nodularia spumigena CCY9414
|
How to extract a couple marked strings from a line (python)
|
My Friends,
I spent quite some time on this one... but cannot yet figure out a better way to do it. I am coding in python, by the way.
So, here is a line of text in a file I am working with, for example:
">ref|ZP_01631227.1| 3-dehydroquinate synthase [Nodularia spumigena CCY9414]..."
How can I extract the two strings "ZP_01631227.1" and "Nodularia spumigena CCY9414" from the line?
The pairs of "| |" and brackets are like markers so we know we want to get the strings in between the two...
I guess I can probably loop over all the characters in the line and do it the hard way. It just takes so much time... Wondering if there is a python library or other smart ways to do it nicely?
Thanks to all!
|
[
"One concise alternative is a regular expression (for some reason they have a bad rep in the Python community, but they do provide conciseness and power for simple text handling):\nimport re\ns = \">ref|ZP_01631227.1| 3-dehydroquinate synthase [Nodularia spumigena CCY9414]...\"\nmo = re.search(r'\\|(.*?)\\|/*\\[(.*?)\\]', s)\nif mo:\n thefirst, thesecond = mo.groups()\n\n",
">>> for line in open(\"file\"):\n... if \"|\" in line:\n... whatiwant_1=line.split(\"|\")[1]\n... if \"[\" in line:\n... whatiwant_2=line.split(\"[\")[1].split(\"]\")[0]\n...\n>>> print whatiwant_1 , whatiwant_2\nZP_01631227.1 Nodularia spumigena CCY9414\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"extract",
"line",
"python",
"string"
] |
stackoverflow_0002573698_extract_line_python_string.txt
|
Q:
Django - urls.py - Filenames with a hash/pound (#) sign?
I'm using django and realized that when the filename that the user wants to access (let's say a photo) has the pound sign, the entry in the url.py does not match.
Any ideas?
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':
MEDIA_ROOT},
it just says:
"/home/user/project/static/upload/images/hello" does not exist
when actually the name of the file is:
hello#world.jpg
Thanks,
Nico
A:
This isn't really Django's fault - the pound (#) sign in a URL means to load the specified anchor on the page. You need to encode the pound sign in your URL to get the browser to request the full image path:
/home/user/project/static/upload/images/hello%23world.jpg
In a Django template you can use the urlencode template tag.
|
Django - urls.py - Filenames with a hash/pound (#) sign?
|
I'm using django and realized that when the filename that the user wants to access (let's say a photo) has the pound sign, the entry in the url.py does not match.
Any ideas?
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':
MEDIA_ROOT},
it just says:
"/home/user/project/static/upload/images/hello" does not exist
when actually the name of the file is:
hello#world.jpg
Thanks,
Nico
|
[
"This isn't really Django's fault - the pound (#) sign in a URL means to load the specified anchor on the page. You need to encode the pound sign in your URL to get the browser to request the full image path:\n/home/user/project/static/upload/images/hello%23world.jpg\n\nIn a Django template you can use the urlencode template tag.\n"
] |
[
11
] |
[] |
[] |
[
"django",
"python",
"regex"
] |
stackoverflow_0002573803_django_python_regex.txt
|
Q:
Control links2 by python
Is there any way to control links browser from python?
I need to make some bot, twill don't work on my page, Selenium need's X server.
Maybe other way to do it?
A:
Using X virtual framebuffer Xvfb you can run selenium/web browser without X:
Xvfb :1 -screen 0 1152x864x16
DISPLAY=1 ./firefox
and run the selenium tests from command line.
A:
I would try to use pexpect (on Unix-like systems; wexpect on Windows), just as I would for the purpose of controlling other text-based, interactive applications that don't offer an explicit API of their own.
|
Control links2 by python
|
Is there any way to control links browser from python?
I need to make some bot, twill don't work on my page, Selenium need's X server.
Maybe other way to do it?
|
[
"Using X virtual framebuffer Xvfb you can run selenium/web browser without X:\nXvfb :1 -screen 0 1152x864x16\nDISPLAY=1 ./firefox\n\nand run the selenium tests from command line.\n",
"I would try to use pexpect (on Unix-like systems; wexpect on Windows), just as I would for the purpose of controlling other text-based, interactive applications that don't offer an explicit API of their own.\n"
] |
[
1,
0
] |
[] |
[] |
[
"controls",
"hyperlink",
"python"
] |
stackoverflow_0002572123_controls_hyperlink_python.txt
|
Q:
Django1.1 model field value preprocessing before returning
I have a model class like this:
class Note(models.Model):
author = models.ForeignKey(User, related_name='notes')
content = NoteContentField(max_length=256)
NoteContentField is a custom sub-class of CharField that override the to_python method in purpose of doing some twitter-text-conversion processing.
class NoteContentField(models.CharField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
value = super(NoteContentField, self).to_python(value)
from ..utils import linkify
return mark_safe(linkify(value))
However, this doesn't work.
When I save a Note object like this:
note = Note(author=request.use,
content=form.cleaned_data['content'])
note.save()
The conversed value is saved into the database, which is not what I wanna see.
What I'm trying to do is to save the raw content into the database, and only make the conversion when the content attribute is later accessed.
Would you please tell me what's wrong with this?
Thanks to Pierre and Daniel.
I have figured out what's wrong.
I thought the text-conversion code should be in either to_python or get_db_prep_value, and that's wrong.
I should override both of them, make to_python do the conversion and get_db_prep_value return the unconversed value:
from ..utils import linkify
class NoteContentField(models.CharField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
self._raw_value = super(NoteContentField, self).to_python(value)
return mark_safe(linkify(self._raw_value))
def get_db_prep_value(self, value):
return self._raw_value
I wonder if there is a better way to implement this?
A:
I think you should provide the reverse function to to_python.
Take a look at Django doc here : Converting Python objects to query value
A:
You seem to have only read half the docs. As Pierre-Jean noted above, and even linked you to the correct part of the document, you need to define the reverse function, which is get_db_prep_value.
|
Django1.1 model field value preprocessing before returning
|
I have a model class like this:
class Note(models.Model):
author = models.ForeignKey(User, related_name='notes')
content = NoteContentField(max_length=256)
NoteContentField is a custom sub-class of CharField that override the to_python method in purpose of doing some twitter-text-conversion processing.
class NoteContentField(models.CharField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
value = super(NoteContentField, self).to_python(value)
from ..utils import linkify
return mark_safe(linkify(value))
However, this doesn't work.
When I save a Note object like this:
note = Note(author=request.use,
content=form.cleaned_data['content'])
note.save()
The conversed value is saved into the database, which is not what I wanna see.
What I'm trying to do is to save the raw content into the database, and only make the conversion when the content attribute is later accessed.
Would you please tell me what's wrong with this?
Thanks to Pierre and Daniel.
I have figured out what's wrong.
I thought the text-conversion code should be in either to_python or get_db_prep_value, and that's wrong.
I should override both of them, make to_python do the conversion and get_db_prep_value return the unconversed value:
from ..utils import linkify
class NoteContentField(models.CharField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
self._raw_value = super(NoteContentField, self).to_python(value)
return mark_safe(linkify(self._raw_value))
def get_db_prep_value(self, value):
return self._raw_value
I wonder if there is a better way to implement this?
|
[
"I think you should provide the reverse function to to_python. \nTake a look at Django doc here : Converting Python objects to query value\n",
"You seem to have only read half the docs. As Pierre-Jean noted above, and even linked you to the correct part of the document, you need to define the reverse function, which is get_db_prep_value.\n"
] |
[
1,
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002573446_django_django_models_python.txt
|
Q:
How to handle redirects while parsing HTML? - Python
I'm trying to submit a few forms through a Python script, I'm using the mechanized library.
This is so I can implement a temporary API.
The problem is that before after submission a blank page is returned informing that the request is being processed, after a few seconds the page is redirected to the final page.
I understand if it might sound a bit generic, but I'm not sure what is going on. :)
Any ideas?
A:
Traditionally When you get a redirect, the status code of the response is 302, and there's a location header that instructs the browser where to go next. Other techniques(that are lame) would be to put a meta refresh tag in the head of the document.
<meta http-equiv="refresh" content="2;url=http://nextlocation.com">
And I suppose there's any number of ways to do it with javascript(also lame)
A:
If it uses meta tags then you need to parse the HTML manually. Otherwise mechanize will handle the redirect automatically.
|
How to handle redirects while parsing HTML? - Python
|
I'm trying to submit a few forms through a Python script, I'm using the mechanized library.
This is so I can implement a temporary API.
The problem is that before after submission a blank page is returned informing that the request is being processed, after a few seconds the page is redirected to the final page.
I understand if it might sound a bit generic, but I'm not sure what is going on. :)
Any ideas?
|
[
"Traditionally When you get a redirect, the status code of the response is 302, and there's a location header that instructs the browser where to go next. Other techniques(that are lame) would be to put a meta refresh tag in the head of the document.\n<meta http-equiv=\"refresh\" content=\"2;url=http://nextlocation.com\">\n\nAnd I suppose there's any number of ways to do it with javascript(also lame)\n",
"If it uses meta tags then you need to parse the HTML manually. Otherwise mechanize will handle the redirect automatically. \n"
] |
[
2,
1
] |
[] |
[] |
[
"forms",
"html",
"http",
"python",
"screen_scraping"
] |
stackoverflow_0002569089_forms_html_http_python_screen_scraping.txt
|
Q:
How to use Django's filesizeformat
I have a small app I'm working on where I'm trying to use Django's built in filesizeformat. Currently, the format looks like this: {{ value|filesizeformat }}. I understand I need to define this in my view.py file but, I can't seem to figure out how to do that. I've tried to use the syntax below:
def filesizeformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
"""
try:
bytes = float(bytes)
except (TypeError,ValueError,UnicodeDecodeError):
return u"0 bytes"
if bytes < 1024:
return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
if bytes < 1024 * 1024:
return ugettext("%.1f KB") % (bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return ugettext("%.1f MB") % (bytes / (1024 * 1024))
return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024))
filesizeformat.is_safe = True
I've then replaced 'value' with 'bytes' in the template but, this does not seem to work. Any suggestions?
A:
filesizeformat is a built-in filter, you do not need to implement it yourself. You should provide the value into the template, for example:
{% for page in pages %}
<li>page.name {{page.size|filesizeformat}}</li>
{% endfor %}
Now when you render the template from the view provide a pages argument which is a list of dicts like:
[{'name': 'page1', 'size': 10000}, {'name': 'page2', 'size': 5023034}]
And so on.
|
How to use Django's filesizeformat
|
I have a small app I'm working on where I'm trying to use Django's built in filesizeformat. Currently, the format looks like this: {{ value|filesizeformat }}. I understand I need to define this in my view.py file but, I can't seem to figure out how to do that. I've tried to use the syntax below:
def filesizeformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
"""
try:
bytes = float(bytes)
except (TypeError,ValueError,UnicodeDecodeError):
return u"0 bytes"
if bytes < 1024:
return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
if bytes < 1024 * 1024:
return ugettext("%.1f KB") % (bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return ugettext("%.1f MB") % (bytes / (1024 * 1024))
return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024))
filesizeformat.is_safe = True
I've then replaced 'value' with 'bytes' in the template but, this does not seem to work. Any suggestions?
|
[
"filesizeformat is a built-in filter, you do not need to implement it yourself. You should provide the value into the template, for example:\n{% for page in pages %}\n <li>page.name {{page.size|filesizeformat}}</li>\n{% endfor %}\n\nNow when you render the template from the view provide a pages argument which is a list of dicts like: \n[{'name': 'page1', 'size': 10000}, {'name': 'page2', 'size': 5023034}]\n\nAnd so on.\n"
] |
[
12
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002574540_django_python.txt
|
Q:
how to create multiple selections in text edit box in qt4?
Qt3.3 used to allow for multiple selections in the QTextEdit widget by calling the setSelection() function and specifying a different selection id (selNum) as the last argument in that function.
In Qt4, to create a selection, I do it by creating a QTextCursor object and call the setPosition() or movePosition() methods. I have no problems being able to create a single selection of text. I am, however, unable to find a way to create multiple selections. The methods in Qt4 do not have an argument which allows you to set a selection id, nor can i find any other function in the QTextCursor or QTextEdit which looks like it might allow me to do so.
Has this feature been completely removed from Qt4? or has is there a new and different way of doing it?
Thanks.
Ronny
A:
The solution, i realise now is actually quite simple.
To graphically visualise all the various selections (separate QTextCursor objects), instead of calling the setTextCursor() method for the QTextEdit widget for each of the selections, i change the background color of each of those sections of text by calling the setCharFormat() method for each of those QTextCursor objects.
A:
How about creating multiple cursors (QTextCursor), each selection a different portion of the text. Would that work for you?
|
how to create multiple selections in text edit box in qt4?
|
Qt3.3 used to allow for multiple selections in the QTextEdit widget by calling the setSelection() function and specifying a different selection id (selNum) as the last argument in that function.
In Qt4, to create a selection, I do it by creating a QTextCursor object and call the setPosition() or movePosition() methods. I have no problems being able to create a single selection of text. I am, however, unable to find a way to create multiple selections. The methods in Qt4 do not have an argument which allows you to set a selection id, nor can i find any other function in the QTextCursor or QTextEdit which looks like it might allow me to do so.
Has this feature been completely removed from Qt4? or has is there a new and different way of doing it?
Thanks.
Ronny
|
[
"The solution, i realise now is actually quite simple. \nTo graphically visualise all the various selections (separate QTextCursor objects), instead of calling the setTextCursor() method for the QTextEdit widget for each of the selections, i change the background color of each of those sections of text by calling the setCharFormat() method for each of those QTextCursor objects. \n",
"How about creating multiple cursors (QTextCursor), each selection a different portion of the text. Would that work for you?\n"
] |
[
1,
0
] |
[] |
[] |
[
"pyqt",
"python",
"qt",
"qt4"
] |
stackoverflow_0002574195_pyqt_python_qt_qt4.txt
|
Q:
Monitor and Terminate Python script based on system resource use
What is the "right" or "best" way to monitor the system resources a python script is using and terminate it if the resource use exceeds some predetermined values. In my case memory usage is of concern. I am not asking how to measure the system resource use although I am open to suggestions.
As a simple example, let's assume I have a function that finds prime numbers less than some large number and adds them to a list based on some condition. I don't know ahead of time how many prime numbers will satisfy the condition so I what to be sure to terminate the function if I use up to much system memory (8gb lets say).
I know that there are ways to monitor the size of python objects. What I don't know is the proper way to monitor the size of the list and exit is to just include a size test in the prime function loop and exit if it exceeds 8gb or if there is an "external" (by external I mean external to the loop but still within or part of the python script) way to monitor and exit.
In my case I am running on a mac but am asking the question in general.
A:
On Unix-like system, a useful "external" way to monitor any process is the ulimit command (you don't clarify whether you want instead to run in Windows, where ulimit doesn't exist and other approaches may, but I don't know them;-).
If you're thinking about performing such controls inside your own Python programs, just change the function in question to check the size of each object it's appending to the list (and keep a running total) and return when the running total reaches or exceeds a threshold (which you could pass as an extra parameter to the function in question).
Edit: the OP has clarified in a comment that they want the monitoring in the very worst place it could possibly be placed -- in the previous paragraphs, I mentioned how it's easy outside of the process, easy inside the function, but the OP wants it "smack in the middle";-).
Least-bad way is probably with a "watchdog thread" -- a separate daemon thread in an infinite loop which, every X seconds, checks the process's resource consumption (e.g. with resource.getrusage, if on Unix-like machines -- again, if on Windows, something else is needed instead) and, if that consumption exceeds the desired limits, attempts to kill the main thread with thread.interrupt_main. Of course, this is fail from foolproof: the periodicity X (like in all cases of "polling") must be low enough to stop a runaway process in the meantime, but high enough to not slow the process down to a crawl. Plus, the main thread (the only one that can be interrupted like this) might be blocking exceptions (in which case the watchdog thread might perhaps try with "signals to this very process" of growing severity, all the way up to SIGKILL, the killer-signal that can never be blocked or intercepted).
So, this intermediate approach is a lot more work than the ulimit command, is more fragile, and has no substantial added value. But, if you want to put the monitoring "inside the process but outside the resource-consuming function", with no advantages, lots of work, and the other disadvantages I've mentioned, this is the way to do it.
A:
resource.getrusage() (in particular ru_idrss) can give you the resource usage of the current python interpreter, which you can use as a sentinel to stop processing.
|
Monitor and Terminate Python script based on system resource use
|
What is the "right" or "best" way to monitor the system resources a python script is using and terminate it if the resource use exceeds some predetermined values. In my case memory usage is of concern. I am not asking how to measure the system resource use although I am open to suggestions.
As a simple example, let's assume I have a function that finds prime numbers less than some large number and adds them to a list based on some condition. I don't know ahead of time how many prime numbers will satisfy the condition so I what to be sure to terminate the function if I use up to much system memory (8gb lets say).
I know that there are ways to monitor the size of python objects. What I don't know is the proper way to monitor the size of the list and exit is to just include a size test in the prime function loop and exit if it exceeds 8gb or if there is an "external" (by external I mean external to the loop but still within or part of the python script) way to monitor and exit.
In my case I am running on a mac but am asking the question in general.
|
[
"On Unix-like system, a useful \"external\" way to monitor any process is the ulimit command (you don't clarify whether you want instead to run in Windows, where ulimit doesn't exist and other approaches may, but I don't know them;-).\nIf you're thinking about performing such controls inside your own Python programs, just change the function in question to check the size of each object it's appending to the list (and keep a running total) and return when the running total reaches or exceeds a threshold (which you could pass as an extra parameter to the function in question).\nEdit: the OP has clarified in a comment that they want the monitoring in the very worst place it could possibly be placed -- in the previous paragraphs, I mentioned how it's easy outside of the process, easy inside the function, but the OP wants it \"smack in the middle\";-). \nLeast-bad way is probably with a \"watchdog thread\" -- a separate daemon thread in an infinite loop which, every X seconds, checks the process's resource consumption (e.g. with resource.getrusage, if on Unix-like machines -- again, if on Windows, something else is needed instead) and, if that consumption exceeds the desired limits, attempts to kill the main thread with thread.interrupt_main. Of course, this is fail from foolproof: the periodicity X (like in all cases of \"polling\") must be low enough to stop a runaway process in the meantime, but high enough to not slow the process down to a crawl. Plus, the main thread (the only one that can be interrupted like this) might be blocking exceptions (in which case the watchdog thread might perhaps try with \"signals to this very process\" of growing severity, all the way up to SIGKILL, the killer-signal that can never be blocked or intercepted).\nSo, this intermediate approach is a lot more work than the ulimit command, is more fragile, and has no substantial added value. But, if you want to put the monitoring \"inside the process but outside the resource-consuming function\", with no advantages, lots of work, and the other disadvantages I've mentioned, this is the way to do it.\n",
"resource.getrusage() (in particular ru_idrss) can give you the resource usage of the current python interpreter, which you can use as a sentinel to stop processing.\n"
] |
[
2,
2
] |
[] |
[] |
[
"monitoring",
"python",
"resources",
"terminate"
] |
stackoverflow_0002573736_monitoring_python_resources_terminate.txt
|
Q:
MySql: How to know if an entry is compressed or not
I'm working with python and mysql and I want to verify that a certain entry is compressed in the db. Ie:
cur = db.getCursor()
cur.execute('''select compressed_column from table where id=12345''')
res = cur.fetchall()
at this point I would like to verify that the entry is compressed (ie in order to work with the data you would have to use select uncompress(compressed_column)..). Ideas?
A:
COMPRESS() on MySQL uses zlib, therefore you can try the following to see if the string is compressed:
try:
out = s.decode('zlib')
except zlib.error:
out = s
|
MySql: How to know if an entry is compressed or not
|
I'm working with python and mysql and I want to verify that a certain entry is compressed in the db. Ie:
cur = db.getCursor()
cur.execute('''select compressed_column from table where id=12345''')
res = cur.fetchall()
at this point I would like to verify that the entry is compressed (ie in order to work with the data you would have to use select uncompress(compressed_column)..). Ideas?
|
[
"COMPRESS() on MySQL uses zlib, therefore you can try the following to see if the string is compressed:\ntry:\n out = s.decode('zlib')\nexcept zlib.error:\n out = s\n\n"
] |
[
4
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0002574687_mysql_python.txt
|
Q:
python sax error "junk after document element"
I use python sax to parse xml file.
The xml file is actually a combination of multiple xml files.
It looks like as follows:
<row name="abc" age="40" body="blalalala..." creationdate="03/10/10" />
<row name="bcd" age="50" body="blalalala..." creationdate="03/10/09" />
My python code is in the following. It show "junk after document element" error. Any good idea to solve this problem. Thanks.
from xml.sax.handler import ContentHandler
from xml.sax import make_parser,SAXException
import sys
class PostHandler (ContentHandler):
def __init__(self):
self.find = 0
self.buffer = ''
self.mapping={}
def startElement(self,name,attrs):
if name == 'row':
self.find = 1
self.body = attrs["body"]
print attrs["body"]
def character(self,data):
if self.find==1:
self.buffer+=data
def endElement(self,name):
if self.find == 1:
self.mapping[self.body] = self.buffer
print self.mapping
parser = make_parser()
handler = PostHandler()
parser.setContentHandler(handler)
try:
parser.parse(open("2.xml"))
except SAXException:
A:
xmldata = '''
<row name="abc" age="40" body="blalalala..." creationdate="03/10/10" />
<row name="bcd" age="50" body="blalalala..." creationdate="03/10/09" />
'''
Add a wrapper tag around the data. I've used ElementTree since it's so simpler, but you'd be able to do the same on any parser:
from xml.etree import ElementTree as etree
# wrap the data
xmldata = '<rows>' +data + '</rows>'
rows = etree.fromstring(xmldata)
for row in rows:
print row.attrib
Results in
{'age': '40',
'body': 'blalalala...',
'creationdate': '03/10/10',
'name': 'abc'}
{'age': '50',
'body': 'blalalala...',
'creationdate': '03/10/09',
'name': 'bcd'}
A:
Seems that you do not have root element in your XML file. Wrap your row elements into single rows element.
|
python sax error "junk after document element"
|
I use python sax to parse xml file.
The xml file is actually a combination of multiple xml files.
It looks like as follows:
<row name="abc" age="40" body="blalalala..." creationdate="03/10/10" />
<row name="bcd" age="50" body="blalalala..." creationdate="03/10/09" />
My python code is in the following. It show "junk after document element" error. Any good idea to solve this problem. Thanks.
from xml.sax.handler import ContentHandler
from xml.sax import make_parser,SAXException
import sys
class PostHandler (ContentHandler):
def __init__(self):
self.find = 0
self.buffer = ''
self.mapping={}
def startElement(self,name,attrs):
if name == 'row':
self.find = 1
self.body = attrs["body"]
print attrs["body"]
def character(self,data):
if self.find==1:
self.buffer+=data
def endElement(self,name):
if self.find == 1:
self.mapping[self.body] = self.buffer
print self.mapping
parser = make_parser()
handler = PostHandler()
parser.setContentHandler(handler)
try:
parser.parse(open("2.xml"))
except SAXException:
|
[
"xmldata = '''\n<row name=\"abc\" age=\"40\" body=\"blalalala...\" creationdate=\"03/10/10\" />\n<row name=\"bcd\" age=\"50\" body=\"blalalala...\" creationdate=\"03/10/09\" />\n'''\n\nAdd a wrapper tag around the data. I've used ElementTree since it's so simpler, but you'd be able to do the same on any parser:\nfrom xml.etree import ElementTree as etree\n\n# wrap the data\nxmldata = '<rows>' +data + '</rows>'\n\nrows = etree.fromstring(xmldata)\nfor row in rows:\n print row.attrib\n\nResults in\n{'age': '40',\n 'body': 'blalalala...',\n 'creationdate': '03/10/10',\n 'name': 'abc'}\n{'age': '50',\n 'body': 'blalalala...',\n 'creationdate': '03/10/09',\n 'name': 'bcd'}\n\n",
"Seems that you do not have root element in your XML file. Wrap your row elements into single rows element.\n"
] |
[
11,
4
] |
[] |
[] |
[
"python",
"sax"
] |
stackoverflow_0002574894_python_sax.txt
|
Q:
AppEngine: how do cursors work?
i have the following code
def get(self):
date = datetime.date.today()
loc_query = Location.all()
last_cursor = memcache.get('location_cursor')
if last_cursor: loc_query.with_cursor(last_cursor)
loc_result = loc_query.fetch(1)
for loc in loc_result:
self.record(loc, date)
taskqueue.add(
url='/task/query/simplegeo',
params={'date':date, 'locid':loc.key().id()}
)
if len(loc_result):
memcache.add('location_cursor', loc_query.cursor())
taskqueue.add(url='/task/count/', method='GET')
else:
memcache.add('location_cursor', None)
i don't know what i'm doing wrong, but i am getting the same cursor which is not the effect i wanted. why isn't the cursor moving?
A:
You're misusing memcache.add, which is documented here as:
Sets a key's value, if and only if the
item is not already in memcache.
So you're never storing any cursor different from the first one. Use memcache.set instead, which
Sets a key's value, regardless of
previous contents in cache.
Note that this has nothing to do with cursors -- it's all about proper use of memcache!
|
AppEngine: how do cursors work?
|
i have the following code
def get(self):
date = datetime.date.today()
loc_query = Location.all()
last_cursor = memcache.get('location_cursor')
if last_cursor: loc_query.with_cursor(last_cursor)
loc_result = loc_query.fetch(1)
for loc in loc_result:
self.record(loc, date)
taskqueue.add(
url='/task/query/simplegeo',
params={'date':date, 'locid':loc.key().id()}
)
if len(loc_result):
memcache.add('location_cursor', loc_query.cursor())
taskqueue.add(url='/task/count/', method='GET')
else:
memcache.add('location_cursor', None)
i don't know what i'm doing wrong, but i am getting the same cursor which is not the effect i wanted. why isn't the cursor moving?
|
[
"You're misusing memcache.add, which is documented here as:\n\nSets a key's value, if and only if the\n item is not already in memcache.\n\nSo you're never storing any cursor different from the first one. Use memcache.set instead, which\n\nSets a key's value, regardless of\n previous contents in cache.\n\nNote that this has nothing to do with cursors -- it's all about proper use of memcache!\n"
] |
[
5
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002575068_python.txt
|
Q:
Boost.python building
really can't understand, how to build correctly project that uses boost.python. I've included boost_(python/thread/system)-mt. Here is simple module file:
#include <boost/python.hpp>
#include "script.hpp"
#include "boost/python/detail/wrap_python.hpp"
BOOST_PYTHON_MODULE(temp)
{
namespace py = boost::python;
py::def("PyLog", &engine::log);
}
Here is bulid log: http://dpaste.com/179232/.
Can't imagine what I forgot.
System: arch linux;
ls /usr/lib |grep boost : http://dpaste.com/179233/
A:
That looks like a missing library in link phase. All those undefined references are included in the Python library. You probably just need to add something like "-lpython2.5" to your last gcc command.
A:
You seem to be missing the headers from python itself.
The symbols such as PySequence_GetSlice and PyExc_ValueError are from the Python headers, not the boost::python headers.
That's all I can say, sorry. I don't really know boost::python. I'm surprised you don't have any error with "missing include file". I guess boost::python doesn't include the python headers itself?
btw, I saw the following on http://www.boost.org/doc/libs/1_42_0/libs/python/doc/building.html
Be sure not to #include any
system headers before wrap_python.hpp.
This restriction is actually imposed
by Python, or more properly, by
Python's interaction with your
operating system. See
http://docs.python.org/ext/simpleExample.html
for details.
maybe that can help?
|
Boost.python building
|
really can't understand, how to build correctly project that uses boost.python. I've included boost_(python/thread/system)-mt. Here is simple module file:
#include <boost/python.hpp>
#include "script.hpp"
#include "boost/python/detail/wrap_python.hpp"
BOOST_PYTHON_MODULE(temp)
{
namespace py = boost::python;
py::def("PyLog", &engine::log);
}
Here is bulid log: http://dpaste.com/179232/.
Can't imagine what I forgot.
System: arch linux;
ls /usr/lib |grep boost : http://dpaste.com/179233/
|
[
"That looks like a missing library in link phase. All those undefined references are included in the Python library. You probably just need to add something like \"-lpython2.5\" to your last gcc command.\n",
"You seem to be missing the headers from python itself.\nThe symbols such as PySequence_GetSlice and PyExc_ValueError are from the Python headers, not the boost::python headers.\nThat's all I can say, sorry. I don't really know boost::python. I'm surprised you don't have any error with \"missing include file\". I guess boost::python doesn't include the python headers itself?\nbtw, I saw the following on http://www.boost.org/doc/libs/1_42_0/libs/python/doc/building.html\n\nBe sure not to #include any\n system headers before wrap_python.hpp.\n This restriction is actually imposed\n by Python, or more properly, by\n Python's interaction with your\n operating system. See\n http://docs.python.org/ext/simpleExample.html\n for details.\n\nmaybe that can help?\n"
] |
[
2,
1
] |
[] |
[] |
[
"boost",
"building",
"python"
] |
stackoverflow_0002573667_boost_building_python.txt
|
Q:
What does printing an empty line do?
I know this question may well be the silliest question you've heard today, but to me it is a big question at this stage of my programming learning.
Why is the second empty line needed in this Python code? What does that line do?
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'
A:
It prints an empty line, just as you have said. It will leave a blank line in the output. The print statement prints its arguments, and then a newline, so this prints just a newline.
You could accomplish the same thing with just:
print
A:
A blank line is required between the headers and the body in an HTTP response, so a CGI script will print a blank line at just that spot. There's no need for the quotes though, since an unadorned print will output a blank line.
A:
Did you even tried to telnet web-server?
It needs \n.
So, it's what it does, you can write it in one line if needed.
print 'Content-Type: text/plain\n\nHello World'
|
What does printing an empty line do?
|
I know this question may well be the silliest question you've heard today, but to me it is a big question at this stage of my programming learning.
Why is the second empty line needed in this Python code? What does that line do?
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'
|
[
"It prints an empty line, just as you have said. It will leave a blank line in the output. The print statement prints its arguments, and then a newline, so this prints just a newline.\nYou could accomplish the same thing with just:\nprint\n\n",
"A blank line is required between the headers and the body in an HTTP response, so a CGI script will print a blank line at just that spot. There's no need for the quotes though, since an unadorned print will output a blank line.\n",
"Did you even tried to telnet web-server?\nIt needs \\n.\nSo, it's what it does, you can write it in one line if needed.\nprint 'Content-Type: text/plain\\n\\nHello World'\n\n"
] |
[
12,
4,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002575584_python.txt
|
Q:
Not-quite-JSON string deserialization in Python
I get the following text as a string from an XML-based REST API
'd':4 'ca':5 'sen':1 'diann':2,6,8 'feinstein':3,7,9
that I'm looking to deserialize into a pretty little Python dictionary:
{
'd': [4],
'ca': [5],
'sen': [1],
'diann': [2, 6, 8],
'feinstein': [3, 7, 9]
}
I'm hoping to avoid using regular expressions or heavy string manipulation, as this format isn't documented and may change. The best I've been able to come up with:
members = {}
for m in elem.text.split(' '):
m = m.split(':')
members[m[0].replace("'", '')] = map(int, m[1].split(','))
return members
Obviously a terrible approach, but it works, and that's better than anything else I've got right now. Any suggestions on better approaches?
A:
I would rewrite it as this (the only difference is explicitely naming m[0] and m[1]):
members = {}
for m in elem.text.split(' '):
key, value = m.split(':')
members[key.replace("'", '')] = map(int, value.split(','))
return members
Otherwise this code looks pretty much fine to me. It could be written a little shorter maybe (but that would decrease it's readability).
A:
I actually like ChristopheD's answer, but in the interest of exploring other possibilities, there's:
eval("{" + s.replace(":", ":[").replace(" ", "], ") + "]}")
This does some simple replacements to turn the string into legal Python, then uses eval to turn it into a dictionary.
The downsides to this method:
eval is dangerous. If the input isn't trusted (and most isn't), then your system could be compromised.
It's kind of terse and perhaps inflexible if the format changes in a way that's not amenable to converting to Python.
|
Not-quite-JSON string deserialization in Python
|
I get the following text as a string from an XML-based REST API
'd':4 'ca':5 'sen':1 'diann':2,6,8 'feinstein':3,7,9
that I'm looking to deserialize into a pretty little Python dictionary:
{
'd': [4],
'ca': [5],
'sen': [1],
'diann': [2, 6, 8],
'feinstein': [3, 7, 9]
}
I'm hoping to avoid using regular expressions or heavy string manipulation, as this format isn't documented and may change. The best I've been able to come up with:
members = {}
for m in elem.text.split(' '):
m = m.split(':')
members[m[0].replace("'", '')] = map(int, m[1].split(','))
return members
Obviously a terrible approach, but it works, and that's better than anything else I've got right now. Any suggestions on better approaches?
|
[
"I would rewrite it as this (the only difference is explicitely naming m[0] and m[1]):\nmembers = {}\nfor m in elem.text.split(' '):\n key, value = m.split(':')\n members[key.replace(\"'\", '')] = map(int, value.split(','))\n return members\n\nOtherwise this code looks pretty much fine to me. It could be written a little shorter maybe (but that would decrease it's readability).\n",
"I actually like ChristopheD's answer, but in the interest of exploring other possibilities, there's:\neval(\"{\" + s.replace(\":\", \":[\").replace(\" \", \"], \") + \"]}\")\n\nThis does some simple replacements to turn the string into legal Python, then uses eval to turn it into a dictionary.\nThe downsides to this method:\n\neval is dangerous. If the input isn't trusted (and most isn't), then your system could be compromised.\nIt's kind of terse and perhaps inflexible if the format changes in a way that's not amenable to converting to Python.\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"python",
"regex",
"serialization",
"string"
] |
stackoverflow_0002575449_python_regex_serialization_string.txt
|
Q:
nonzeros in csr_matrix in scipy.sparse matrices
There is a nonzero() method for the csr_matrix of scipy library, however trying to use that function for csr matrices result in an error, according to the manual that should return a tuple with row and colum arrays. Any ideas on this problem?
Best regards,
Umut
A:
Umut, could you provide a code snippet? The following works for me:
import scipy.sparse as sparse
x = sparse.csr_matrix([[1,0,1],[0,1,0]])
x.nonzero()
and yields
(array([0, 0, 1], dtype=int32), array([0, 2, 1], dtype=int32))
This is for the latest development version of scipy (you can check by printing scipy.__version__).
|
nonzeros in csr_matrix in scipy.sparse matrices
|
There is a nonzero() method for the csr_matrix of scipy library, however trying to use that function for csr matrices result in an error, according to the manual that should return a tuple with row and colum arrays. Any ideas on this problem?
Best regards,
Umut
|
[
"Umut, could you provide a code snippet? The following works for me:\nimport scipy.sparse as sparse\nx = sparse.csr_matrix([[1,0,1],[0,1,0]])\nx.nonzero()\n\nand yields\n(array([0, 0, 1], dtype=int32), array([0, 2, 1], dtype=int32))\n\nThis is for the latest development version of scipy (you can check by printing scipy.__version__).\n"
] |
[
1
] |
[] |
[] |
[
"python",
"scipy"
] |
stackoverflow_0002574057_python_scipy.txt
|
Q:
Python lookup hostname from IP with 1 second timeout
How can I look up a hostname given an IP address? Furthermore, how can I specify a timeout in case no such reverse DNS entry exists? Trying to keep things as fast as possible. Or is there a better way? Thank you!
A:
>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])
For implementing the timeout on the function, this stackoverflow thread has answers on that.
A:
What you're trying to accomplish is called Reverse DNS lookup.
socket.gethostbyaddr("IP")
# => (hostname, alias-list, IP)
http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr
However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.
|
Python lookup hostname from IP with 1 second timeout
|
How can I look up a hostname given an IP address? Furthermore, how can I specify a timeout in case no such reverse DNS entry exists? Trying to keep things as fast as possible. Or is there a better way? Thank you!
|
[
">>> import socket\n>>> socket.gethostbyaddr(\"69.59.196.211\")\n('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])\n\nFor implementing the timeout on the function, this stackoverflow thread has answers on that.\n",
"What you're trying to accomplish is called Reverse DNS lookup. \nsocket.gethostbyaddr(\"IP\") \n# => (hostname, alias-list, IP)\n\nhttp://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr\nHowever, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.\n"
] |
[
108,
21
] |
[] |
[] |
[
"dns",
"hostname",
"nameservers",
"python"
] |
stackoverflow_0002575760_dns_hostname_nameservers_python.txt
|
Q:
What's an easy and fast way to put returned XML data into a dict?
I'm trying to take the data returned from:
http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true
Into a dict in a fast and easy way. What's the best way to do this?
Thanks.
A:
Using xml from the standard Python library:
import xml.etree.ElementTree as xee
contents='''\
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Ip>74.125.45.100</Ip>
<Status>OK</Status>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
<RegionCode>06</RegionCode>
<RegionName>California</RegionName>
<City>Mountain View</City>
<ZipPostalCode>94043</ZipPostalCode>
<Latitude>37.4192</Latitude>
<Longitude>-122.057</Longitude>
<TimezoneName>America/Los_Angeles</TimezoneName>
<Gmtoffset>-25200</Gmtoffset>
<Isdst>1</Isdst>
</Response>'''
doc=xee.fromstring(contents)
print dict(((elt.tag,elt.text) for elt in doc))
Or using lxml:
import lxml.etree
import urllib2
url='http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true'
doc = lxml.etree.parse( urllib2.urlopen(url) ).getroot()
print dict(((elt.tag,elt.text) for elt in doc))
A:
I would use the xml.dom builtin, something like this:
import urllib
from xml.dom import minidom
data = urllib.urlopen('http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true')
xml_data = minidom.parse(data)
my_dict ={}
for node in xml_data.getElementsByTagName('Response')[0].childNodes:
if node.nodeType != minidom.Node.TEXT_NODE:
my_dict[node.nodeName] = node.childNodes[0].data
A:
xml.etree from standard library starting from python2.5. look also at lxml which has the same interface. I don't "dived in" to much but i think that this is also applicable to python >= 2.5 too.
Edit:
This is a fast and really easy way to parse xml, don't really put data to a dict but the api is pretty intuitive.
|
What's an easy and fast way to put returned XML data into a dict?
|
I'm trying to take the data returned from:
http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true
Into a dict in a fast and easy way. What's the best way to do this?
Thanks.
|
[
"Using xml from the standard Python library:\nimport xml.etree.ElementTree as xee\ncontents='''\\\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response>\n <Ip>74.125.45.100</Ip>\n <Status>OK</Status>\n <CountryCode>US</CountryCode>\n <CountryName>United States</CountryName>\n <RegionCode>06</RegionCode>\n <RegionName>California</RegionName>\n <City>Mountain View</City>\n <ZipPostalCode>94043</ZipPostalCode>\n <Latitude>37.4192</Latitude>\n <Longitude>-122.057</Longitude>\n <TimezoneName>America/Los_Angeles</TimezoneName>\n <Gmtoffset>-25200</Gmtoffset>\n <Isdst>1</Isdst>\n</Response>'''\n\ndoc=xee.fromstring(contents)\nprint dict(((elt.tag,elt.text) for elt in doc))\n\nOr using lxml:\nimport lxml.etree\nimport urllib2\nurl='http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true'\ndoc = lxml.etree.parse( urllib2.urlopen(url) ).getroot()\nprint dict(((elt.tag,elt.text) for elt in doc))\n\n",
"I would use the xml.dom builtin, something like this:\nimport urllib\nfrom xml.dom import minidom\n\ndata = urllib.urlopen('http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true')\nxml_data = minidom.parse(data)\nmy_dict ={}\nfor node in xml_data.getElementsByTagName('Response')[0].childNodes:\n if node.nodeType != minidom.Node.TEXT_NODE:\n my_dict[node.nodeName] = node.childNodes[0].data\n\n",
"xml.etree from standard library starting from python2.5. look also at lxml which has the same interface. I don't \"dived in\" to much but i think that this is also applicable to python >= 2.5 too.\nEdit:\nThis is a fast and really easy way to parse xml, don't really put data to a dict but the api is pretty intuitive.\n"
] |
[
8,
2,
0
] |
[] |
[] |
[
"dictionary",
"python",
"xml",
"xml_parsing"
] |
stackoverflow_0002575672_dictionary_python_xml_xml_parsing.txt
|
Q:
Searching for specific HTML string using Python
What modules would be the best to write a python program that searches through hundreds of html documents and deletes a certain string of html that is given.
For instance, if I have an html doc that has <a href="test.html">Test</a> and I want to delete this out of every html page that has it.
Any help is much appreciated, and I don't need someone to write the program for me, just a helpful point in the right direction.
A:
If the string you are searching for will be in the HTML literally, then simple string replacement will be fine:
old_html = open(html_file).read()
new_html = old_html.replace(my_string, "")
if new_html != old_html:
open(html_file, "w").write(new_html)
As an example of the string not being in the HTML literally, suppose you are looking for "Test" as you said. Do you want it to match these snippets of HTML?:
<a href='test.html'>Test</a>
<A HREF='test.html'>Test</A>
<a href="test.html" class="external">Test</a>
<a href="test.html">Test</a>
and so on: the "same" HTML can be expressed in many different ways. If you know the precise characters used in the HTML, then simple string replacement is fine. If you need to match at an HTML semantic level, then you'll need to use more advanced tools like BeautifulSoup, but then you'll also have potentially very different HTML output than you started with, even in the sections not affected by the deletion, because the entire file will have been parsed and reconstituted.
To execute code over many files, you'll find os.path.walk useful for finding files in a tree, or glob.glob for matching filenames to shell-like wildcard patterns.
A:
BeautifulSoup or lxml.
A:
htmllib
This module defines a class which can serve as a base for parsing text
files formatted in the HyperText Mark-up Language (HTML). The class is
not directly concerned with I/O — it must be provided with input in
string form via a method, and makes calls to methods of a “formatter”
object in order to produce output. The HTMLParser class is designed to
be used as a base class for other classes in order to add
functionality, and allows most of its methods to be extended or
overridden. In turn, this class is derived from and extends the
SGMLParser class defined in module sgmllib. The HTMLParser
implementation supports the HTML 2.0 language as described in RFC
1866.
|
Searching for specific HTML string using Python
|
What modules would be the best to write a python program that searches through hundreds of html documents and deletes a certain string of html that is given.
For instance, if I have an html doc that has <a href="test.html">Test</a> and I want to delete this out of every html page that has it.
Any help is much appreciated, and I don't need someone to write the program for me, just a helpful point in the right direction.
|
[
"If the string you are searching for will be in the HTML literally, then simple string replacement will be fine:\nold_html = open(html_file).read()\nnew_html = old_html.replace(my_string, \"\")\nif new_html != old_html:\n open(html_file, \"w\").write(new_html)\n\nAs an example of the string not being in the HTML literally, suppose you are looking for \"Test\" as you said. Do you want it to match these snippets of HTML?:\n<a href='test.html'>Test</a>\n<A HREF='test.html'>Test</A>\n<a href=\"test.html\" class=\"external\">Test</a>\n<a href=\"test.html\">Test</a>\n\nand so on: the \"same\" HTML can be expressed in many different ways. If you know the precise characters used in the HTML, then simple string replacement is fine. If you need to match at an HTML semantic level, then you'll need to use more advanced tools like BeautifulSoup, but then you'll also have potentially very different HTML output than you started with, even in the sections not affected by the deletion, because the entire file will have been parsed and reconstituted.\nTo execute code over many files, you'll find os.path.walk useful for finding files in a tree, or glob.glob for matching filenames to shell-like wildcard patterns.\n",
"BeautifulSoup or lxml.\n",
"htmllib\n\nThis module defines a class which can serve as a base for parsing text\n files formatted in the HyperText Mark-up Language (HTML). The class is\n not directly concerned with I/O — it must be provided with input in\n string form via a method, and makes calls to methods of a “formatter”\n object in order to produce output. The HTMLParser class is designed to\n be used as a base class for other classes in order to add\n functionality, and allows most of its methods to be extended or\n overridden. In turn, this class is derived from and extends the\n SGMLParser class defined in module sgmllib. The HTMLParser\n implementation supports the HTML 2.0 language as described in RFC\n 1866.\n\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"html",
"python"
] |
stackoverflow_0002575872_html_python.txt
|
Q:
How can I include custom modules in a Django app
I'm really new to Python and Django. I created a class in Python that I would like to use in a Django application. It doesn't seem like it belongs in it's own application, how can I include it in my django app?
Thank you!
A:
Put it in a module somewhere and import it.
|
How can I include custom modules in a Django app
|
I'm really new to Python and Django. I created a class in Python that I would like to use in a Django application. It doesn't seem like it belongs in it's own application, how can I include it in my django app?
Thank you!
|
[
"Put it in a module somewhere and import it.\n"
] |
[
8
] |
[] |
[] |
[
"django",
"module",
"python"
] |
stackoverflow_0002576060_django_module_python.txt
|
Q:
How do I delete a curse window in python and restore background window?
I'm working on python curses and I have an initial window with initscr(). Then I create several new windows to overlap it, I want to know if I can delete these windows and restore the standard screen without having to refill it. Is there a way? Could someone tell me the difference between a window, subwindow, pad and sub pad.
I have this code:
stdscr = curses.initscr()
####Then I fill it with random letters
stdscr.refresh()
newwin=curses.newwin(10,20,5,5)
newwin.touchwin()
newwin.refresh()
####I want to delete newwin here so that if I write stdscr.refresh() newwin won't appear
stdscr.touchwin()
stdscr.refresh()
####And here it should appear as if no window was created.
A:
This, e.g, should work:
import curses
def fillwin(w, c):
y, x = w.getmaxyx()
s = c * (x - 1)
for l in range(y):
w.addstr(l, 0, s)
def main(stdscr):
fillwin(stdscr, 'S')
stdscr.refresh()
stdscr.getch()
newwin=curses.newwin(10,20,5,5)
fillwin(newwin, 'w')
newwin.touchwin()
newwin.refresh()
newwin.getch()
del newwin
stdscr.touchwin()
stdscr.refresh()
stdscr.getch()
curses.wrapper(main)
This fills the terminal with 'S'; at any keystoke, it fills the window with 'w'; at the next keystroke, it removes the window and show the stdscr again, so it's again all-'S'; at the next keystroke, the script ends and the terminal goes back to normal. Isn't this working for you? Or do you actually want something different...?
|
How do I delete a curse window in python and restore background window?
|
I'm working on python curses and I have an initial window with initscr(). Then I create several new windows to overlap it, I want to know if I can delete these windows and restore the standard screen without having to refill it. Is there a way? Could someone tell me the difference between a window, subwindow, pad and sub pad.
I have this code:
stdscr = curses.initscr()
####Then I fill it with random letters
stdscr.refresh()
newwin=curses.newwin(10,20,5,5)
newwin.touchwin()
newwin.refresh()
####I want to delete newwin here so that if I write stdscr.refresh() newwin won't appear
stdscr.touchwin()
stdscr.refresh()
####And here it should appear as if no window was created.
|
[
"This, e.g, should work:\nimport curses\n\ndef fillwin(w, c):\n y, x = w.getmaxyx()\n s = c * (x - 1)\n for l in range(y):\n w.addstr(l, 0, s)\n\ndef main(stdscr):\n fillwin(stdscr, 'S')\n stdscr.refresh()\n stdscr.getch()\n\n newwin=curses.newwin(10,20,5,5)\n fillwin(newwin, 'w')\n newwin.touchwin()\n newwin.refresh()\n newwin.getch()\n del newwin\n\n stdscr.touchwin()\n stdscr.refresh()\n stdscr.getch()\n\ncurses.wrapper(main)\n\nThis fills the terminal with 'S'; at any keystoke, it fills the window with 'w'; at the next keystroke, it removes the window and show the stdscr again, so it's again all-'S'; at the next keystroke, the script ends and the terminal goes back to normal. Isn't this working for you? Or do you actually want something different...?\n"
] |
[
10
] |
[] |
[] |
[
"curses",
"python",
"window"
] |
stackoverflow_0002575409_curses_python_window.txt
|
Q:
Beginner problems with references to arrays in python 3.1.1
As part of the last assignment in a beginner python programing class, I have been assigned a traveling sales man problem. I settled on a recursive function to find each permutation and the sum of the distances between the destinations, however, I am have a lot of problems with references. Arrays in different instances of the Permute and Main functions of TSP seem to be pointing to the same reference.
from math import sqrt
class TSP:
def __init__(self):
self.CartisianCoordinates = [['A',[1,1]], ['B',[2,2]], ['C',[2,1]], ['D',[1,2]], ['E',[3,3]]]
self.Array = []
self.Max = 0
self.StoredList = ['',0]
def Distance(self, i1, i2):
x1 = self.CartisianCoordinates[i1][1][0]
y1 = self.CartisianCoordinates[i1][1][1]
x2 = self.CartisianCoordinates[i2][1][0]
y2 = self.CartisianCoordinates[i2][1][1]
return sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2))
def Evaluate(self):
temparray = []
Data = []
for i in range(len(self.CartisianCoordinates)):
Data.append([])
for i1 in range(len(self.CartisianCoordinates)):
for i2 in range(len(self.CartisianCoordinates)):
if i1 != i2:
temparray.append(self.Distance(i1, i2))
else:
temparray.append('X')
Data[i1] = temparray
temparray = []
self.Array = Data
self.Max = len(Data)
def Permute(self,varray,index,vcarry,mcarry): #Problem Class
array = varray[:]
carry = vcarry[:]
for i in range(self.Max):
print ('ARRAY:', array)
print (index,i,carry,array[index][i])
if array[index][i] != 'X':
carry[0] += self.CartisianCoordinates[i][0]
carry[1] += array[index][i]
if len(carry) != self.Max:
temparray = array[:]
for j in range(self.Max):temparray[j][i] = 'X'
index = i
mcarry += self.Permute(temparray,index,carry,mcarry)
else:
return mcarry
print ('pass',mcarry)
return mcarry
def Main(self):
out = []
self.Evaluate()
for i in range(self.Max):
array = self.Array[:] #array appears to maintain the same reference after each copy, resulting in an incorrect array being passed to Permute after the first iteration.
print (self.Array[:])
for j in range(self.Max):array[j][i] = 'X'
print('I:', i, array)
out.append(self.Permute(array,i,[str(self.CartisianCoordinates[i][0]),0],[]))
return out
SalesPerson = TSP()
print(SalesPerson.Main())
It would be greatly appreciated if you could provide me with help in solving the reference problems I am having. Thank you.
A:
Slicing a list (by using [:] as you do) does not create a deep copy -- it creates a shallow copy. That means that if the list contains references to other lists, the copy will contain the same references -- not references to new lists. Put another way, only the list itself is copied, not its elements or its elements' elements.
What you want here is a deep copy. Instead of
array = self.Array[:]
try
array = copy.deepcopy(self.Array)
for which you'll need import copy.
|
Beginner problems with references to arrays in python 3.1.1
|
As part of the last assignment in a beginner python programing class, I have been assigned a traveling sales man problem. I settled on a recursive function to find each permutation and the sum of the distances between the destinations, however, I am have a lot of problems with references. Arrays in different instances of the Permute and Main functions of TSP seem to be pointing to the same reference.
from math import sqrt
class TSP:
def __init__(self):
self.CartisianCoordinates = [['A',[1,1]], ['B',[2,2]], ['C',[2,1]], ['D',[1,2]], ['E',[3,3]]]
self.Array = []
self.Max = 0
self.StoredList = ['',0]
def Distance(self, i1, i2):
x1 = self.CartisianCoordinates[i1][1][0]
y1 = self.CartisianCoordinates[i1][1][1]
x2 = self.CartisianCoordinates[i2][1][0]
y2 = self.CartisianCoordinates[i2][1][1]
return sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2))
def Evaluate(self):
temparray = []
Data = []
for i in range(len(self.CartisianCoordinates)):
Data.append([])
for i1 in range(len(self.CartisianCoordinates)):
for i2 in range(len(self.CartisianCoordinates)):
if i1 != i2:
temparray.append(self.Distance(i1, i2))
else:
temparray.append('X')
Data[i1] = temparray
temparray = []
self.Array = Data
self.Max = len(Data)
def Permute(self,varray,index,vcarry,mcarry): #Problem Class
array = varray[:]
carry = vcarry[:]
for i in range(self.Max):
print ('ARRAY:', array)
print (index,i,carry,array[index][i])
if array[index][i] != 'X':
carry[0] += self.CartisianCoordinates[i][0]
carry[1] += array[index][i]
if len(carry) != self.Max:
temparray = array[:]
for j in range(self.Max):temparray[j][i] = 'X'
index = i
mcarry += self.Permute(temparray,index,carry,mcarry)
else:
return mcarry
print ('pass',mcarry)
return mcarry
def Main(self):
out = []
self.Evaluate()
for i in range(self.Max):
array = self.Array[:] #array appears to maintain the same reference after each copy, resulting in an incorrect array being passed to Permute after the first iteration.
print (self.Array[:])
for j in range(self.Max):array[j][i] = 'X'
print('I:', i, array)
out.append(self.Permute(array,i,[str(self.CartisianCoordinates[i][0]),0],[]))
return out
SalesPerson = TSP()
print(SalesPerson.Main())
It would be greatly appreciated if you could provide me with help in solving the reference problems I am having. Thank you.
|
[
"Slicing a list (by using [:] as you do) does not create a deep copy -- it creates a shallow copy. That means that if the list contains references to other lists, the copy will contain the same references -- not references to new lists. Put another way, only the list itself is copied, not its elements or its elements' elements.\nWhat you want here is a deep copy. Instead of\narray = self.Array[:]\n\ntry\narray = copy.deepcopy(self.Array)\n\nfor which you'll need import copy.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002575952_python.txt
|
Q:
strange behavior in python
The tags might not be accurate since I am not sure where the problem is.
I have a module where I am trying to read some data from a socket, and write the results into a file (append) It looks something like this, (only relevant parts included)
if __name__ == "__main__":
<some init code>
for line in file:
t = Thread(target=foo, args=(line,))
t.start()
while nThreads > 0:
time.sleep(1)
Here are the other modules,
def foo(text):
global countLock, nThreads
countLock.acquire()
nThreads += 1
countLock.release()
"""connect to socket, send data, read response"""
writeResults(text, result)
countLock.acquire()
nThreads -= 1
countLock.release()
def writeResults(text, result):
"""acquire file lock"""
"""append to file"""
"""release file lock"""
Now here's the problem. Initially, I had a typo in the function 'foo', where I was passing the variable 'line' to writeResults instead of 'text'. 'line' is not defined in the function foo, it's defined in the main block, so I should have seen an error, but instead, it worked fine, except that the data was appended to the file multiple times, instead of being written just once, which is the required behavior, which I got when I fixed the typo.
My question is,
1) Why didn't I get an error?
2) Why was the writeResults function being called multiple times?
A:
You really ought to use Thread.join() for your main loop to wait for a thread to finish:
if __name__ == "__main__":
<some init code>
threads = []
for line in file:
t = Thread(target=foo, args=(line,))
t.start()
threads.append(t)
for t in threads:
t.join()
and get rid of the nThreads global and countLock.
As for your questions, I don't know why you didn't get an error (maybe the exception got eaten by something?), and I wonder if the number of repetitions of writeResults correlated with the number of lines in the file. If it did, I would have to wonder if line is a global and each thread wrote it once.
A:
When you had (simplifying to the important part)
def foo(text):
writeResults(line, result)
foo, not having a local variable line, was using the global variable by that name... which happens to be the one set (in the main thread) by for line in file:.
Specifically, I would expect the total number of lines written to be OK: there's one thread per line (a weird architecture, BTW) and each thread writes one line... the only issue is, which line each thread writes.
In your intention, the first thread writes the first line, the second thread writes the second line, etc; but in reality each thread will write the line that happens to be bound to the global line name at the crucial moment when the thread calls writeResults. So, some lines may well end up written multiple times, others, not written.
For example, suppose the main thread ran faster by enough to start all subthreads before any of them actually gets to writing. In that case, the last value taken by the global name line (i.e., the last line in the file) would be the one written by all of the threads.
Note that even in the "corrected" version there is no guarantee about the order in which the various lines get written, which is part of what makes this architecture weird -- normally, since lines come in a certain order, you'd want to preserve that order on output. I guess your application case is peculiar enough to not need that constraint, but I'm still puzzled that you need so many threads when you're reading from one file and writing to one file!-)
A:
To avoid the global variable called line, you should write a function called main that does the job. Then the variable is local to the main function.
Make your program look like this:
def main(args):
# ... init ...
for line in file:
# ... process the line
pass
if __name__ == "__main__":
main(sys.argv[1:])
|
strange behavior in python
|
The tags might not be accurate since I am not sure where the problem is.
I have a module where I am trying to read some data from a socket, and write the results into a file (append) It looks something like this, (only relevant parts included)
if __name__ == "__main__":
<some init code>
for line in file:
t = Thread(target=foo, args=(line,))
t.start()
while nThreads > 0:
time.sleep(1)
Here are the other modules,
def foo(text):
global countLock, nThreads
countLock.acquire()
nThreads += 1
countLock.release()
"""connect to socket, send data, read response"""
writeResults(text, result)
countLock.acquire()
nThreads -= 1
countLock.release()
def writeResults(text, result):
"""acquire file lock"""
"""append to file"""
"""release file lock"""
Now here's the problem. Initially, I had a typo in the function 'foo', where I was passing the variable 'line' to writeResults instead of 'text'. 'line' is not defined in the function foo, it's defined in the main block, so I should have seen an error, but instead, it worked fine, except that the data was appended to the file multiple times, instead of being written just once, which is the required behavior, which I got when I fixed the typo.
My question is,
1) Why didn't I get an error?
2) Why was the writeResults function being called multiple times?
|
[
"You really ought to use Thread.join() for your main loop to wait for a thread to finish:\nif __name__ == \"__main__\":\n <some init code>\n threads = []\n for line in file:\n t = Thread(target=foo, args=(line,))\n t.start()\n threads.append(t)\n for t in threads:\n t.join()\n\nand get rid of the nThreads global and countLock.\nAs for your questions, I don't know why you didn't get an error (maybe the exception got eaten by something?), and I wonder if the number of repetitions of writeResults correlated with the number of lines in the file. If it did, I would have to wonder if line is a global and each thread wrote it once.\n",
"When you had (simplifying to the important part)\ndef foo(text):\n writeResults(line, result)\n\nfoo, not having a local variable line, was using the global variable by that name... which happens to be the one set (in the main thread) by for line in file:.\nSpecifically, I would expect the total number of lines written to be OK: there's one thread per line (a weird architecture, BTW) and each thread writes one line... the only issue is, which line each thread writes.\nIn your intention, the first thread writes the first line, the second thread writes the second line, etc; but in reality each thread will write the line that happens to be bound to the global line name at the crucial moment when the thread calls writeResults. So, some lines may well end up written multiple times, others, not written.\nFor example, suppose the main thread ran faster by enough to start all subthreads before any of them actually gets to writing. In that case, the last value taken by the global name line (i.e., the last line in the file) would be the one written by all of the threads.\nNote that even in the \"corrected\" version there is no guarantee about the order in which the various lines get written, which is part of what makes this architecture weird -- normally, since lines come in a certain order, you'd want to preserve that order on output. I guess your application case is peculiar enough to not need that constraint, but I'm still puzzled that you need so many threads when you're reading from one file and writing to one file!-)\n",
"To avoid the global variable called line, you should write a function called main that does the job. Then the variable is local to the main function.\nMake your program look like this:\ndef main(args):\n # ... init ...\n for line in file:\n # ... process the line\n pass\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n"
] |
[
1,
1,
1
] |
[] |
[] |
[
"multithreading",
"namespaces",
"python"
] |
stackoverflow_0002575847_multithreading_namespaces_python.txt
|
Q:
Do alternate python implementation version numbers imply that they provide the same syntax?
for example Jython is at version 2.5.1, does that imply a parallel fidelity to cpython syntax when it was at version 2.5.1?
A:
Generally yes, but there's technically nothing stopping alternate implementations from choosing whatever version numbers they want.
It's also important to note that just because Jython 2.5.1 is intended to match CPython 2.5.1, doesn't mean that they're going to behave exactly the same or be entirely compatible -- consider C-based modules, for example, and facilities for getting at the underlying bytecode.
The lack of any real standards body or formal specification for the Python language means that there are no clear rules on what constitutes "Python" and what is "implementation defined".
A:
That is correct, or very close. Jython and IronPython have changed their numbering scheme to match the CPython version whose features they most closely implement.
A:
The syntax (and feature set) are controlled strictly by the first two numbers -- every 2.5.* is claiming to implement the same syntax and feature set (in terms of language definition, not of aspects the language-reference manual explicitly leaves up to the implementation: for example, both Jython and IronPython have 'buh' mean "a unicode string literal", while CPython has it mean "a byte string literal"). A higher *, within any line of implementation, implies bug fixes and/or optimizations which don't affect syntax and features (except for fixing implementation bugs that had happened at some lower *, if any).
So, Jython 2.5.1 may be substituted for any CPython 2.5.x for any value of x -- and it claims to be better than Jython 2.5 (IMHO shd be 2.5.0 but the trailing .0 is not used in practice), though not as good as Jython 2.5.2 if the latter exist. But it does not purport to emulate the bugs in CPython 2.5.1 that were fixed in CPython 2.5.2 or later: no doubt each implementation has its own bugs, and nobody claims bug-for-bug compatibility;-).
|
Do alternate python implementation version numbers imply that they provide the same syntax?
|
for example Jython is at version 2.5.1, does that imply a parallel fidelity to cpython syntax when it was at version 2.5.1?
|
[
"Generally yes, but there's technically nothing stopping alternate implementations from choosing whatever version numbers they want.\nIt's also important to note that just because Jython 2.5.1 is intended to match CPython 2.5.1, doesn't mean that they're going to behave exactly the same or be entirely compatible -- consider C-based modules, for example, and facilities for getting at the underlying bytecode.\nThe lack of any real standards body or formal specification for the Python language means that there are no clear rules on what constitutes \"Python\" and what is \"implementation defined\".\n",
"That is correct, or very close. Jython and IronPython have changed their numbering scheme to match the CPython version whose features they most closely implement.\n",
"The syntax (and feature set) are controlled strictly by the first two numbers -- every 2.5.* is claiming to implement the same syntax and feature set (in terms of language definition, not of aspects the language-reference manual explicitly leaves up to the implementation: for example, both Jython and IronPython have 'buh' mean \"a unicode string literal\", while CPython has it mean \"a byte string literal\"). A higher *, within any line of implementation, implies bug fixes and/or optimizations which don't affect syntax and features (except for fixing implementation bugs that had happened at some lower *, if any).\nSo, Jython 2.5.1 may be substituted for any CPython 2.5.x for any value of x -- and it claims to be better than Jython 2.5 (IMHO shd be 2.5.0 but the trailing .0 is not used in practice), though not as good as Jython 2.5.2 if the latter exist. But it does not purport to emulate the bugs in CPython 2.5.1 that were fixed in CPython 2.5.2 or later: no doubt each implementation has its own bugs, and nobody claims bug-for-bug compatibility;-).\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002576320_python.txt
|
Q:
Does python's httplib.HTTPConnection block?
I am unsure whether or not the following code is a blocking operation in python:
import httplib
import urllib
def do_request(server, port, timeout, remote_url):
conn = httplib.HTTPConnection(server, port, timeout=timeout)
conn.request("POST", remote_url, urllib.urlencode(query_dictionary, True))
conn.close()
return True
do_request("http://www.example.org", 80, 30, "foo/bar")
print "hi!"
And if it is, how would one go about creating a non-blocking asynchronous http request in python?
Thanks from a python noob.
A:
Unless you go to lengths to prevent it, IO will always block.
Although you can do asynchronous requests, you will have to make you entire program async-friendly. Async does not magically make your code non-blocking. It would be much easier to do the request in another thread or process if you don't want to block your main loop.
If you're interested in asynchronous network programming, you will want to look into Twisted.
|
Does python's httplib.HTTPConnection block?
|
I am unsure whether or not the following code is a blocking operation in python:
import httplib
import urllib
def do_request(server, port, timeout, remote_url):
conn = httplib.HTTPConnection(server, port, timeout=timeout)
conn.request("POST", remote_url, urllib.urlencode(query_dictionary, True))
conn.close()
return True
do_request("http://www.example.org", 80, 30, "foo/bar")
print "hi!"
And if it is, how would one go about creating a non-blocking asynchronous http request in python?
Thanks from a python noob.
|
[
"Unless you go to lengths to prevent it, IO will always block.\nAlthough you can do asynchronous requests, you will have to make you entire program async-friendly. Async does not magically make your code non-blocking. It would be much easier to do the request in another thread or process if you don't want to block your main loop.\nIf you're interested in asynchronous network programming, you will want to look into Twisted.\n"
] |
[
6
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002576534_python.txt
|
Q:
Start PyGTK cellrenderer edit from code
I have a treeview with an editable CellRendererText:
self.renderer = gtk.CellRendererText()
self.renderer.set_property('editable', True)
But now I need to launch the edition from code instead from user, this is to focus the user attention in the fact he just created a new row and needs to be named. I tried this but does not work:
self.renderer.start_editing(
gtk.gdk.Event(gtk.gdk.NOTHING),
self.treeview,
str(index),
gtk.gdk.Rectangle(),
gtk.gdk.Rectangle(),
0)
Neither does not throw errors, but the documentation about for what is each argument is not clear, in fact I really don't know if start_editing method is for this.
All suggestions are welcome, thanks.
A:
def set_cursor(path, focus_column=None, start_editing=False)
... If column is specified, and start_editing is True, then editing should be started in the specified cell. This method is often followed by the gtk.Widget.grab_focus() method to give keyboard focus to the treeview.
Source
|
Start PyGTK cellrenderer edit from code
|
I have a treeview with an editable CellRendererText:
self.renderer = gtk.CellRendererText()
self.renderer.set_property('editable', True)
But now I need to launch the edition from code instead from user, this is to focus the user attention in the fact he just created a new row and needs to be named. I tried this but does not work:
self.renderer.start_editing(
gtk.gdk.Event(gtk.gdk.NOTHING),
self.treeview,
str(index),
gtk.gdk.Rectangle(),
gtk.gdk.Rectangle(),
0)
Neither does not throw errors, but the documentation about for what is each argument is not clear, in fact I really don't know if start_editing method is for this.
All suggestions are welcome, thanks.
|
[
"\ndef set_cursor(path, focus_column=None, start_editing=False)\n\n... If column is specified, and start_editing is True, then editing should be started in the specified cell. This method is often followed by the gtk.Widget.grab_focus() method to give keyboard focus to the treeview.\n\nSource\n"
] |
[
6
] |
[] |
[] |
[
"gnome",
"gtk",
"pygtk",
"python",
"user_interface"
] |
stackoverflow_0002576481_gnome_gtk_pygtk_python_user_interface.txt
|
Q:
wxWidgets/wxPython: Do two identical events cause two handlings?
When there are two identical events in the event loop, will wxPython handle both of them, or will it call the handler only once for them both?
I mean, in my widget I want to have an event like EVT_NEED_TO_RECALCULATE_X. I want this event to be posted in all kinds of different circumstances that require x to be recalculated. However, even if there are two different reasons to recalculate x, only one recalculation needs to be done.
How do I do this?
EDIT:
I tried this code:
import wx
class Frame(wx.Frame):
def __init__(self, parent=None):
wx.Frame.__init__(self, parent)
self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_event)
self.Centre()
self.Show(True)
self.i = 0
self.event_all()
def on_event(self, event):
print self.i
self.i += 1
def event_all(self):
for j in range(1000):
event = wx.PyEvent()
event.SetEventType(wx.EVT_COLOURPICKER_CHANGED.evtType[0])
wx.PostEvent(self, event)
app = wx.App()
Frame(None)
app.MainLoop()
If the events do get grouped together, I'd expect it not to count all the way to 1000. But it does. Do they get grouped or not?
A:
you're talking about three things
the event
the source of the event
the event handling
The event is a single one (X needs to be recalculated). It has multiple sources. But it has only a single handler.
So it should just work. You make it a single event, add a single handler to it, but signal/raise the event whenever you want - every time you raise the need X recalculated flag, the handler should run one time.
EDIT:
This line...
event = wx.PyEvent()
...creates a new event. That means something happened, and must be reacted upon.
If you create 1000 events, then sure, the event handler will be called 1000 times.
The handler will be called once for each time the event happens, that is, once for each PyEvent instance that gets posted on the event queue.
If you want to group them, one way is to not create a new PyEvent instance if one is pending:
class Frame(wx.Frame):
def __init__(self, parent=None):
wx.Frame.__init__(self, parent)
self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_event)
self.Centre()
self.Show(True)
self.i = 0
self.recalculating = False
self.event_all()
def on_event(self, event):
self.recalculating = False
print self.i
self.i += 1
def event_all(self):
for j in range(1000):
if not self.recalculating:
event = wx.PyEvent()
event.SetEventType(wx.EVT_COLOURPICKER_CHANGED.evtType[0])
wx.PostEvent(self, event)
self.recalculating = True
A:
If you will post a event 1000 times you will receive it 1000 times, why would any event system group them, that would be a bug.
If you do not want to deal with all 1000 of them ignore them, also only you can decide how they should be grouped, if user changes something rapidly do you want to group those changes or respond to all events and have a better responsive UI?
In you case may be you should either
group them with time e.g. handle events which come N msec apart
Group the with value e.g. if last value is same as current value do nothing
Set a flag is a object has been modified, you get event, you do something and reset flag, so next time on event check flag is something really has changed or not
But the bottom line is You have to decide how you respond to events.
|
wxWidgets/wxPython: Do two identical events cause two handlings?
|
When there are two identical events in the event loop, will wxPython handle both of them, or will it call the handler only once for them both?
I mean, in my widget I want to have an event like EVT_NEED_TO_RECALCULATE_X. I want this event to be posted in all kinds of different circumstances that require x to be recalculated. However, even if there are two different reasons to recalculate x, only one recalculation needs to be done.
How do I do this?
EDIT:
I tried this code:
import wx
class Frame(wx.Frame):
def __init__(self, parent=None):
wx.Frame.__init__(self, parent)
self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_event)
self.Centre()
self.Show(True)
self.i = 0
self.event_all()
def on_event(self, event):
print self.i
self.i += 1
def event_all(self):
for j in range(1000):
event = wx.PyEvent()
event.SetEventType(wx.EVT_COLOURPICKER_CHANGED.evtType[0])
wx.PostEvent(self, event)
app = wx.App()
Frame(None)
app.MainLoop()
If the events do get grouped together, I'd expect it not to count all the way to 1000. But it does. Do they get grouped or not?
|
[
"you're talking about three things\n\nthe event\nthe source of the event\nthe event handling\n\nThe event is a single one (X needs to be recalculated). It has multiple sources. But it has only a single handler.\nSo it should just work. You make it a single event, add a single handler to it, but signal/raise the event whenever you want - every time you raise the need X recalculated flag, the handler should run one time.\n\nEDIT:\nThis line...\nevent = wx.PyEvent()\n\n...creates a new event. That means something happened, and must be reacted upon.\nIf you create 1000 events, then sure, the event handler will be called 1000 times.\nThe handler will be called once for each time the event happens, that is, once for each PyEvent instance that gets posted on the event queue.\nIf you want to group them, one way is to not create a new PyEvent instance if one is pending:\nclass Frame(wx.Frame):\n def __init__(self, parent=None):\n wx.Frame.__init__(self, parent)\n self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_event)\n self.Centre()\n self.Show(True)\n self.i = 0\n self.recalculating = False\n self.event_all()\n\n def on_event(self, event):\n self.recalculating = False\n print self.i\n self.i += 1\n\n def event_all(self):\n for j in range(1000):\n if not self.recalculating:\n event = wx.PyEvent()\n event.SetEventType(wx.EVT_COLOURPICKER_CHANGED.evtType[0])\n wx.PostEvent(self, event)\n self.recalculating = True\n\n",
"If you will post a event 1000 times you will receive it 1000 times, why would any event system group them, that would be a bug.\nIf you do not want to deal with all 1000 of them ignore them, also only you can decide how they should be grouped, if user changes something rapidly do you want to group those changes or respond to all events and have a better responsive UI?\nIn you case may be you should either\n\ngroup them with time e.g. handle events which come N msec apart\nGroup the with value e.g. if last value is same as current value do nothing\nSet a flag is a object has been modified, you get event, you do something and reset flag, so next time on event check flag is something really has changed or not\n\nBut the bottom line is You have to decide how you respond to events.\n"
] |
[
0,
0
] |
[] |
[] |
[
"events",
"python",
"wxpython",
"wxwidgets"
] |
stackoverflow_0002574830_events_python_wxpython_wxwidgets.txt
|
Q:
Python: How to display the calculated MD5 value in my browser?
I was given this Python code that would calculate an MD5 value for any phrase:
import md5
md5.new("Nobody inspects the spammish repetition").digest()
(The phrase here is: "Nobody inspects the spammish repetition")
What I want to do is display this value in my browser. How do I do it in Python?
I tried all these variants, none of them worked:
import md5
show = md5.new("Nobody inspects the spammish repetition").digest()
print show
import md5
print md5.new("Nobody inspects the spammish repetition").digest()
import md5
md5.new("Nobody inspects the spammish repetition").digest()
print md5
import md5
md5.new("Nobody inspects the spammish repetition").digest()
print md5.new
update A:
By now (Monday, 5 April 2010, 07:19:35 GMT) I have received two answers from Ignacio Vazquez-Abrams and from Ji. Both have suggested pretty much the same thing. I have tried Ji's code, but it didn't work. Here is the screen shot of the error lines I received:
(source: narod.ru)
(I believe you need to right click on the image and choose "View the Image" to see it in a bigger size)
A:
In order to display the hexdigest in your browser you need to have some sort of web framework (in this case in python) that handles all the web serving for you.
Here's an example using web.py (I've copied the default example and adjusted for the md5). But you can use any other framework out there
import web
from md5 import md5
urls = (
'/(.*)', 'digest'
)
app = web.application(urls, globals())
class digest:
def GET(self):
return md5("Nobody inspects the spammish repetition").hexdigest()
if __name__ == "__main__":
app.run()
A:
.hexdigest() is what you want.
|
Python: How to display the calculated MD5 value in my browser?
|
I was given this Python code that would calculate an MD5 value for any phrase:
import md5
md5.new("Nobody inspects the spammish repetition").digest()
(The phrase here is: "Nobody inspects the spammish repetition")
What I want to do is display this value in my browser. How do I do it in Python?
I tried all these variants, none of them worked:
import md5
show = md5.new("Nobody inspects the spammish repetition").digest()
print show
import md5
print md5.new("Nobody inspects the spammish repetition").digest()
import md5
md5.new("Nobody inspects the spammish repetition").digest()
print md5
import md5
md5.new("Nobody inspects the spammish repetition").digest()
print md5.new
update A:
By now (Monday, 5 April 2010, 07:19:35 GMT) I have received two answers from Ignacio Vazquez-Abrams and from Ji. Both have suggested pretty much the same thing. I have tried Ji's code, but it didn't work. Here is the screen shot of the error lines I received:
(source: narod.ru)
(I believe you need to right click on the image and choose "View the Image" to see it in a bigger size)
|
[
"In order to display the hexdigest in your browser you need to have some sort of web framework (in this case in python) that handles all the web serving for you.\nHere's an example using web.py (I've copied the default example and adjusted for the md5). But you can use any other framework out there\nimport web\nfrom md5 import md5\n\nurls = (\n '/(.*)', 'digest' \n)\n\napp = web.application(urls, globals())\n\nclass digest: \n def GET(self):\n return md5(\"Nobody inspects the spammish repetition\").hexdigest()\n\nif __name__ == \"__main__\":\n app.run()\n\n",
".hexdigest() is what you want.\n"
] |
[
4,
3
] |
[] |
[] |
[
"google_app_engine",
"md5",
"python"
] |
stackoverflow_0002577041_google_app_engine_md5_python.txt
|
Q:
ImportError and Django driving me crazy
OK, I have the following directory structure (it's a django project):
-> project
--> app
and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py
I'm trying to do the following:
import urllib2
import os
import sys
import time
import datetime
import re
import BeautifulSoup
sys.path.append('/home/userspace/Development/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from project.app.models import ClassName
and this code just isn't working. I get an error of:
Traceback (most recent call last):
File "scraper.py", line 14, in
from project.app.models import ClassName
ImportError: No module named project.app.models
This code above used to work, but broke somewhere along the line and I'm extremely confused as to why I'm having problems. On SnowLeopard using python2.5.
A:
import sys
sys.path.append ('/path/to/the/project')
from django.core.management import setup_environ
import settings
setup_environ(settings)
from app.models import MyModel
A:
Whoa whoa whoa. You should never ever have to put your project name in any of your app code. You should be able to reuse app code across multiple projects with no changes. Pinax does this really well and I highly recommend checking it out for a lot of django best practices.
The worst thing you could do here is to hard code your absolute path into your app or settings. You shouldn't do this because it will break during deployment unless you do some import local_settings hacking.
If you have to access the project root directory, try what pinax has in settings.py...
import os.path
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
The thing is that it looks like you are trying to access the models module within the same app and this is waaay easier.
To import models.py inside scraper.py in the same directory just use import models or import models as app_models if you already have something named models in scraper.py (django.db.models for instance). Are you familiar with Python module conventions?
However, the best way is probably to stick with the django idiom, from ... import ... statement:
from app import models
If this doesn't work automatically, then something is wrong in your settings.py.
A:
You don't indicate if project is located in /home/userspace/Development/. I'll assume that it is.
Make sure there's an (empty by default) file named __init__.py in project and another one in app.
EDIT: Next thing to try: Fire up the Python command line in the script's directory and try the following:
import project
import project.app as app
import project.app.models as models
models.__dict__.keys()
Do they all work? If so, what is the last line's output? If not, which dies first?
|
ImportError and Django driving me crazy
|
OK, I have the following directory structure (it's a django project):
-> project
--> app
and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py
I'm trying to do the following:
import urllib2
import os
import sys
import time
import datetime
import re
import BeautifulSoup
sys.path.append('/home/userspace/Development/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from project.app.models import ClassName
and this code just isn't working. I get an error of:
Traceback (most recent call last):
File "scraper.py", line 14, in
from project.app.models import ClassName
ImportError: No module named project.app.models
This code above used to work, but broke somewhere along the line and I'm extremely confused as to why I'm having problems. On SnowLeopard using python2.5.
|
[
"import sys\nsys.path.append ('/path/to/the/project')\nfrom django.core.management import setup_environ\nimport settings\nsetup_environ(settings)\n\nfrom app.models import MyModel\n\n",
"Whoa whoa whoa. You should never ever have to put your project name in any of your app code. You should be able to reuse app code across multiple projects with no changes. Pinax does this really well and I highly recommend checking it out for a lot of django best practices.\nThe worst thing you could do here is to hard code your absolute path into your app or settings. You shouldn't do this because it will break during deployment unless you do some import local_settings hacking.\nIf you have to access the project root directory, try what pinax has in settings.py...\nimport os.path\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n\nThe thing is that it looks like you are trying to access the models module within the same app and this is waaay easier.\nTo import models.py inside scraper.py in the same directory just use import models or import models as app_models if you already have something named models in scraper.py (django.db.models for instance). Are you familiar with Python module conventions?\nHowever, the best way is probably to stick with the django idiom, from ... import ... statement:\nfrom app import models\n\nIf this doesn't work automatically, then something is wrong in your settings.py.\n",
"You don't indicate if project is located in /home/userspace/Development/. I'll assume that it is.\nMake sure there's an (empty by default) file named __init__.py in project and another one in app.\nEDIT: Next thing to try: Fire up the Python command line in the script's directory and try the following:\nimport project\nimport project.app as app\nimport project.app.models as models\nmodels.__dict__.keys()\n\nDo they all work? If so, what is the last line's output? If not, which dies first?\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"django",
"django_models",
"importerror",
"python"
] |
stackoverflow_0002575859_django_django_models_importerror_python.txt
|
Q:
Can't get MySQL source query to work using Python mysqldb module
I have the following lines of code:
sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql"
cursor.execute (sql)
When I execute my program, I get the following error:
Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'source C:\My Dropbox\workspace\projects\hosted_inv\create_site_db.sql' at line 1
Now I can copy and past the following into mysql as a query:
source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql
And it works perfect. When I check the query log for the query executed by my script, it shows that my query was the following:
source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql
However, when I manually paste it in and execute, the entire create_site_db.sql gets expanded in the query log and it shows all the sql queries in that file.
Am I missing something here on how mysqldb does queries? Am I running into a limitation. My goal is to run a sql script to create the schema structure, but I don't want to have to call mysql in a shell process to source the sql file.
Any thoughts? Thanks!
A:
As others said, you cannot use the command source in MySQLdb Python API
So, instead of running that, load the file and execute it
Lets say your .sql file has
create database test;
Read the content like
sql=open("test.sql").read()
And then execute it
cursor.execute(sql);
You will get new database "test"
A:
The source command is one of the built-in commands recognized only by the mysql command-line client. It is not supported as a statement you can execute via any API.
Some people think you can simply split an SQL script file on the ";" statement terminator and call execute() on each line you get. But there are numerous exception cases:
Statements that are built-in commands like CONNECT, SOURCE, CHARSET, WARNINGS, QUIT, etc.
Note that built-in commands don't need to terminate in ; for example DELIMITER.
Statements that contain ; but not as a terminator, like CREATE TRIGGER.
Statements that contain ; inside string literals or comments or even quoted identifiers.
Comments lines.
To load an SQL script programmatically, you'd have to duplicate a fair amount of the functionality of the mysql client. So it's best if you just fork a process to actually execute that client program with the script as input.
See also:
Loading .sql files from within PHP
is it possible to call a sql script from a stored procedure in another sql script?
composing multiple mysql scripts
Running Database scripts in C#
A:
'source' is not an SQL command, but an internal command of the mysql command line client.
A:
I ran into the same problem!
As a solution I installed the library sqlparse and used the sqlparse.split( sql ) results. I had to check that sql_parts don't include blank lines as solo statements... Otherwise "WOW" sqlparse is pretty great and exactly what I needed!
import sqlparse
....
sql = open("test.sql").read()
sql_parts = sqlparse.split( sql )
for sql_part in sql_parts:
if sql_part.strip() == '':
continue
cursor.execute( sql_part )
FYI: If you do not run each statement on its own you may get the error "Commands out of sync; you can't run this command now". I only got this error after I added some more queries to my sql file - not the first time around.
A:
I believe the "source" command is specific to the mysql shell executable - it is not an sql command and cannot be interpreted correctly when executed as an sql statement.
To achieve your goal, you probably need to read your script file and parse it into individual sql statements, then execute them one at a time with your cursor.
|
Can't get MySQL source query to work using Python mysqldb module
|
I have the following lines of code:
sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql"
cursor.execute (sql)
When I execute my program, I get the following error:
Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'source C:\My Dropbox\workspace\projects\hosted_inv\create_site_db.sql' at line 1
Now I can copy and past the following into mysql as a query:
source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql
And it works perfect. When I check the query log for the query executed by my script, it shows that my query was the following:
source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql
However, when I manually paste it in and execute, the entire create_site_db.sql gets expanded in the query log and it shows all the sql queries in that file.
Am I missing something here on how mysqldb does queries? Am I running into a limitation. My goal is to run a sql script to create the schema structure, but I don't want to have to call mysql in a shell process to source the sql file.
Any thoughts? Thanks!
|
[
"As others said, you cannot use the command source in MySQLdb Python API\nSo, instead of running that, load the file and execute it\nLets say your .sql file has \ncreate database test;\n\nRead the content like \nsql=open(\"test.sql\").read()\n\nAnd then execute it\ncursor.execute(sql);\n\nYou will get new database \"test\"\n",
"The source command is one of the built-in commands recognized only by the mysql command-line client. It is not supported as a statement you can execute via any API.\nSome people think you can simply split an SQL script file on the \";\" statement terminator and call execute() on each line you get. But there are numerous exception cases:\n\nStatements that are built-in commands like CONNECT, SOURCE, CHARSET, WARNINGS, QUIT, etc.\nNote that built-in commands don't need to terminate in ; for example DELIMITER.\nStatements that contain ; but not as a terminator, like CREATE TRIGGER.\nStatements that contain ; inside string literals or comments or even quoted identifiers.\nComments lines.\n\nTo load an SQL script programmatically, you'd have to duplicate a fair amount of the functionality of the mysql client. So it's best if you just fork a process to actually execute that client program with the script as input.\nSee also:\n\nLoading .sql files from within PHP\nis it possible to call a sql script from a stored procedure in another sql script?\ncomposing multiple mysql scripts\nRunning Database scripts in C# \n\n",
"'source' is not an SQL command, but an internal command of the mysql command line client. \n",
"I ran into the same problem! \nAs a solution I installed the library sqlparse and used the sqlparse.split( sql ) results. I had to check that sql_parts don't include blank lines as solo statements... Otherwise \"WOW\" sqlparse is pretty great and exactly what I needed!\nimport sqlparse \n....\nsql = open(\"test.sql\").read()\nsql_parts = sqlparse.split( sql )\nfor sql_part in sql_parts:\n if sql_part.strip() == '':\n continue \n cursor.execute( sql_part )\n\nFYI: If you do not run each statement on its own you may get the error \"Commands out of sync; you can't run this command now\". I only got this error after I added some more queries to my sql file - not the first time around.\n",
"I believe the \"source\" command is specific to the mysql shell executable - it is not an sql command and cannot be interpreted correctly when executed as an sql statement.\nTo achieve your goal, you probably need to read your script file and parse it into individual sql statements, then execute them one at a time with your cursor. \n"
] |
[
13,
8,
3,
3,
1
] |
[] |
[] |
[
"mysql",
"python",
"scripting"
] |
stackoverflow_0001932298_mysql_python_scripting.txt
|
Q:
what is the 'extra' mean in this django code
TOPIC_COUNT_SQL = """
SELECT COUNT(*)
FROM topics_topic
WHERE
topics_topic.object_id = maps_map.id AND
topics_topic.content_type_id = %s
"""
MEMBER_COUNT_SQL = """
SELECT COUNT(*)
FROM maps_map_members
WHERE maps_map_members.map_id = maps_map.id
"""
maps = maps.extra(select=SortedDict([
('member_count', MEMBER_COUNT_SQL),
('topic_count', TOPIC_COUNT_SQL),
]), select_params=(content_type.id,))
i don't know this mean,
thanks
A:
It's a method of QuerySet.
|
what is the 'extra' mean in this django code
|
TOPIC_COUNT_SQL = """
SELECT COUNT(*)
FROM topics_topic
WHERE
topics_topic.object_id = maps_map.id AND
topics_topic.content_type_id = %s
"""
MEMBER_COUNT_SQL = """
SELECT COUNT(*)
FROM maps_map_members
WHERE maps_map_members.map_id = maps_map.id
"""
maps = maps.extra(select=SortedDict([
('member_count', MEMBER_COUNT_SQL),
('topic_count', TOPIC_COUNT_SQL),
]), select_params=(content_type.id,))
i don't know this mean,
thanks
|
[
"It's a method of QuerySet.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python",
"sql"
] |
stackoverflow_0002577252_django_python_sql.txt
|
Q:
Make Python 2.6 see Django
In a harrowing attempt to get mod_wsgi to run on CentOS 5.4, I've added Python 2.6 as an optional library following the instructions here. The configuration seems fine except that when trying to ping the server the Apache log prints this error:
mod_wsgi (pid=20033, process='otalo', application='127.0.0.1|'): Loading WSGI script '...django.wsgi'.
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] mod_wsgi (pid=20033): Target WSGI script '...django.wsgi' cannot be loaded as Python module.
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] mod_wsgi (pid=20033): Exception occurred processing WSGI script '...django.wsgi'.
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] Traceback (most recent call last):
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] File "...django.wsgi", line 8, in <module>
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] import django.core.handlers.wsgi
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] ImportError: No module named django.core.handlers.wsgi
when I go to my python2.6 install's command line and try 'import Django', the module is not found (ImportError). However, my default Python 2.4 installation (still working fine) is able to import successfully. How do I point Python 2.6 to Django?
A:
You need to install Django specifically with/for the Python version that's meant to use it -- installs for 2.4 and 2.6 are always going to be separate (they have to be -- there are incompatibilities in binary and bytecode formats!). I don't know what, if any, possibilities CentOS offers for that -- I'd get Django's sources and install from sources (which boils down to: download, tar, cd, and finally a simple sudo python2.6 setup.py install -- or however else you run your 2.6 install of Python). Being a much better developer than I'm a system administrator, I always have a bias in favor of installing from sources for stuff that's really at the core of what I'm doing (especially Python versions and extensions).
A:
I created a write up link text of my experiences of getting Django working on Redhat and and CentOS. I upgraded the version of python that I was using and started with init.d scripts.
|
Make Python 2.6 see Django
|
In a harrowing attempt to get mod_wsgi to run on CentOS 5.4, I've added Python 2.6 as an optional library following the instructions here. The configuration seems fine except that when trying to ping the server the Apache log prints this error:
mod_wsgi (pid=20033, process='otalo', application='127.0.0.1|'): Loading WSGI script '...django.wsgi'.
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] mod_wsgi (pid=20033): Target WSGI script '...django.wsgi' cannot be loaded as Python module.
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] mod_wsgi (pid=20033): Exception occurred processing WSGI script '...django.wsgi'.
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] Traceback (most recent call last):
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] File "...django.wsgi", line 8, in <module>
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] import django.core.handlers.wsgi
[Sat Mar 27 16:11:45 2010] [error] [client 171.66.52.218] ImportError: No module named django.core.handlers.wsgi
when I go to my python2.6 install's command line and try 'import Django', the module is not found (ImportError). However, my default Python 2.4 installation (still working fine) is able to import successfully. How do I point Python 2.6 to Django?
|
[
"You need to install Django specifically with/for the Python version that's meant to use it -- installs for 2.4 and 2.6 are always going to be separate (they have to be -- there are incompatibilities in binary and bytecode formats!). I don't know what, if any, possibilities CentOS offers for that -- I'd get Django's sources and install from sources (which boils down to: download, tar, cd, and finally a simple sudo python2.6 setup.py install -- or however else you run your 2.6 install of Python). Being a much better developer than I'm a system administrator, I always have a bias in favor of installing from sources for stuff that's really at the core of what I'm doing (especially Python versions and extensions).\n",
"I created a write up link text of my experiences of getting Django working on Redhat and and CentOS. I upgraded the version of python that I was using and started with init.d scripts.\n"
] |
[
0,
0
] |
[] |
[] |
[
"centos",
"django",
"mod_wsgi",
"python"
] |
stackoverflow_0002531364_centos_django_mod_wsgi_python.txt
|
Q:
Python's preferred comparison operators
Is it preferred to do:
if x is y:
return True
or
if x == y
return True
Same thing for "is not"
A:
x is y is different than x == y.
x is y is true if and only if id(x) == id(y) -- that is, x and y have to be one and the same object (with the same ids).
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x == y is also True. However, this is not guaranteed in general. Strictly speaking, x == y is true if and only if x.__eq__(y) returns True.
It is possible to define an object x with a __eq__ method which always returns False, for example, and this would cause x == y to return False, even if x is y.
So the bottom line is, x is y and x == y are completely different tests.
Consider this for example:
In [1]: 0 is False
Out[1]: False
In [2]: 0 == False
Out[2]: True
PS. Instead of
if x is y:
return True
else:
return False
it is more Pythonic to write
return x is y
And similarly,
if x == y:
return True
else:
return False
can be replaced with
return x == y
A:
x is y compares the identities of the two objects, and is asking 'are x and y different names for the same object?' It is equivalent to id(x) == id(y).
x == y uses the equality operator and asks the looser question 'are x and y equal?' For user defined types it is equivalent to x.__eq__(y).
The __eq__ special method should represent 'equalness' for the objects, for example a class representing fractions would want 1/2 to equal 2/4, even though the 'one half' object couldn't have the same identity as the 'two quarters' object.
Note that it is not only the case that a == b does not imply a is b, but also the reverse is true. One is not in general a more stringent requirement than the other. Yes, this means that you can have a == a return False if you really want to, for example:
>>> a = float('nan')
>>> a is a
True
>>> a == a
False
In practice though is is almost always a more specific comparison than ==.
A:
== and != are object value comparison operators
is and is not are object identity comparison operators
as others have already said, is (and is not) are only when you actually care that a pair of variables are referring to exactly the same object. in most cases, you really don't care at all, so you would use == and !=.
however, what you may start to notice, if you look at a lot of Python code, is that is (and is not) are more likely to be used when comparing against True, False, and None. the main reason for this is that those objects are singletons, meaning there is exactly one instance of each of those values. why does that matter? well, this leads to another reason... speed.
with == and !=, the interpreter has to pull up both referred objects in order to make a comparison (of whether they're the same or not), while is and is not simply just check the values of the objects they're referring to. with this said, you can see that the latter pair will perform faster because you don't have to fetch the objects themselves in order to make the comparison. here's a speed test from a couple of years back where we concluded that for one-offs, it's not a big deal, but if it's called a gazillion times in a tight loop, well, it will start to add up.
http://mail.python.org/pipermail/tutor/2008-June/062708.html
bottom line is that you can use object identity comparisons for checking against True, False, and None, and everything else should use straight-up equality operators. we won't get into interned integers nor bound instance methods, or anything like that here. :-)
A:
Depends. is and is not do identity comparison, which is good for None, Ellipsis, or making sure that two objects are the same. Otherwise, use == or !=.
|
Python's preferred comparison operators
|
Is it preferred to do:
if x is y:
return True
or
if x == y
return True
Same thing for "is not"
|
[
"x is y is different than x == y.\nx is y is true if and only if id(x) == id(y) -- that is, x and y have to be one and the same object (with the same ids).\nFor all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x == y is also True. However, this is not guaranteed in general. Strictly speaking, x == y is true if and only if x.__eq__(y) returns True. \nIt is possible to define an object x with a __eq__ method which always returns False, for example, and this would cause x == y to return False, even if x is y. \nSo the bottom line is, x is y and x == y are completely different tests.\nConsider this for example:\nIn [1]: 0 is False\nOut[1]: False\n\nIn [2]: 0 == False\nOut[2]: True\n\nPS. Instead of\nif x is y:\n return True\nelse:\n return False\n\nit is more Pythonic to write\nreturn x is y\n\nAnd similarly,\nif x == y:\n return True\nelse:\n return False\n\ncan be replaced with\nreturn x == y\n\n",
"x is y compares the identities of the two objects, and is asking 'are x and y different names for the same object?' It is equivalent to id(x) == id(y).\nx == y uses the equality operator and asks the looser question 'are x and y equal?' For user defined types it is equivalent to x.__eq__(y).\nThe __eq__ special method should represent 'equalness' for the objects, for example a class representing fractions would want 1/2 to equal 2/4, even though the 'one half' object couldn't have the same identity as the 'two quarters' object.\nNote that it is not only the case that a == b does not imply a is b, but also the reverse is true. One is not in general a more stringent requirement than the other. Yes, this means that you can have a == a return False if you really want to, for example:\n>>> a = float('nan')\n>>> a is a\nTrue\n>>> a == a\nFalse\n\nIn practice though is is almost always a more specific comparison than ==.\n",
"\n== and != are object value comparison operators\nis and is not are object identity comparison operators\n\nas others have already said, is (and is not) are only when you actually care that a pair of variables are referring to exactly the same object. in most cases, you really don't care at all, so you would use == and !=.\nhowever, what you may start to notice, if you look at a lot of Python code, is that is (and is not) are more likely to be used when comparing against True, False, and None. the main reason for this is that those objects are singletons, meaning there is exactly one instance of each of those values. why does that matter? well, this leads to another reason... speed.\nwith == and !=, the interpreter has to pull up both referred objects in order to make a comparison (of whether they're the same or not), while is and is not simply just check the values of the objects they're referring to. with this said, you can see that the latter pair will perform faster because you don't have to fetch the objects themselves in order to make the comparison. here's a speed test from a couple of years back where we concluded that for one-offs, it's not a big deal, but if it's called a gazillion times in a tight loop, well, it will start to add up.\nhttp://mail.python.org/pipermail/tutor/2008-June/062708.html\nbottom line is that you can use object identity comparisons for checking against True, False, and None, and everything else should use straight-up equality operators. we won't get into interned integers nor bound instance methods, or anything like that here. :-)\n",
"Depends. is and is not do identity comparison, which is good for None, Ellipsis, or making sure that two objects are the same. Otherwise, use == or !=.\n"
] |
[
40,
15,
9,
5
] |
[] |
[] |
[
"comparison",
"python"
] |
stackoverflow_0002576826_comparison_python.txt
|
Q:
Python newbie: trying to create a script that opens a file and replaces words
im trying to create a script that opens a file and replace every 'hola' with 'hello'.
f=open("kk.txt","w")
for line in f:
if "hola" in line:
line=line.replace('hola','hello')
f.close()
But im getting this error:
Traceback (most recent call last):
File "prueba.py", line 3, in
for line in f: IOError: [Errno 9] Bad file descriptor
Any idea?
Javi
A:
open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello'))
Or if you want to properly close the file:
with open('test.txt', 'r') as src:
src_text = src.read()
with open('test.txt', 'w') as dst:
dst.write(src_text.replace('hola', 'hello'))
A:
You've opened the file for writing, but you're reading from it. Open the original file for reading and a new file for writing. After the replacement, rename the original out and the new one in.
A:
Your main issue is that you're opening the file for writing first. When you open a file for writing, the contents of the file are deleted, which makes it quite difficult to do replacements! If you want to replace words in the file, you have a three-step process:
Read the file into a string
Make replacements in that string
Write that string to the file
In code:
# open for reading first since we need to get the text out
f = open('kk.txt','r')
# step 1
data = f.read()
# step 2
data = data.replace("hola", "hello")
f.close()
# *now* open for writing
f = open('kk.txt', 'w')
# step 3
f.write(data)
f.close()
A:
You could also have a look at the with statement.
|
Python newbie: trying to create a script that opens a file and replaces words
|
im trying to create a script that opens a file and replace every 'hola' with 'hello'.
f=open("kk.txt","w")
for line in f:
if "hola" in line:
line=line.replace('hola','hello')
f.close()
But im getting this error:
Traceback (most recent call last):
File "prueba.py", line 3, in
for line in f: IOError: [Errno 9] Bad file descriptor
Any idea?
Javi
|
[
"open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello'))\n\nOr if you want to properly close the file:\nwith open('test.txt', 'r') as src:\n src_text = src.read()\n\nwith open('test.txt', 'w') as dst:\n dst.write(src_text.replace('hola', 'hello'))\n\n",
"You've opened the file for writing, but you're reading from it. Open the original file for reading and a new file for writing. After the replacement, rename the original out and the new one in.\n",
"Your main issue is that you're opening the file for writing first. When you open a file for writing, the contents of the file are deleted, which makes it quite difficult to do replacements! If you want to replace words in the file, you have a three-step process:\n\nRead the file into a string\nMake replacements in that string\nWrite that string to the file\n\nIn code:\n# open for reading first since we need to get the text out\nf = open('kk.txt','r')\n# step 1\ndata = f.read()\n# step 2\ndata = data.replace(\"hola\", \"hello\")\nf.close()\n# *now* open for writing\nf = open('kk.txt', 'w')\n# step 3\nf.write(data)\nf.close()\n\n",
"You could also have a look at the with statement.\n"
] |
[
7,
4,
4,
3
] |
[] |
[] |
[
"file_manipulation",
"python"
] |
stackoverflow_0002577671_file_manipulation_python.txt
|
Q:
Python - Access a class from a list using a key
Is there any way to make a list of classes behave like a set in python?
Basically, I'm working on a piece of software that does some involved string comparison, and I have a custom class for handling the strings. Therefore, there is an instance of the class for each string.
As a result, I have a large list containing all these classes. I would like to be able to access them like list[key], where in this case, the key is a string the class is based off of (note: the string will never change once the class is instantiated, so it should be hashable).
It seems to me that I should be able to do this somewhat easily, by adding something like __cmp__ to the class, but either I'm being obtuse (likely), or I'm missing something in the docs.
Basically, I want to be able to do something like this (Python prompt example):
>>class a:
... def __init__(self, x):
... self.var = x
...
>>> from test import a
>>> cl = set([a("Hello"), a("World"), a("Pie")])
>>> print cl
set([<test.a instance at 0x00C866C0>, <test.a instance at 0x00C866E8>, <test.a instance at 0x00C86710>])
>>> cl["World"]
<test.a instance at 0x00C866E8>
Thanks!
Edit Some additional Tweaks:
class a:
... def __init__(self, x):
... self.var = x
... def __hash__(self):
... return hash(self.var)
...
>>> v = a("Hello")
>>> x = {}
>>> x[v]=v
>>> x["Hello"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Hello'
>>> x["Hello"]
A:
Just write a class that behaves a bit like a mapping:
class ClassDict(object):
def __init__(self):
self.classes = {}
def add(self, cls):
self.classes[cls.__name__] = cls
def remove(self, cls):
if self.classes[cls.__name__] == cls:
del self.classes[cls.__name__]
else:
raise KeyError('%r' % cls)
def __getitem__(self, key):
return self.classes[key]
def __repr__(self):
return 'ClassDict(%s)' % (', '.join(self.classes),)
class C(object):
pass
class D(object):
pass
cd = ClassDict()
cd.add(C)
cd.add(D)
print cd
print cd['C']
A:
Why don't you just do:
>>> v = MyStr("Hello")
>>> x = {}
>>> x[v.val]=v
>>> x["Hello"]
MyStr("Hello")
Why go through all the trouble of trying to create a hand-rolled dict that uses different keys than the ones you pass in? (i.e. "Hello" instead of MyStr("Hello")).
ex.
class MyStr(object):
def __init__(self, val):
self.val = str(val)
def __hash__(self):
return hash(self.val)
def __str__(self):
return self.val
def __repr__(self):
return 'MyStr("%s")' % self.val
>>> v = MyStr("Hello")
>>> x = {}
>>> x[str(v)]=v
>>> x["Hello"]
MyStr("Hello")
A:
As I remember "set" and "dict" uses also __hash__
From Python 2.x doc:
A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.
A:
Set and dict use the value returned by an object's __hash__ method to look up the object, so this will do what you want:
>>class a:
... def __init__(self, x):
... self.var = x
...
... def __hash__(self):
... return hash(self.var)
A:
Do you want something like this
class A(object):
ALL_INSTANCES = {}
def __init__(self, text):
self.text = text
self.ALL_INSTANCES[self.text] = self
a1 = A("hello")
a2 = A("world")
print A.ALL_INSTANCES["hello"]
output:
<__main__.A object at 0x00B7EA50>
|
Python - Access a class from a list using a key
|
Is there any way to make a list of classes behave like a set in python?
Basically, I'm working on a piece of software that does some involved string comparison, and I have a custom class for handling the strings. Therefore, there is an instance of the class for each string.
As a result, I have a large list containing all these classes. I would like to be able to access them like list[key], where in this case, the key is a string the class is based off of (note: the string will never change once the class is instantiated, so it should be hashable).
It seems to me that I should be able to do this somewhat easily, by adding something like __cmp__ to the class, but either I'm being obtuse (likely), or I'm missing something in the docs.
Basically, I want to be able to do something like this (Python prompt example):
>>class a:
... def __init__(self, x):
... self.var = x
...
>>> from test import a
>>> cl = set([a("Hello"), a("World"), a("Pie")])
>>> print cl
set([<test.a instance at 0x00C866C0>, <test.a instance at 0x00C866E8>, <test.a instance at 0x00C86710>])
>>> cl["World"]
<test.a instance at 0x00C866E8>
Thanks!
Edit Some additional Tweaks:
class a:
... def __init__(self, x):
... self.var = x
... def __hash__(self):
... return hash(self.var)
...
>>> v = a("Hello")
>>> x = {}
>>> x[v]=v
>>> x["Hello"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Hello'
>>> x["Hello"]
|
[
"Just write a class that behaves a bit like a mapping:\nclass ClassDict(object):\n def __init__(self):\n self.classes = {}\n\n def add(self, cls):\n self.classes[cls.__name__] = cls\n\n def remove(self, cls):\n if self.classes[cls.__name__] == cls:\n del self.classes[cls.__name__]\n else:\n raise KeyError('%r' % cls)\n\n def __getitem__(self, key):\n return self.classes[key]\n\n def __repr__(self):\n return 'ClassDict(%s)' % (', '.join(self.classes),)\n\nclass C(object):\n pass\n\nclass D(object):\n pass\n\ncd = ClassDict()\ncd.add(C)\ncd.add(D)\n\nprint cd\n\nprint cd['C']\n\n",
"Why don't you just do:\n>>> v = MyStr(\"Hello\")\n>>> x = {}\n>>> x[v.val]=v\n>>> x[\"Hello\"]\nMyStr(\"Hello\")\n\nWhy go through all the trouble of trying to create a hand-rolled dict that uses different keys than the ones you pass in? (i.e. \"Hello\" instead of MyStr(\"Hello\")).\nex.\nclass MyStr(object):\n def __init__(self, val):\n self.val = str(val)\n\n def __hash__(self):\n return hash(self.val)\n\n def __str__(self):\n return self.val\n\n def __repr__(self):\n return 'MyStr(\"%s\")' % self.val\n\n\n>>> v = MyStr(\"Hello\")\n>>> x = {}\n>>> x[str(v)]=v\n>>> x[\"Hello\"]\nMyStr(\"Hello\")\n\n",
"As I remember \"set\" and \"dict\" uses also __hash__\nFrom Python 2.x doc:\n\nA dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.\n\n",
"Set and dict use the value returned by an object's __hash__ method to look up the object, so this will do what you want:\n>>class a:\n... def __init__(self, x):\n... self.var = x\n...\n... def __hash__(self):\n... return hash(self.var)\n\n",
"Do you want something like this\nclass A(object):\n ALL_INSTANCES = {}\n def __init__(self, text):\n self.text = text\n self.ALL_INSTANCES[self.text] = self\n\n\n\na1 = A(\"hello\")\na2 = A(\"world\")\n\nprint A.ALL_INSTANCES[\"hello\"]\n\noutput:\n<__main__.A object at 0x00B7EA50>\n\n"
] |
[
2,
2,
1,
1,
0
] |
[] |
[] |
[
"class",
"python"
] |
stackoverflow_0002577549_class_python.txt
|
Q:
Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
i would like to replace the lines
function *{
by
function *{echo "The function starts here."
where * is what ever.
Any idea how to do that in Python?
Regards
Javi
A:
re.compile(r'(^function .*{)', re.M).sub(r'\1echo "The function starts here."', s)
A:
if all your scripts are "well coded",
import fileinput,os
root="/path"
path=os.path.join(root,"mydir")
os.chdir(path)
for file in os.listdir("."):
if os.path.isfile(file) and file.endswith(".txt"): # do for txt files
for line in fileinput.FileInput(file,inplace=1):
line=line.rstrip()
if "function" in line and "{" in line:
s=line.split("{")
s.insert(1,'{echo "The function starts here."')
line=' '.join(s)
print line
A:
Apply a regular expression replace to the text. The module you are looking for is re.
|
Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
|
i would like to replace the lines
function *{
by
function *{echo "The function starts here."
where * is what ever.
Any idea how to do that in Python?
Regards
Javi
|
[
"re.compile(r'(^function .*{)', re.M).sub(r'\\1echo \"The function starts here.\"', s)\n\n",
"if all your scripts are \"well coded\",\nimport fileinput,os\nroot=\"/path\"\npath=os.path.join(root,\"mydir\")\nos.chdir(path)\nfor file in os.listdir(\".\"):\n if os.path.isfile(file) and file.endswith(\".txt\"): # do for txt files\n for line in fileinput.FileInput(file,inplace=1):\n line=line.rstrip()\n if \"function\" in line and \"{\" in line: \n s=line.split(\"{\")\n s.insert(1,'{echo \"The function starts here.\"')\n line=' '.join(s)\n print line\n\n",
"Apply a regular expression replace to the text. The module you are looking for is re.\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002577819_python_regex.txt
|
Q:
Python 2.5.2: trying to open files recursively
The script below should open all the files inside the folder 'pruebaba' recursively but I get this error:
Traceback (most recent call last):
File
"/home/tirengarfio/Desktop/prueba.py",
line 8, in
f = open(file,'r') IOError: [Errno 21] Is a directory
This is the hierarchy:
pruebaba
folder1
folder11
test1.php
folder12
test1.php
test2.php
folder2
test1.php
The script:
import re,fileinput,os
path="/home/tirengarfio/Desktop/pruebaba"
os.chdir(path)
for file in os.listdir("."):
f = open(file,'r')
data = f.read()
data = re.sub(r'(\s*function\s+.*\s*{\s*)',
r'\1echo "The function starts here."',
data)
f.close()
f = open(file, 'w')
f.write(data)
f.close()
Any idea?
A:
Use os.walk. It recursively walks into directory and subdirectories, and already gives you separate variables for files and directories.
import re
import os
from __future__ import with_statement
PATH = "/home/tirengarfio/Desktop/pruebaba"
for path, dirs, files in os.walk(PATH):
for filename in files:
fullpath = os.path.join(path, filename)
with open(fullpath, 'r') as f:
data = re.sub(r'(\s*function\s+.*\s*{\s*)',
r'\1echo "The function starts here."',
f.read())
with open(fullpath, 'w') as f:
f.write(data)
A:
You're trying to open everything you see. One thing you tried to open was a directory; you need to check if an entry is a file or is a directory, and make a decision from there. (Was the error IOError: [Errno 21] Is a directory not descriptive enough?)
If it is a directory, then you'll want to make a recursive call to your function to walk over the files in that directory as well.
Alternatively, you might be interested in the os.walk function to take care of the recursive-ness for you.
A:
os.listdir lists both files and directories. You should check if what you're trying to open really is a file with os.path.isfile
|
Python 2.5.2: trying to open files recursively
|
The script below should open all the files inside the folder 'pruebaba' recursively but I get this error:
Traceback (most recent call last):
File
"/home/tirengarfio/Desktop/prueba.py",
line 8, in
f = open(file,'r') IOError: [Errno 21] Is a directory
This is the hierarchy:
pruebaba
folder1
folder11
test1.php
folder12
test1.php
test2.php
folder2
test1.php
The script:
import re,fileinput,os
path="/home/tirengarfio/Desktop/pruebaba"
os.chdir(path)
for file in os.listdir("."):
f = open(file,'r')
data = f.read()
data = re.sub(r'(\s*function\s+.*\s*{\s*)',
r'\1echo "The function starts here."',
data)
f.close()
f = open(file, 'w')
f.write(data)
f.close()
Any idea?
|
[
"Use os.walk. It recursively walks into directory and subdirectories, and already gives you separate variables for files and directories.\nimport re\nimport os\nfrom __future__ import with_statement\n\nPATH = \"/home/tirengarfio/Desktop/pruebaba\"\n\nfor path, dirs, files in os.walk(PATH):\n for filename in files:\n fullpath = os.path.join(path, filename)\n with open(fullpath, 'r') as f:\n data = re.sub(r'(\\s*function\\s+.*\\s*{\\s*)',\n r'\\1echo \"The function starts here.\"',\n f.read())\n with open(fullpath, 'w') as f:\n f.write(data)\n\n",
"You're trying to open everything you see. One thing you tried to open was a directory; you need to check if an entry is a file or is a directory, and make a decision from there. (Was the error IOError: [Errno 21] Is a directory not descriptive enough?)\nIf it is a directory, then you'll want to make a recursive call to your function to walk over the files in that directory as well.\nAlternatively, you might be interested in the os.walk function to take care of the recursive-ness for you.\n",
"os.listdir lists both files and directories. You should check if what you're trying to open really is a file with os.path.isfile\n"
] |
[
14,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002578022_python.txt
|
Q:
Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
I've been following the saga of Python 3.x and have watched the 3.x features gradually getting back-ported to the 2.x line.
Most of the libraries I use haven't been ported and some (e.g. Twisted) seem covertly or overtly hostile to 3.x to varying degrees. At any rate, there has been very little movement towards compatible versions of many of them. Expecially the larger ones.
So, my question is, with all the features that have been backported, what is still available in 3.x that's NOT been back-ported? It's pretty easy to find what has been backported, but not what's left.
Right now, porting to 3.x just seems like all pain, and I can't see the gain; maybe an "Only in 3.x" list would let me see the light...
Thanks,
Stu
A:
The most important thing is probably unicode throughout. So there is no need anymore to fiddle around with str/unicode. This sounds small but has huge (positive) implications when you think of OS interaction - for example everyone has to try hard to give you 'usable' strings instead of 'a binary thing that might be an error message'.
There's also a lot of stuff in the interpreter itself that was improved. One example is the global interpreter lock (GIL) which did not vanish but it way better in py3k: presentation+slides
A:
Speed might be a feature worth mentioning.
The speed imporovements of project "Unladen Swallow" have been approved to be merged into Python. But as far as I know only to Python 3. See PEP 3146 for details.
|
Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
|
I've been following the saga of Python 3.x and have watched the 3.x features gradually getting back-ported to the 2.x line.
Most of the libraries I use haven't been ported and some (e.g. Twisted) seem covertly or overtly hostile to 3.x to varying degrees. At any rate, there has been very little movement towards compatible versions of many of them. Expecially the larger ones.
So, my question is, with all the features that have been backported, what is still available in 3.x that's NOT been back-ported? It's pretty easy to find what has been backported, but not what's left.
Right now, porting to 3.x just seems like all pain, and I can't see the gain; maybe an "Only in 3.x" list would let me see the light...
Thanks,
Stu
|
[
"The most important thing is probably unicode throughout. So there is no need anymore to fiddle around with str/unicode. This sounds small but has huge (positive) implications when you think of OS interaction - for example everyone has to try hard to give you 'usable' strings instead of 'a binary thing that might be an error message'.\nThere's also a lot of stuff in the interpreter itself that was improved. One example is the global interpreter lock (GIL) which did not vanish but it way better in py3k: presentation+slides\n",
"Speed might be a feature worth mentioning.\nThe speed imporovements of project \"Unladen Swallow\" have been approved to be merged into Python. But as far as I know only to Python 3. See PEP 3146 for details.\n"
] |
[
6,
3
] |
[] |
[] |
[
"python",
"python_2.7",
"python_3.x"
] |
stackoverflow_0002568187_python_python_2.7_python_3.x.txt
|
Q:
How to check if a network path exist?
What is the best way to know if a network path(e.g. //192.168.1.1/test) exist using python in linux?
A:
If by "path" you mean an internet URL, you'll want to look at the urllib module.
from urllib import urlopen
try:
urlopen(path)
except IOError:
pass # does not exist
else:
pass # does exist
If by "path" you mean a Windows UNC, then you'll want to use the os module.
import os
os.path.isdir(path)
Note, I've found the Windows UNC paths somewhat flakey. Depending on your network setup and permissions, they may or may not be accessible.
|
How to check if a network path exist?
|
What is the best way to know if a network path(e.g. //192.168.1.1/test) exist using python in linux?
|
[
"If by \"path\" you mean an internet URL, you'll want to look at the urllib module.\nfrom urllib import urlopen\ntry:\n urlopen(path)\nexcept IOError:\n pass # does not exist\nelse:\n pass # does exist\n\nIf by \"path\" you mean a Windows UNC, then you'll want to use the os module.\nimport os\nos.path.isdir(path)\n\nNote, I've found the Windows UNC paths somewhat flakey. Depending on your network setup and permissions, they may or may not be accessible.\n"
] |
[
3
] |
[] |
[] |
[
"linux",
"networking",
"python"
] |
stackoverflow_0002578177_linux_networking_python.txt
|
Q:
Is there an admin plugin for Python Pylon?
Im moving from django to pylons, is there an admin app?
A:
Not out of the box, but there are few options you can use. See Forms - Pylons Cookbook - PythonWeb for the options:
formalchemy - the only one I used personally, and there is even an extension module for pylons documented formalchemy.ext.pylons – Pylons extensions, which I recommend to try out.
ToscaWidgets
DBSprockets
even Django's newforms (the link to it on the site above is broken, but google for it)
|
Is there an admin plugin for Python Pylon?
|
Im moving from django to pylons, is there an admin app?
|
[
"Not out of the box, but there are few options you can use. See Forms - Pylons Cookbook - PythonWeb for the options:\n\nformalchemy - the only one I used personally, and there is even an extension module for pylons documented formalchemy.ext.pylons – Pylons extensions, which I recommend to try out.\nToscaWidgets\nDBSprockets\neven Django's newforms (the link to it on the site above is broken, but google for it)\n\n"
] |
[
3
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0002578641_pylons_python.txt
|
Q:
Python socket error on UDP data receive. (10054)
I currently have a problem using UDP and Python socket module. We have a server and clients. The problem occurs when we send data to a user. It's possible that user may have closed their connection to the server through a client crash, disconnect by ISP, or some other improper method. As such, it is possible to send data to a closed socket.
Of course with UDP you can't tell if the data really reached or if it's closed, as it doesn't care (atleast, it doesn't bring up an exception). However, if you send data and it is closed off, you get data back somehow (???), which ends up giving you a socket error on sock.recvfrom. [Errno 10054] An existing connection was forcibly closed by the remote host. Almost seems like an automatic response from the connection.
Although this is fine, and can be handled by a try: except: block (even if it lowers performance of the server a little bit). The problem is, I can't tell who this is coming from or what socket is closed. Is there anyway to find out 'who' (ip, socket #) sent this? It would be great as I could instantly just disconnect them and remove them from the data. Any suggestions? Thanks.
Server:
import socket
class Server(object):
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.connected = {}
def connect(self):
self.socket.bind(('127.0.0.1', 5579))
def find_data(self):
while 1:
data, address = self.socket.recvfrom(1024)
self.got_data(data,address)
if self.connected.has_key(address):
pass
else:
self.connected[address] = None
def got_data(self, data, address):
print "GOT",data,"FROM",address
for people in self.connected:
print people
self.send_data('hi', people)
def send_data(self, data, address):
self.socket.sendto(data,address)
if __name__ == '__main__':
server = Server()
server.connect()
print "NOW SEARCHING FOR DATA"
server.find_data()
Client:
import socket, time
class Client(object):
def __init__(self):
self.socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
def connect(self):
self.socket.connect(('127.0.0.1', 5579))
def send_data(self):
self.socket.sendto('hi',('127.0.0.1', 5579))
def got_data(self, data, address):
print "GOT",data,"FROM",address
if __name__ == '__main__':
client = Client()
client.connect()
while 1:
client.send_data()
time.sleep(5)
A:
Firstly this is possibly platform specific and you don't mention the platform that you're running on; however, 10054 is WSAECONNRESET so I'm guessing a Windows platform of some kind.
Secondly as previously pointed out there is no connection with UDP. Your call to Connect() in the client simply causes the networking code on your client machine to allow you to initiate Send() calls rather than SendTo() calls and simply default the address that you are sending data to when you issue Send() calls to the address supplied to the call to Connect().
Thirdly I'm surprised that you're getting WSAECONNRESET and not ERROR_PORT_UNREACHABLE; however the underlying reason is probably the same. The UDP stack on the remote machine will likely be sending a ICMP Port Unreachable error if there's no socket open on the port that you are sending to. So, if your client sends data and then closes the socket and then your server sends data back to the client address you'll get a port unreachable and some versions of windows might be translating that into a connection reset error...
The problem with these ICMP port unreachable errors, is that they're reported via the Winsock code by failing a pending UDP Recv/RecvFrom call. As I explain here and question here the UDP stack obviously knows the address that generated the port unreachable but it doesn't pass that information on to the caller so there's nothing that you can do to map these messages to something useful. It's possible that you're running on a version of Windows prior to Vista and the UDP stack is doing something useful with the address and it IS reporting the error to the correct socket, but don't bet on it.
Finally you have a problem anyway; the ICMP port unreachable error isn't delivered reliably so you can't know for sure that you WILL get an error if you try and send UDP data to a client that has gone away. IMHO this means that you shouldn't rely on it even if it works sometimes.
You are obviously attempting to build some kind of connection oriented protocol on top of UDP (why else would your server hold on to the addresses of the clients). You'll have to do a lot more to create a viable pseudo connection over UDP and one of the first things to realise is that the only way you can know when a client has gone away is to set your own timeout and 'disconnect' your pseudo connection if you don't hear from them within a certain period of time.
Of course this doesn't answer your question; how do you avoid the exception. I expect you can't. The cause of the exception is likely a 'failure' return code from a Recv() or RecvFrom() call and the python network code is probably converting all such failure returns into exceptions for you.
A:
The problem is far simpler than it looks. Use socket.recv() rather than socket.recvfrom() - I made this change locally and your code then works.
A:
Well, it seems obvious.
UDP doesn't have connections, so Client.connect is wrong
You're storing the client address in the Server.connected dict. When the client is closed, nobody will be there to receive what you're sending.
Getting network communication right is hard, since socket library it is too low-level (it is a thin wrapper around C sockets). A lot of details have been left out on your code. I suggest trying a higher level library, like twisted. Here's some example on UDP to get you started.
|
Python socket error on UDP data receive. (10054)
|
I currently have a problem using UDP and Python socket module. We have a server and clients. The problem occurs when we send data to a user. It's possible that user may have closed their connection to the server through a client crash, disconnect by ISP, or some other improper method. As such, it is possible to send data to a closed socket.
Of course with UDP you can't tell if the data really reached or if it's closed, as it doesn't care (atleast, it doesn't bring up an exception). However, if you send data and it is closed off, you get data back somehow (???), which ends up giving you a socket error on sock.recvfrom. [Errno 10054] An existing connection was forcibly closed by the remote host. Almost seems like an automatic response from the connection.
Although this is fine, and can be handled by a try: except: block (even if it lowers performance of the server a little bit). The problem is, I can't tell who this is coming from or what socket is closed. Is there anyway to find out 'who' (ip, socket #) sent this? It would be great as I could instantly just disconnect them and remove them from the data. Any suggestions? Thanks.
Server:
import socket
class Server(object):
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.connected = {}
def connect(self):
self.socket.bind(('127.0.0.1', 5579))
def find_data(self):
while 1:
data, address = self.socket.recvfrom(1024)
self.got_data(data,address)
if self.connected.has_key(address):
pass
else:
self.connected[address] = None
def got_data(self, data, address):
print "GOT",data,"FROM",address
for people in self.connected:
print people
self.send_data('hi', people)
def send_data(self, data, address):
self.socket.sendto(data,address)
if __name__ == '__main__':
server = Server()
server.connect()
print "NOW SEARCHING FOR DATA"
server.find_data()
Client:
import socket, time
class Client(object):
def __init__(self):
self.socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
def connect(self):
self.socket.connect(('127.0.0.1', 5579))
def send_data(self):
self.socket.sendto('hi',('127.0.0.1', 5579))
def got_data(self, data, address):
print "GOT",data,"FROM",address
if __name__ == '__main__':
client = Client()
client.connect()
while 1:
client.send_data()
time.sleep(5)
|
[
"Firstly this is possibly platform specific and you don't mention the platform that you're running on; however, 10054 is WSAECONNRESET so I'm guessing a Windows platform of some kind.\nSecondly as previously pointed out there is no connection with UDP. Your call to Connect() in the client simply causes the networking code on your client machine to allow you to initiate Send() calls rather than SendTo() calls and simply default the address that you are sending data to when you issue Send() calls to the address supplied to the call to Connect().\nThirdly I'm surprised that you're getting WSAECONNRESET and not ERROR_PORT_UNREACHABLE; however the underlying reason is probably the same. The UDP stack on the remote machine will likely be sending a ICMP Port Unreachable error if there's no socket open on the port that you are sending to. So, if your client sends data and then closes the socket and then your server sends data back to the client address you'll get a port unreachable and some versions of windows might be translating that into a connection reset error...\nThe problem with these ICMP port unreachable errors, is that they're reported via the Winsock code by failing a pending UDP Recv/RecvFrom call. As I explain here and question here the UDP stack obviously knows the address that generated the port unreachable but it doesn't pass that information on to the caller so there's nothing that you can do to map these messages to something useful. It's possible that you're running on a version of Windows prior to Vista and the UDP stack is doing something useful with the address and it IS reporting the error to the correct socket, but don't bet on it.\nFinally you have a problem anyway; the ICMP port unreachable error isn't delivered reliably so you can't know for sure that you WILL get an error if you try and send UDP data to a client that has gone away. IMHO this means that you shouldn't rely on it even if it works sometimes. \nYou are obviously attempting to build some kind of connection oriented protocol on top of UDP (why else would your server hold on to the addresses of the clients). You'll have to do a lot more to create a viable pseudo connection over UDP and one of the first things to realise is that the only way you can know when a client has gone away is to set your own timeout and 'disconnect' your pseudo connection if you don't hear from them within a certain period of time.\nOf course this doesn't answer your question; how do you avoid the exception. I expect you can't. The cause of the exception is likely a 'failure' return code from a Recv() or RecvFrom() call and the python network code is probably converting all such failure returns into exceptions for you. \n",
"The problem is far simpler than it looks. Use socket.recv() rather than socket.recvfrom() - I made this change locally and your code then works.\n",
"Well, it seems obvious.\n\nUDP doesn't have connections, so Client.connect is wrong\nYou're storing the client address in the Server.connected dict. When the client is closed, nobody will be there to receive what you're sending.\n\nGetting network communication right is hard, since socket library it is too low-level (it is a thin wrapper around C sockets). A lot of details have been left out on your code. I suggest trying a higher level library, like twisted. Here's some example on UDP to get you started.\n"
] |
[
9,
2,
1
] |
[] |
[] |
[
"client",
"python",
"sockets",
"udp"
] |
stackoverflow_0002576926_client_python_sockets_udp.txt
|
Q:
Why is the destructor called when the CPython garbage collector is disabled?
I'm trying to understand the internals of the CPython garbage collector, specifically when the destructor is called. So far, the behavior is intuitive, but the following case trips me up:
Disable the GC.
Create an object, then remove a reference to it.
The object is destroyed and the _____del_____ method is called.
I thought this would only happen if the garbage collector was enabled. Can someone explain why this happens? Is there a way to defer calling the destructor?
import gc
import unittest
_destroyed = False
class MyClass(object):
def __del__(self):
global _destroyed
_destroyed = True
class GarbageCollectionTest(unittest.TestCase):
def testExplicitGarbageCollection(self):
gc.disable()
ref = MyClass()
ref = None
# The next test fails.
# The object is automatically destroyed even with the collector turned off.
self.assertFalse(_destroyed)
gc.collect()
self.assertTrue(_destroyed)
if __name__=='__main__':
unittest.main()
Disclaimer: this code is not meant for production -- I've already noted that this is very implementation-specific and does not work on Jython.
A:
Python has both reference counting garbage collection and cyclic garbage collection, and it's the latter that the gc module controls. Reference counting can't be disabled, and hence still happens when the cyclic garbage collector is switched off.
Since there are no references left to your object after ref = None, its __del__ method is called as a result of its reference count going to zero.
There's a clue in the documentation: "Since the collector supplements the reference counting already used in Python..." (my emphasis).
You can stop the first assertion from firing by making the object refer to itself, so that its reference count doesn't go to zero, for instance by giving it this constructor:
def __init__(self):
self.myself = self
But if you do that, the second assertion will fire. That's because garbage cycles with __del__ methods don't get collected - see the documentation for gc.garbage.
A:
The docs here (original link was to a documentation section which up to Python 3.5 was here, and was later relocated) explain how what's called "the optional garbage collector" is actually a collector of cyclic garbage (the kind that reference counting wouldn't catch) (see also here). Reference counting is explained here, with a nod to its interplay with the cyclic gc:
While Python uses the traditional
reference counting implementation, it
also offers a cycle detector that
works to detect reference cycles. This
allows applications to not worry about
creating direct or indirect circular
references; these are the weakness of
garbage collection implemented using
only reference counting. Reference
cycles consist of objects which
contain (possibly indirect) references
to themselves, so that each object in
the cycle has a reference count which
is non-zero. Typical reference
counting implementations are not able
to reclaim the memory belonging to any
objects in a reference cycle, or
referenced from the objects in the
cycle, even though there are no
further references to the cycle
itself.
A:
Depending on your definition of garbage collector, CPython has two garbage collectors, the reference counting one, and the other one.
The reference counter is always working, and cannot be turned off, as it's quite a fast and lightweight one that does not sigificantly affect the run time of the system.
The other one (some varient of mark and sweep, I think), gets run every so often, and can be disabled. This is because it requires the interpreter to be paused while it is running, and this can happen at the wrong moment, and consume quite a lot of CPU time.
This ability to disable it is there for those time when you expect to be doing something that's time critical, and the lack of this GC won't cause you any problems.
|
Why is the destructor called when the CPython garbage collector is disabled?
|
I'm trying to understand the internals of the CPython garbage collector, specifically when the destructor is called. So far, the behavior is intuitive, but the following case trips me up:
Disable the GC.
Create an object, then remove a reference to it.
The object is destroyed and the _____del_____ method is called.
I thought this would only happen if the garbage collector was enabled. Can someone explain why this happens? Is there a way to defer calling the destructor?
import gc
import unittest
_destroyed = False
class MyClass(object):
def __del__(self):
global _destroyed
_destroyed = True
class GarbageCollectionTest(unittest.TestCase):
def testExplicitGarbageCollection(self):
gc.disable()
ref = MyClass()
ref = None
# The next test fails.
# The object is automatically destroyed even with the collector turned off.
self.assertFalse(_destroyed)
gc.collect()
self.assertTrue(_destroyed)
if __name__=='__main__':
unittest.main()
Disclaimer: this code is not meant for production -- I've already noted that this is very implementation-specific and does not work on Jython.
|
[
"Python has both reference counting garbage collection and cyclic garbage collection, and it's the latter that the gc module controls. Reference counting can't be disabled, and hence still happens when the cyclic garbage collector is switched off.\nSince there are no references left to your object after ref = None, its __del__ method is called as a result of its reference count going to zero.\nThere's a clue in the documentation: \"Since the collector supplements the reference counting already used in Python...\" (my emphasis).\nYou can stop the first assertion from firing by making the object refer to itself, so that its reference count doesn't go to zero, for instance by giving it this constructor:\ndef __init__(self):\n self.myself = self\n\nBut if you do that, the second assertion will fire. That's because garbage cycles with __del__ methods don't get collected - see the documentation for gc.garbage.\n",
"The docs here (original link was to a documentation section which up to Python 3.5 was here, and was later relocated) explain how what's called \"the optional garbage collector\" is actually a collector of cyclic garbage (the kind that reference counting wouldn't catch) (see also here). Reference counting is explained here, with a nod to its interplay with the cyclic gc:\n\nWhile Python uses the traditional\nreference counting implementation, it\nalso offers a cycle detector that\nworks to detect reference cycles. This\nallows applications to not worry about\ncreating direct or indirect circular\nreferences; these are the weakness of\ngarbage collection implemented using\nonly reference counting. Reference\ncycles consist of objects which\ncontain (possibly indirect) references\nto themselves, so that each object in\nthe cycle has a reference count which\nis non-zero. Typical reference\ncounting implementations are not able\nto reclaim the memory belonging to any\nobjects in a reference cycle, or\nreferenced from the objects in the\ncycle, even though there are no\nfurther references to the cycle\nitself.\n\n",
"Depending on your definition of garbage collector, CPython has two garbage collectors, the reference counting one, and the other one.\nThe reference counter is always working, and cannot be turned off, as it's quite a fast and lightweight one that does not sigificantly affect the run time of the system.\nThe other one (some varient of mark and sweep, I think), gets run every so often, and can be disabled. This is because it requires the interpreter to be paused while it is running, and this can happen at the wrong moment, and consume quite a lot of CPU time.\nThis ability to disable it is there for those time when you expect to be doing something that's time critical, and the lack of this GC won't cause you any problems.\n"
] |
[
11,
5,
4
] |
[] |
[] |
[
"cpython",
"garbage_collection",
"python"
] |
stackoverflow_0002578098_cpython_garbage_collection_python.txt
|
Q:
What is the best way to convert a zope DateTime object into Python datetime object?
I need to convert a zope 2 DateTime object into a Python datetime object. What is the best way to do that? Thanks, Erika
A:
Newer DateTime implementations (2.11 and up) have a asdatetime method that returns a python datetime.datetime instance:
modernthingy = zopethingy.asdatetime()
A:
modernthingy = datetime.datetime.fromtimestamp(zopethingy.timeTime())
The datetime instance is timezone-naive; if you need to support timezones (as Zope2's DateTime does), I recommend third-party extension package pytz.
A:
If you mean this one
.strftime('%m/%d/%Y %H:%M') = 04/25/2005 10:19
then reverse is
>>> time.strptime('04/25/2005 10:19','%m/%d/%Y %H:%M')
time.struct_time(tm_year=2005, tm_mon=4, tm_mday=25, tm_hour=10, tm_min=19, tm_sec=0, tm_wday=0, tm_yday=115, tm_isdst=-1)
|
What is the best way to convert a zope DateTime object into Python datetime object?
|
I need to convert a zope 2 DateTime object into a Python datetime object. What is the best way to do that? Thanks, Erika
|
[
"Newer DateTime implementations (2.11 and up) have a asdatetime method that returns a python datetime.datetime instance:\nmodernthingy = zopethingy.asdatetime()\n\n",
"modernthingy = datetime.datetime.fromtimestamp(zopethingy.timeTime())\n\nThe datetime instance is timezone-naive; if you need to support timezones (as Zope2's DateTime does), I recommend third-party extension package pytz.\n",
"If you mean this one\n.strftime('%m/%d/%Y %H:%M') = 04/25/2005 10:19\n\nthen reverse is\n>>> time.strptime('04/25/2005 10:19','%m/%d/%Y %H:%M')\ntime.struct_time(tm_year=2005, tm_mon=4, tm_mday=25, tm_hour=10, tm_min=19, tm_sec=0, tm_wday=0, tm_yday=115, tm_isdst=-1)\n\n"
] |
[
11,
7,
1
] |
[] |
[] |
[
"python",
"zope"
] |
stackoverflow_0002578770_python_zope.txt
|
Q:
Using set with values from a table
I'm writing a database of all DVDs I have at home.
One of the fields, actors, I would like it to be a set of values from an other table, which is storing actors. So for every film I want to store a list of actors, all of which selected from a list of actors, taken from a different table.
Is it possible? How do I do this? It would be a set of foreign keys basically.
I'm using a MySQL database for a Django application (python), so any hint in SQL or Python would be much appreciated.
I hope the question is clear,
many thanks.
A:
Make your tables like this:
Movies
MovieID int auto increment/identity PK
MovieTitle
MovieDescription
etc...
Actors
ActorID int auto increment/identity PK
ActorName
DateOfBirth
etc...
MovieActors
MovieID PK and FK
ActorID PK and FK
RoleName
etc...
Don't store multiple Actors within a single field within the Movies table, break them out into individual rows in the MovieActors table.
If you combine all the actors within one field, it will make writing queries difficult. For example, you would need to do string manipulation to query all movies that actor X was in.
A:
The answer is clear too. You will need not a field, but another films_actors table. This table would act as your field, but much more reliable. This is called many-to-many relation.
|
Using set with values from a table
|
I'm writing a database of all DVDs I have at home.
One of the fields, actors, I would like it to be a set of values from an other table, which is storing actors. So for every film I want to store a list of actors, all of which selected from a list of actors, taken from a different table.
Is it possible? How do I do this? It would be a set of foreign keys basically.
I'm using a MySQL database for a Django application (python), so any hint in SQL or Python would be much appreciated.
I hope the question is clear,
many thanks.
|
[
"Make your tables like this:\nMovies\nMovieID int auto increment/identity PK\nMovieTitle\nMovieDescription\netc...\n\nActors\nActorID int auto increment/identity PK\nActorName\nDateOfBirth\netc...\n\nMovieActors\nMovieID PK and FK\nActorID PK and FK\nRoleName\netc...\n\nDon't store multiple Actors within a single field within the Movies table, break them out into individual rows in the MovieActors table. \nIf you combine all the actors within one field, it will make writing queries difficult. For example, you would need to do string manipulation to query all movies that actor X was in.\n",
"The answer is clear too. You will need not a field, but another films_actors table. This table would act as your field, but much more reliable. This is called many-to-many relation.\n"
] |
[
2,
1
] |
[] |
[] |
[
"django_models",
"mysql",
"python",
"sql"
] |
stackoverflow_0002579866_django_models_mysql_python_sql.txt
|
Q:
Pylibmc: ImportError: dynamic module does not define init function (init_pylibmc)
>>> import pylibmc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylibmc.py", line 55, in <module>
import _pylibmc
ImportError: dynamic module does not define init function (init_pylibmc)
Trying to import pylibmc, which tries to import _pylibmc.so
I'm using Mac OSX 10.5.6
A:
That's very odd. I (the developer of pylibmc) use Mac OS X 10.6.3 to develop pylibmc, and libmemcached 0.38 should be fine.
Try downloading the actual tarball and unpacking it, then:
$ sudo python setup.py install --with-libmemcached=/path/to/libmemcached-0.38
(lots of output)
$ python -m pylibmc -v
|
Pylibmc: ImportError: dynamic module does not define init function (init_pylibmc)
|
>>> import pylibmc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylibmc.py", line 55, in <module>
import _pylibmc
ImportError: dynamic module does not define init function (init_pylibmc)
Trying to import pylibmc, which tries to import _pylibmc.so
I'm using Mac OSX 10.5.6
|
[
"That's very odd. I (the developer of pylibmc) use Mac OS X 10.6.3 to develop pylibmc, and libmemcached 0.38 should be fine.\nTry downloading the actual tarball and unpacking it, then:\n$ sudo python setup.py install --with-libmemcached=/path/to/libmemcached-0.38\n(lots of output)\n$ python -m pylibmc -v\n\n"
] |
[
2
] |
[] |
[] |
[
"memcached",
"python",
"python_module"
] |
stackoverflow_0002547117_memcached_python_python_module.txt
|
Q:
Not Possible to Reference self in a Method Declaration?
I wanted to write a method with an argument that defaults to a member variable like so:
def method(self, arg1=0, arg2=self.member):
Apparently this is not allowed. Should I write it a different way, or perhaps use a value of arg2 to signal when to use the member variable?
A:
Yep, use a sentinel -- e.g.:
class Foo(object):
_sentinel = object()
def method(self, arg1=0, arg2=_sentinel):
if arg2 is self._sentinel: arg2 = self.member
...
...
note that you need barename _sentinel in the def, but self._sentinel in the body of the method (since that's how scoping works out in class bodies vs method bodies;-).
A:
def method(self, arg1=0, arg2=None):
if arg2 is None:
arg2 = self.member
...
|
Not Possible to Reference self in a Method Declaration?
|
I wanted to write a method with an argument that defaults to a member variable like so:
def method(self, arg1=0, arg2=self.member):
Apparently this is not allowed. Should I write it a different way, or perhaps use a value of arg2 to signal when to use the member variable?
|
[
"Yep, use a sentinel -- e.g.:\nclass Foo(object):\n _sentinel = object()\n def method(self, arg1=0, arg2=_sentinel):\n if arg2 is self._sentinel: arg2 = self.member\n ...\n ...\n\nnote that you need barename _sentinel in the def, but self._sentinel in the body of the method (since that's how scoping works out in class bodies vs method bodies;-).\n",
"def method(self, arg1=0, arg2=None):\n if arg2 is None:\n arg2 = self.member\n ...\n\n"
] |
[
5,
2
] |
[] |
[] |
[
"argument_passing",
"python"
] |
stackoverflow_0002580022_argument_passing_python.txt
|
Q:
Python initialization and circular reference counts
Can we initialize Python objects with statement like this:
a = b = c = None
It seems to me when I did a = b = c = list(), it will cause a circular reference count issue.
A:
There are no cycles in your code and even if there were, Python's garbage collector can handle a circular reference fine, so you don't ever need to worry about that.
However your code has another (possible) problem: All three variables will point to the same list. This means that changing, for example, a, will also change b and c (where by "changing" I mean calling a mutating operation like for example append. Reassigning a variable will not affect the other variables).
A:
Yes, you can do that. There is no circular reference in your code and even if there were, it wouldn't cause any problems as Python has a garbage collector that correctly handles cycles.
A:
No. That's equivalent to:
c = list()
b = c
a = b
There is no problem. Why did you think there would be an issue?
|
Python initialization and circular reference counts
|
Can we initialize Python objects with statement like this:
a = b = c = None
It seems to me when I did a = b = c = list(), it will cause a circular reference count issue.
|
[
"There are no cycles in your code and even if there were, Python's garbage collector can handle a circular reference fine, so you don't ever need to worry about that.\nHowever your code has another (possible) problem: All three variables will point to the same list. This means that changing, for example, a, will also change b and c (where by \"changing\" I mean calling a mutating operation like for example append. Reassigning a variable will not affect the other variables).\n",
"Yes, you can do that. There is no circular reference in your code and even if there were, it wouldn't cause any problems as Python has a garbage collector that correctly handles cycles.\n",
"No. That's equivalent to:\n\nc = list()\nb = c\na = b\n\nThere is no problem. Why did you think there would be an issue?\n"
] |
[
4,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002580218_python.txt
|
Q:
Python 2.5.2: remove what found between two lines that contain two concrete strings
is there any way to remove what found between two lines that contain two concrete strings?
I mean: I want to remove anything found between 'heaven' and 'hell' in a text file with this text:
I'm in heaven
foobar
I'm in hell
After executing the script/function I'm asking the text file will be empty.
A:
Use a flag to indicate whether you're writing or not.
from __future__ import with_statement
writing = True
with open('myfile.txt') as f:
with open('output.txt') as out:
for line in f:
if writing:
if "heaven" in line:
writing = False
else:
out.write(line)
elif "hell" in line:
writing = True
os.remove('myfile.txt')
os.rename('output.txt', 'myfile.txt')
EDIT
As extraneon pointed in the comments, the requirement is to remove the lines between two concrete strings. That means that if the second (closing) string is never found, nothing should be removed. That can be achieved by keeping a buffer of lines. The buffer gets discarded if the closing string "I'm in hell" is found, but if the end of file is reached without finding it, the whole contents must be written to the file.
Example:
I'm in heaven
foo
bar
Should keep the whole contents since there's no closing tag and the question says between two lines.
Here's an example to do that, for completion:
from __future__ import with_statement
writing = True
with open('myfile.txt') as f:
with open('output.txt') as out:
for line in f:
if writing:
if "heaven" in line:
writing = False
buffer = [line]
else:
out.write(line)
elif "hell" in line:
writing = True
else:
buffer.append(line)
else:
if not writing:
#There wasn't a closing "I'm in hell", so write buffer contents
out.writelines(buffer)
os.remove('myfile.txt')
os.rename('output.txt', 'myfile.txt')
A:
Looks like by "remove" you mean "rewrite the input file in-place" (or make it look like you're so doing;-), in which case fileinput.input helps:
import fileinput
writing = True
for line in fileinput.input(['thefile.txt'], inplace=True):
if writing:
if 'heaven' in line: writing = False
else: print line,
else:
if 'hell' in line: writing = True
A:
You could do something like the following with regular expressions. There are probably more efficient ways to do it since I'm still learning a lot of python, but this should work.
import re
f = open('hh_remove.txt')
lines = f.readlines()
pattern1 = re.compile("heaven",re.I)
pattern2 = re.compile("hell",re.I)
mark1 = False
mark2 = False
for i, line in enumerate(lines):
if pattern1.search(line) != None:
mark1 = True
set1 = i
if pattern2.search(line) != None:
mark2 = True
set2 = i+1
if ((mark1 == True) and (mark2 == True)):
del lines[set1:set2]
mark1 = False
mark2 = False
f.close()
out = open('hh_remove.txt','w')
out.write("".join(lines))
out.close()
|
Python 2.5.2: remove what found between two lines that contain two concrete strings
|
is there any way to remove what found between two lines that contain two concrete strings?
I mean: I want to remove anything found between 'heaven' and 'hell' in a text file with this text:
I'm in heaven
foobar
I'm in hell
After executing the script/function I'm asking the text file will be empty.
|
[
"Use a flag to indicate whether you're writing or not.\nfrom __future__ import with_statement\n\nwriting = True\n\nwith open('myfile.txt') as f:\n with open('output.txt') as out:\n for line in f:\n if writing:\n if \"heaven\" in line:\n writing = False\n else:\n out.write(line)\n elif \"hell\" in line:\n writing = True \nos.remove('myfile.txt')\nos.rename('output.txt', 'myfile.txt')\n\n\nEDIT\nAs extraneon pointed in the comments, the requirement is to remove the lines between two concrete strings. That means that if the second (closing) string is never found, nothing should be removed. That can be achieved by keeping a buffer of lines. The buffer gets discarded if the closing string \"I'm in hell\" is found, but if the end of file is reached without finding it, the whole contents must be written to the file.\nExample:\nI'm in heaven\nfoo\nbar\n\nShould keep the whole contents since there's no closing tag and the question says between two lines.\nHere's an example to do that, for completion:\nfrom __future__ import with_statement\n\nwriting = True\nwith open('myfile.txt') as f:\n with open('output.txt') as out:\n for line in f:\n if writing:\n if \"heaven\" in line:\n writing = False\n buffer = [line]\n else:\n out.write(line)\n elif \"hell\" in line:\n writing = True\n else:\n buffer.append(line)\n else:\n if not writing:\n #There wasn't a closing \"I'm in hell\", so write buffer contents\n out.writelines(buffer)\n\nos.remove('myfile.txt')\nos.rename('output.txt', 'myfile.txt')\n\n",
"Looks like by \"remove\" you mean \"rewrite the input file in-place\" (or make it look like you're so doing;-), in which case fileinput.input helps:\nimport fileinput\nwriting = True\nfor line in fileinput.input(['thefile.txt'], inplace=True):\n if writing:\n if 'heaven' in line: writing = False\n else: print line,\n else:\n if 'hell' in line: writing = True\n\n",
"You could do something like the following with regular expressions. There are probably more efficient ways to do it since I'm still learning a lot of python, but this should work. \nimport re\n\nf = open('hh_remove.txt')\nlines = f.readlines()\n\npattern1 = re.compile(\"heaven\",re.I)\npattern2 = re.compile(\"hell\",re.I)\n\nmark1 = False\nmark2 = False\n\nfor i, line in enumerate(lines):\n if pattern1.search(line) != None:\n mark1 = True\n set1 = i\n if pattern2.search(line) != None:\n mark2 = True\n set2 = i+1\n if ((mark1 == True) and (mark2 == True)):\n del lines[set1:set2]\n mark1 = False\n mark2 = False\n\nf.close()\nout = open('hh_remove.txt','w')\nout.write(\"\".join(lines))\nout.close()\n\n"
] |
[
3,
1,
0
] |
[
"I apologize but this sounds like a homework problem. We have a policy on these: https://meta.stackexchange.com/questions/10811/homework-on-stackoverflow\nHowever, what I can say is that the feature @nosklo wrote about is available in any Python 2.5.x (or newer), but you need to learn enough Python to enable it. :-)\nMy solution would involve using creating a new string with the undesired stuff stripped out using str.find() or str.index() (or some relative of those 2).\nBest of luck!\n",
"see below. I dont know if it's ok but It seems is working ok.\nimport re,fileinput,os\n\n\nfor path, dirs, files in os.walk(path):\n for filename in files:\n fullpath = os.path.join(path, filename)\n\n\n f = open(fullpath,'r')\n\n\n data = f.read()\n\n patter = re.compile('Im in heaven.*?Im in hell', re.I | re.S)\n data = patter.sub(\"\", data)\n\n f.close()\n\n f = open(fullpath, 'w')\n\n f.write(data)\n f.close()\n\nAnyway when i execute it, it leaves a blank line. I mean, if have this function:\npublic function preFetchAll(Doctrine_Event $event){ \n//Im in heaven\n$a = sfContext::getInstance()->getUser()->getAttribute(\"passw.formulario\");\nvar_dump($a);\n//Im in hell\nforeach ($this->_listeners as $listener) {\n $listener->preFetchAll($event);\n}\n}\n\nand i execute my script, i get this:\npublic function preFetchAll(Doctrine_Event $event){ \n\nforeach ($this->_listeners as $listener) {\n $listener->preFetchAll($event);\n}\n}\n\nAs you can see there is an empty line between \"public...\" and \"foreach...\". \nWhy?\nJavi\n"
] |
[
-1,
-1
] |
[
"lines",
"python"
] |
stackoverflow_0002579609_lines_python.txt
|
Q:
Syntax highlighting: rich text box control for .NET
I'm looking for a free control/component/library something like a rich text box for editing codes of python (or other languages.)
I like to have some features:
Highlight codes
Auto Indent
Line numbering
Defining new styles or rules of highlighting (for OpenType keywords)
Is there such a control? or I have to write my own?
A:
Have a look at ScintillaNET.
ScintillaNET is a powerful text editing control for Windows Forms applications and a managed wrapper around the versatile Scintilla Windows control. Created with the developer in mind, the ScintllaNET API makes it simple to add advanced text editing and syntax highlighting to your application or IDE (Integrated Developer Environment) .
A:
A commercial option is ActiPro Software's SyntaxEditor. The link is for a WPF version of the control. They also offer a WinForms version which I've used for XML editing - works very well.
From what I've read on the site, the WPF version supports ANTLR-generated lexer-parsers.
|
Syntax highlighting: rich text box control for .NET
|
I'm looking for a free control/component/library something like a rich text box for editing codes of python (or other languages.)
I like to have some features:
Highlight codes
Auto Indent
Line numbering
Defining new styles or rules of highlighting (for OpenType keywords)
Is there such a control? or I have to write my own?
|
[
"Have a look at ScintillaNET.\n\nScintillaNET is a powerful text editing control for Windows Forms applications and a managed wrapper around the versatile Scintilla Windows control. Created with the developer in mind, the ScintllaNET API makes it simple to add advanced text editing and syntax highlighting to your application or IDE (Integrated Developer Environment) .\n\n",
"A commercial option is ActiPro Software's SyntaxEditor. The link is for a WPF version of the control. They also offer a WinForms version which I've used for XML editing - works very well.\nFrom what I've read on the site, the WPF version supports ANTLR-generated lexer-parsers.\n"
] |
[
4,
1
] |
[] |
[] |
[
".net",
"components",
"controls",
"ironpython",
"python"
] |
stackoverflow_0002580374_.net_components_controls_ironpython_python.txt
|
Q:
Using BeautifulSoup's findAll to search html element's innerText to get same result as searching attributes?
For instance if I am searching by an element's attribute like id:
soup.findAll('span',{'id':re.compile("^score_")})
I get back a list of the whole span element that matches (which I like).
But if I try to search by the innerText of the html element like this:
soup.findAll('a',text = re.compile("discuss|comment"))
I get back only the innerText part of element back that matches instead of the whole element with tags and attributes like I would above.
Is this possible to do with out finding the match and then getting it's parent?
Thanks.
A:
You don't get back the text. You get a NavigableString with the text. That object has methods to go to the parent, etc.
from BeautifulSoup import BeautifulSoup
import re
soup = BeautifulSoup('<html><p>foo</p></html>')
r = soup.findAll('p', text=re.compile('foo'))
print r[0].parent
prints
<p>foo</p>
|
Using BeautifulSoup's findAll to search html element's innerText to get same result as searching attributes?
|
For instance if I am searching by an element's attribute like id:
soup.findAll('span',{'id':re.compile("^score_")})
I get back a list of the whole span element that matches (which I like).
But if I try to search by the innerText of the html element like this:
soup.findAll('a',text = re.compile("discuss|comment"))
I get back only the innerText part of element back that matches instead of the whole element with tags and attributes like I would above.
Is this possible to do with out finding the match and then getting it's parent?
Thanks.
|
[
"You don't get back the text. You get a NavigableString with the text. That object has methods to go to the parent, etc.\nfrom BeautifulSoup import BeautifulSoup\nimport re\n\nsoup = BeautifulSoup('<html><p>foo</p></html>')\n\nr = soup.findAll('p', text=re.compile('foo'))\n\nprint r[0].parent\n\nprints\n<p>foo</p>\n\n"
] |
[
6
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0002580507_beautifulsoup_python.txt
|
Q:
Blackjack game reshuffling problem-edited
I am trying to make a blackjack game where before each new round, the program checks to make sure that the deck has 7 cards per player. And if it doesn't, the deck clears, repopulates, and reshuffles. I have most of the problem down, but for some reason at the start of every deal it reshuffles the deck more than once, and I can't figure out why. Help, please.
Here's what I have so far:
(P.S. the imported cards and games modules aren't part of the problem, I'm fairly sure my problem lies in the deal() function of my BJ_Deck class.)
import cards, games
class BJ_Card(cards.Card):
""" A Blackjack Card. """
ACE_VALUE = 1
def get_value(self):
if self.is_face_up:
value = BJ_Card.RANKS.index(self.rank) + 1
if value > 10:
value = 10
else:
value = None
return value
value = property(get_value)
class BJ_Deck(cards.Deck):
""" A Blackjack Deck. """
def populate(self):
for suit in BJ_Card.SUITS:
for rank in BJ_Card.RANKS:
self.cards.append(BJ_Card(rank, suit))
def deal(self, hands, per_hand=1):
for rounds in range(per_hand):
if len(self.cards)>=7*(len(hands)):
print "Reshuffling the deck."
self.cards=[]
self.populate()
self.shuffle()
for hand in hands:
top_card=self.cards[0]
self.give(top_card, hand)
class BJ_Hand(cards.Hand):
""" A Blackjack Hand. """
def __init__(self, name):
super(BJ_Hand, self).__init__()
self.name = name
def __str__(self):
rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
if self.total:
rep += "(" + str(self.total) + ")"
return rep
def get_total(self):
# if a card in the hand has value of None, then total is None
for card in self.cards:
if not card.value:
return None
# add up card values, treat each Ace as 1
total = 0
for card in self.cards:
total += card.value
# determine if hand contains an Ace
contains_ace = False
for card in self.cards:
if card.value == BJ_Card.ACE_VALUE:
contains_ace = True
# if hand contains Ace and total is low enough, treat Ace as 11
if contains_ace and total <= 11:
# add only 10 since we've already added 1 for the Ace
total += 10
return total
total = property(get_total)
def is_busted(self):
return self.total > 21
class BJ_Player(BJ_Hand):
""" A Blackjack Player. """
def is_hitting(self):
response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ")
return response == "y"
def bust(self):
print self.name, "busts."
self.lose()
def lose(self):
print self.name, "loses."
def win(self):
print self.name, "wins."
def push(self):
print self.name, "pushes."
class BJ_Dealer(BJ_Hand):
""" A Blackjack Dealer. """
def is_hitting(self):
return self.total < 17
def bust(self):
print self.name, "busts."
def flip_first_card(self):
first_card = self.cards[0]
first_card.flip()
class BJ_Game(object):
""" A Blackjack Game. """
def __init__(self, names):
self.players = []
for name in names:
player = BJ_Player(name)
self.players.append(player)
self.dealer = BJ_Dealer("Dealer")
self.deck = BJ_Deck()
self.deck.populate()
self.deck.shuffle()
def get_still_playing(self):
remaining = []
for player in self.players:
if not player.is_busted():
remaining.append(player)
return remaining
# list of players still playing (not busted) this round
still_playing = property(get_still_playing)
def __additional_cards(self, player):
while not player.is_busted() and player.is_hitting():
self.deck.deal([player])
print player
if player.is_busted():
player.bust()
def play(self):
# deal initial 2 cards to everyone
self.deck.deal(self.players + [self.dealer], per_hand = 2)
self.dealer.flip_first_card() # hide dealer's first card
for player in self.players:
print player
print self.dealer
# deal additional cards to players
for player in self.players:
self.__additional_cards(player)
self.dealer.flip_first_card() # reveal dealer's first
if not self.still_playing:
# since all players have busted, just show the dealer's hand
print self.dealer
else:
# deal additional cards to dealer
print self.dealer
self.__additional_cards(self.dealer)
if self.dealer.is_busted():
# everyone still playing wins
for player in self.still_playing:
player.win()
else:
# compare each player still playing to dealer
for player in self.still_playing:
if player.total > self.dealer.total:
player.win()
elif player.total < self.dealer.total:
player.lose()
else:
player.push()
# remove everyone's cards
for player in self.players:
player.clear()
self.dealer.clear()
def main():
print "\t\tWelcome to Blackjack!\n"
names = []
number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
for i in range(number):
name = raw_input("Enter player name: ")
names.append(name)
print
game = BJ_Game(names)
again = None
while again != "n":
game.play()
again = games.ask_yes_no("\nDo you want to play again?: ")
main()
raw_input("\n\nPress the enter key to exit.")
Since someone decided to call this 'psychic-debugging', I'll go ahead and tell you what the modules are then.
Here's the cards module:
class Card(object):
""" A playing card. """
RANKS = ["A", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "J", "Q", "K"]
SUITS = ["c", "d", "h", "s"]
def __init__(self, rank, suit, face_up = True):
self.rank = rank
self.suit = suit
self.is_face_up = face_up
def __str__(self):
if self.is_face_up:
rep = self.rank + self.suit
else:
rep = "XX"
return rep
def flip(self):
self.is_face_up = not self.is_face_up
class Hand(object):
""" A hand of playing cards. """
def init(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + "\t"
else:
rep = "<empty>"
return rep
def clear(self):
self.cards = []
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand):
self.cards.remove(card)
other_hand.add(card)
class Deck(Hand):
""" A deck of playing cards. """
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank, suit))
def shuffle(self):
import random
random.shuffle(self.cards)
def deal(self, hands, per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card, hand)
else:
print "Can't continue deal. Out of cards!"
if name == "main":
print "This is a module with classes for playing cards."
raw_input("\n\nPress the enter key to exit.")
And here's the games module:
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = raw_input(question).lower()
return response
def ask_number(question, low, high):
"""Ask for a number within a range."""
response = None
while response not in range(low, high):
response = int(raw_input(question))
return response
if name == "main":
print "You ran this module directly (and did not 'import' it)."
raw_input("\n\nPress the enter key to exit.")
A:
You're checking it again and again, inside the loop, and while you distribute the cards, the deck is being reduced, I think (can't see the Deck.give method on your code to know for sure).
You probably want to check only once, move the check to outside the loop.
def deal(self, hands, per_hand=1):
for rounds in range(per_hand):
if len(self.cards) <= 7 * len(hands):
print "Reshuffling the deck."
self.cards = []
self.populate()
self.shuffle()
for hand in hands:
top_card=self.cards[0]
self.give(top_card, hand)
A:
for hand in hands:
Do you really want to run that logic for each hand?
A:
Nosklo pointed out one problem (checking it inside the loop) but there is a second problem.
the condition
if len(self.cards)>=7*(len(hands)):
is checking if the number of cards is greater than the number needed and if so,clears the deck, populates and shuffles.
When combined with the check inside the loop, it will repopulate and shuffle the deck every time it starts another round.
So you probably want something like:
if len(self.cards) <= 7*(len(hands)):
print "Reshuffling the deck."
self.cards=[]
self.populate()
self.shuffle()
for rounds in range(per_hand):
for hand in hands:
top_card=self.cards[0]
self.give(top_card, hand)
|
Blackjack game reshuffling problem-edited
|
I am trying to make a blackjack game where before each new round, the program checks to make sure that the deck has 7 cards per player. And if it doesn't, the deck clears, repopulates, and reshuffles. I have most of the problem down, but for some reason at the start of every deal it reshuffles the deck more than once, and I can't figure out why. Help, please.
Here's what I have so far:
(P.S. the imported cards and games modules aren't part of the problem, I'm fairly sure my problem lies in the deal() function of my BJ_Deck class.)
import cards, games
class BJ_Card(cards.Card):
""" A Blackjack Card. """
ACE_VALUE = 1
def get_value(self):
if self.is_face_up:
value = BJ_Card.RANKS.index(self.rank) + 1
if value > 10:
value = 10
else:
value = None
return value
value = property(get_value)
class BJ_Deck(cards.Deck):
""" A Blackjack Deck. """
def populate(self):
for suit in BJ_Card.SUITS:
for rank in BJ_Card.RANKS:
self.cards.append(BJ_Card(rank, suit))
def deal(self, hands, per_hand=1):
for rounds in range(per_hand):
if len(self.cards)>=7*(len(hands)):
print "Reshuffling the deck."
self.cards=[]
self.populate()
self.shuffle()
for hand in hands:
top_card=self.cards[0]
self.give(top_card, hand)
class BJ_Hand(cards.Hand):
""" A Blackjack Hand. """
def __init__(self, name):
super(BJ_Hand, self).__init__()
self.name = name
def __str__(self):
rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
if self.total:
rep += "(" + str(self.total) + ")"
return rep
def get_total(self):
# if a card in the hand has value of None, then total is None
for card in self.cards:
if not card.value:
return None
# add up card values, treat each Ace as 1
total = 0
for card in self.cards:
total += card.value
# determine if hand contains an Ace
contains_ace = False
for card in self.cards:
if card.value == BJ_Card.ACE_VALUE:
contains_ace = True
# if hand contains Ace and total is low enough, treat Ace as 11
if contains_ace and total <= 11:
# add only 10 since we've already added 1 for the Ace
total += 10
return total
total = property(get_total)
def is_busted(self):
return self.total > 21
class BJ_Player(BJ_Hand):
""" A Blackjack Player. """
def is_hitting(self):
response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ")
return response == "y"
def bust(self):
print self.name, "busts."
self.lose()
def lose(self):
print self.name, "loses."
def win(self):
print self.name, "wins."
def push(self):
print self.name, "pushes."
class BJ_Dealer(BJ_Hand):
""" A Blackjack Dealer. """
def is_hitting(self):
return self.total < 17
def bust(self):
print self.name, "busts."
def flip_first_card(self):
first_card = self.cards[0]
first_card.flip()
class BJ_Game(object):
""" A Blackjack Game. """
def __init__(self, names):
self.players = []
for name in names:
player = BJ_Player(name)
self.players.append(player)
self.dealer = BJ_Dealer("Dealer")
self.deck = BJ_Deck()
self.deck.populate()
self.deck.shuffle()
def get_still_playing(self):
remaining = []
for player in self.players:
if not player.is_busted():
remaining.append(player)
return remaining
# list of players still playing (not busted) this round
still_playing = property(get_still_playing)
def __additional_cards(self, player):
while not player.is_busted() and player.is_hitting():
self.deck.deal([player])
print player
if player.is_busted():
player.bust()
def play(self):
# deal initial 2 cards to everyone
self.deck.deal(self.players + [self.dealer], per_hand = 2)
self.dealer.flip_first_card() # hide dealer's first card
for player in self.players:
print player
print self.dealer
# deal additional cards to players
for player in self.players:
self.__additional_cards(player)
self.dealer.flip_first_card() # reveal dealer's first
if not self.still_playing:
# since all players have busted, just show the dealer's hand
print self.dealer
else:
# deal additional cards to dealer
print self.dealer
self.__additional_cards(self.dealer)
if self.dealer.is_busted():
# everyone still playing wins
for player in self.still_playing:
player.win()
else:
# compare each player still playing to dealer
for player in self.still_playing:
if player.total > self.dealer.total:
player.win()
elif player.total < self.dealer.total:
player.lose()
else:
player.push()
# remove everyone's cards
for player in self.players:
player.clear()
self.dealer.clear()
def main():
print "\t\tWelcome to Blackjack!\n"
names = []
number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
for i in range(number):
name = raw_input("Enter player name: ")
names.append(name)
print
game = BJ_Game(names)
again = None
while again != "n":
game.play()
again = games.ask_yes_no("\nDo you want to play again?: ")
main()
raw_input("\n\nPress the enter key to exit.")
Since someone decided to call this 'psychic-debugging', I'll go ahead and tell you what the modules are then.
Here's the cards module:
class Card(object):
""" A playing card. """
RANKS = ["A", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "J", "Q", "K"]
SUITS = ["c", "d", "h", "s"]
def __init__(self, rank, suit, face_up = True):
self.rank = rank
self.suit = suit
self.is_face_up = face_up
def __str__(self):
if self.is_face_up:
rep = self.rank + self.suit
else:
rep = "XX"
return rep
def flip(self):
self.is_face_up = not self.is_face_up
class Hand(object):
""" A hand of playing cards. """
def init(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + "\t"
else:
rep = "<empty>"
return rep
def clear(self):
self.cards = []
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand):
self.cards.remove(card)
other_hand.add(card)
class Deck(Hand):
""" A deck of playing cards. """
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank, suit))
def shuffle(self):
import random
random.shuffle(self.cards)
def deal(self, hands, per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card, hand)
else:
print "Can't continue deal. Out of cards!"
if name == "main":
print "This is a module with classes for playing cards."
raw_input("\n\nPress the enter key to exit.")
And here's the games module:
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = raw_input(question).lower()
return response
def ask_number(question, low, high):
"""Ask for a number within a range."""
response = None
while response not in range(low, high):
response = int(raw_input(question))
return response
if name == "main":
print "You ran this module directly (and did not 'import' it)."
raw_input("\n\nPress the enter key to exit.")
|
[
"You're checking it again and again, inside the loop, and while you distribute the cards, the deck is being reduced, I think (can't see the Deck.give method on your code to know for sure).\nYou probably want to check only once, move the check to outside the loop.\ndef deal(self, hands, per_hand=1):\n for rounds in range(per_hand):\n if len(self.cards) <= 7 * len(hands):\n print \"Reshuffling the deck.\"\n self.cards = []\n self.populate()\n self.shuffle()\n for hand in hands:\n top_card=self.cards[0]\n self.give(top_card, hand)\n\n",
"for hand in hands:\nDo you really want to run that logic for each hand?\n",
"Nosklo pointed out one problem (checking it inside the loop) but there is a second problem.\nthe condition\nif len(self.cards)>=7*(len(hands)):\n\nis checking if the number of cards is greater than the number needed and if so,clears the deck, populates and shuffles.\nWhen combined with the check inside the loop, it will repopulate and shuffle the deck every time it starts another round.\nSo you probably want something like:\n if len(self.cards) <= 7*(len(hands)):\n print \"Reshuffling the deck.\"\n self.cards=[]\n self.populate()\n self.shuffle()\n for rounds in range(per_hand):\n for hand in hands:\n top_card=self.cards[0]\n self.give(top_card, hand)\n\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002577047_python.txt
|
Q:
Unittest in Django. What is relationship between TestCase class and method
I am doing some unit testing stuff in Django. What is the relationship between TestCase class and the actual method in this class? What is the best practice for organizing these stuff?
For example, I have
class Test(TestCase):
def __init__(self):
...
def testTestA(self):
#test code
def testTestB(self):
#test code
If I organize in this way:
class Test1(TestCase):
def __init__(self):
...
def testTestA(self):
#test code
class Test2(TestCase):
def __init__(self):
...
def testTestB(self):
...
Which is better and what is the difference?
Thanks!
A:
You rarely write __init__ for a TestCase. So strike that from your mental model of unit testing.
You sometimes write a setUp and tearDown. Django automates much of this, however, and you often merely provide a static fixtures= variable that's used to populate the test database.
More fundamentally, what's a test case?
A test case is a "fixture" -- a configuration of a unit under test -- that you can then exercise. Ideally each TestCase has a setUp method that creates one fixture. Each method will perform a manipulation on that fixture and assert that the manipulation worked.
However. There's nothing dogmatic about that.
In many cases -- particularly when exercising Django models -- where there just aren't that many interesting manipulations.
If you don't override save in a model, you don't really need to do CRUD testing. You can (and should) trust the ORM. [If you don't trust it, then get a new framework that you do trust.]
If you have a few properties in a models class, you might not want to create a distinct method to test each property. You might want to simply test them sequentially in a single method of a single TestCase.
If, OTOH, you have really complex class with lots of state changes, you will need a distinct TestCase to configure an object is one state, manipulate it into another state and assert that the changes all behaved correctly.
View Functions, since they aren't -- technically -- stateful, don't match the Unit Test philosophy perfectly. When doing setUp to create a unit in a known state, you're using the client interface to step through some interactions to create a session in a known state. Once the session has reached as desired state, then your various test methods will exercise that session, and assert that things worked.
Summary
Think of TestCase as a "Setup" or "Context" in which tests will be run.
Think of each method as "when_X_should_Y" statement. Some folks suggest that kind of name ("test_when_x_should_y") So the method will perform "X" and assert that "Y" was the response.
A:
It's kind of hard to answer this question regarding the proper organization of cases A and B and test methods 1, 2 and 3...
However splitting the tests to test cases serves two major purposes:
1) Organizing the tests around some logical groups, such as CustomerViewTests, OrdersAggregationTests, etc.
2) Sharing the same setUp() and tearDown() methods, for tests which require the same, well, setup and tear down.
More information and examples can be found at unitTest documentation.
|
Unittest in Django. What is relationship between TestCase class and method
|
I am doing some unit testing stuff in Django. What is the relationship between TestCase class and the actual method in this class? What is the best practice for organizing these stuff?
For example, I have
class Test(TestCase):
def __init__(self):
...
def testTestA(self):
#test code
def testTestB(self):
#test code
If I organize in this way:
class Test1(TestCase):
def __init__(self):
...
def testTestA(self):
#test code
class Test2(TestCase):
def __init__(self):
...
def testTestB(self):
...
Which is better and what is the difference?
Thanks!
|
[
"\nYou rarely write __init__ for a TestCase. So strike that from your mental model of unit testing.\nYou sometimes write a setUp and tearDown. Django automates much of this, however, and you often merely provide a static fixtures= variable that's used to populate the test database.\n\nMore fundamentally, what's a test case?\nA test case is a \"fixture\" -- a configuration of a unit under test -- that you can then exercise. Ideally each TestCase has a setUp method that creates one fixture. Each method will perform a manipulation on that fixture and assert that the manipulation worked.\nHowever. There's nothing dogmatic about that.\nIn many cases -- particularly when exercising Django models -- where there just aren't that many interesting manipulations.\nIf you don't override save in a model, you don't really need to do CRUD testing. You can (and should) trust the ORM. [If you don't trust it, then get a new framework that you do trust.]\nIf you have a few properties in a models class, you might not want to create a distinct method to test each property. You might want to simply test them sequentially in a single method of a single TestCase.\nIf, OTOH, you have really complex class with lots of state changes, you will need a distinct TestCase to configure an object is one state, manipulate it into another state and assert that the changes all behaved correctly.\nView Functions, since they aren't -- technically -- stateful, don't match the Unit Test philosophy perfectly. When doing setUp to create a unit in a known state, you're using the client interface to step through some interactions to create a session in a known state. Once the session has reached as desired state, then your various test methods will exercise that session, and assert that things worked.\nSummary\nThink of TestCase as a \"Setup\" or \"Context\" in which tests will be run.\nThink of each method as \"when_X_should_Y\" statement. Some folks suggest that kind of name (\"test_when_x_should_y\") So the method will perform \"X\" and assert that \"Y\" was the response.\n",
"It's kind of hard to answer this question regarding the proper organization of cases A and B and test methods 1, 2 and 3...\nHowever splitting the tests to test cases serves two major purposes:\n1) Organizing the tests around some logical groups, such as CustomerViewTests, OrdersAggregationTests, etc.\n2) Sharing the same setUp() and tearDown() methods, for tests which require the same, well, setup and tear down.\nMore information and examples can be found at unitTest documentation.\n"
] |
[
8,
1
] |
[] |
[] |
[
"django",
"python",
"unit_testing"
] |
stackoverflow_0002580519_django_python_unit_testing.txt
|
Q:
Unittest in Django. Static variable feeded into the test case
I want to generate some dynamic data and feed these data in to test cases. But I found that Django will initial the test class every time to do the test. So the data will get generated every time django test framework calls the function.
Is there anyway to use something like the singleton or static variable to solve the problem? What should be the solution?
Thanks!
A:
This is normal unittest behavior, though you would normally set up the test data in the setUp() method instead of __init__ (and destroy it in tearDown() perhaps).
If generating your dynamic test data takes to long to perform for each test case method, then I guess the best way to go is to create a singleton test data class. In this case you would have to take care that each test method leaves the test data class in exactly the same state it found it, which is not trivial if you want your test case methods to write something in it; this is the reason why unittest try to re-generate the test environment for every test case method.
One improvement might be to have the singleton test data class return a deep-copy of itself every time you request it's instance.
|
Unittest in Django. Static variable feeded into the test case
|
I want to generate some dynamic data and feed these data in to test cases. But I found that Django will initial the test class every time to do the test. So the data will get generated every time django test framework calls the function.
Is there anyway to use something like the singleton or static variable to solve the problem? What should be the solution?
Thanks!
|
[
"This is normal unittest behavior, though you would normally set up the test data in the setUp() method instead of __init__ (and destroy it in tearDown() perhaps). \nIf generating your dynamic test data takes to long to perform for each test case method, then I guess the best way to go is to create a singleton test data class. In this case you would have to take care that each test method leaves the test data class in exactly the same state it found it, which is not trivial if you want your test case methods to write something in it; this is the reason why unittest try to re-generate the test environment for every test case method.\nOne improvement might be to have the singleton test data class return a deep-copy of itself every time you request it's instance.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"python",
"unit_testing"
] |
stackoverflow_0002580648_django_python_unit_testing.txt
|
Q:
Pythonic mapping of an array (Beginner)
I've got a question related to a beginner Python snippet I've written to introduce myself to the language. It's an admittedly trivial early effort, but I'm still wondering how I could have written it more elegantly.
The program outputs NATO phoenetic readable versions of an argument, such "H2O" -> "Hotel 2 Oscar", or (lacking an argument) just outputs the whole alphabet. I mainly use it for calling in MAC addresses and IQNs, but it's useful for other phone support too.
Here's the body of the relevant portion of the program:
#!/usr/bin/env python
import sys
nato = {
"a": 'Alfa',
"b": 'Bravo',
"c": 'Charlie',
"d": 'Delta',
"e": 'Echo',
"f": 'Foxtrot',
"g": 'Golf',
"h": 'Hotel',
"i": 'India',
"j": 'Juliet',
"k": 'Kilo',
"l": 'Lima',
"m": 'Mike',
"n": 'November',
"o": 'Oscar',
"p": 'Papa',
"q": 'Quebec',
"r": 'Romeo',
"s": 'Sierra',
"t": 'Tango',
"u": 'Uniform',
"v": 'Victor',
"w": 'Whiskey',
"x": 'Xray',
"y": 'Yankee',
"z": 'Zulu',
}
if len(sys.argv) < 2:
for n in nato.keys():
print nato[n]
else:
# if sys.argv[1] == "-i" # TODO
for char in sys.argv[1].lower():
if char in nato:
print nato[char],
else: print char,
As I mentioned, I just want to see suggestions for a more elegant way to code this.
My first guess was to use a list comprehension along the lines of [nato[x] for x in sys.argv[1].lower() if x in nato], but that doesn't allow me to output any non-alphabetic characters.
My next guess was to use map, but I couldn't format any lambdas that didn't suffer from the same corner case.
Any suggestions? Maybe something with first-class functions? Messing with Array's guts?
This seems like it could almost be a Code Golf question, but I feel like I'm just overthinking :)
A:
The dict get with default perhaps?
for char in sys.argv[1].lower():
print nato.get(char, char) # try to get nato[char] otherwise return char
A:
Using the above suggestion and a generator expression to do it all in one line
print ' '.join(nato.get(c,c) for c in sys.argv[1].lower())
A:
Here's a compact way of building your list:
import sys
import string
NATO = '''Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet
Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform
Victor Whiskey X-Ray Yankee Zulu'''.split()
nato = dict(zip(string.lowercase,NATO))
if len(sys.argv) < 2:
for n in nato:
print n,nato[n]
else:
for char in sys.argv[1].lower():
print nato.get(char,char)
|
Pythonic mapping of an array (Beginner)
|
I've got a question related to a beginner Python snippet I've written to introduce myself to the language. It's an admittedly trivial early effort, but I'm still wondering how I could have written it more elegantly.
The program outputs NATO phoenetic readable versions of an argument, such "H2O" -> "Hotel 2 Oscar", or (lacking an argument) just outputs the whole alphabet. I mainly use it for calling in MAC addresses and IQNs, but it's useful for other phone support too.
Here's the body of the relevant portion of the program:
#!/usr/bin/env python
import sys
nato = {
"a": 'Alfa',
"b": 'Bravo',
"c": 'Charlie',
"d": 'Delta',
"e": 'Echo',
"f": 'Foxtrot',
"g": 'Golf',
"h": 'Hotel',
"i": 'India',
"j": 'Juliet',
"k": 'Kilo',
"l": 'Lima',
"m": 'Mike',
"n": 'November',
"o": 'Oscar',
"p": 'Papa',
"q": 'Quebec',
"r": 'Romeo',
"s": 'Sierra',
"t": 'Tango',
"u": 'Uniform',
"v": 'Victor',
"w": 'Whiskey',
"x": 'Xray',
"y": 'Yankee',
"z": 'Zulu',
}
if len(sys.argv) < 2:
for n in nato.keys():
print nato[n]
else:
# if sys.argv[1] == "-i" # TODO
for char in sys.argv[1].lower():
if char in nato:
print nato[char],
else: print char,
As I mentioned, I just want to see suggestions for a more elegant way to code this.
My first guess was to use a list comprehension along the lines of [nato[x] for x in sys.argv[1].lower() if x in nato], but that doesn't allow me to output any non-alphabetic characters.
My next guess was to use map, but I couldn't format any lambdas that didn't suffer from the same corner case.
Any suggestions? Maybe something with first-class functions? Messing with Array's guts?
This seems like it could almost be a Code Golf question, but I feel like I'm just overthinking :)
|
[
"The dict get with default perhaps?\nfor char in sys.argv[1].lower():\n print nato.get(char, char) # try to get nato[char] otherwise return char\n\n",
"Using the above suggestion and a generator expression to do it all in one line\nprint ' '.join(nato.get(c,c) for c in sys.argv[1].lower())\n\n",
"Here's a compact way of building your list:\nimport sys\nimport string\n\nNATO = '''Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet\nKilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform\nVictor Whiskey X-Ray Yankee Zulu'''.split()\n\nnato = dict(zip(string.lowercase,NATO))\n\nif len(sys.argv) < 2:\n for n in nato:\n print n,nato[n]\nelse:\n for char in sys.argv[1].lower():\n print nato.get(char,char)\n\n"
] |
[
5,
3,
2
] |
[] |
[] |
[
"arrays",
"python"
] |
stackoverflow_0002580802_arrays_python.txt
|
Q:
Parsing text file in python
I have html-file. I have to replace all text between this: [%anytext%]. As I understand, it's very easy to do with BeautifulSoup for parsing hmtl. But what is regular expression and how to remove&write back text data?
Okay, here is the sample file:
<html>
[t1] [t2] ... [tood] ... [sadsada]
Sample text [i8]
[d9]
</html>
Python script must work with all strings and replace [%] -> some another string, for example:
<html>
* * ... * ... *
Sample text *
*
</html>
What I did:
import re
import codecs
fullData = ''
for line in codecs.open(u'test.txt', encoding='utf-8'):
line = re.sub("\[.*?\]", '*', line)
fullData += line
print fullData
This code does exactly I described in sample. Thanks all.
A:
Looks like you need to parse a generic textfile, looking for that marker to replace it -- the fact that other text outside the marker is HTML, at least from the way you phrased your task, does not seem to matter.
If so, and what you want is to replace every occurrence of [%anytext%] with loremipsum, then a simple:
thenew = theold.replace('[%anytext%]', 'loremipsum')
will serve, if theold is the original string containing the file's text -- now thenew is a new string with all occurrences of that marker replaced - no need for regex, BS or anything else.
If your task is very different from this, pls edit your Question to explain it in more detail!-)
A:
Regex does the trick if you are needing to replace any text between "[%" and "%]".
The code would look something like this:
import re
newstring = re.sub("\[%.*?%\]",newtext,oldstring)
The regex used here is lazy so it would match everything between an occurrence of "[%" and the next occurrence of "%]". You could make it greedy by removing the question mark. This would match everything between the first occurrence of of "[%" and the last occurrence of "%]"
|
Parsing text file in python
|
I have html-file. I have to replace all text between this: [%anytext%]. As I understand, it's very easy to do with BeautifulSoup for parsing hmtl. But what is regular expression and how to remove&write back text data?
Okay, here is the sample file:
<html>
[t1] [t2] ... [tood] ... [sadsada]
Sample text [i8]
[d9]
</html>
Python script must work with all strings and replace [%] -> some another string, for example:
<html>
* * ... * ... *
Sample text *
*
</html>
What I did:
import re
import codecs
fullData = ''
for line in codecs.open(u'test.txt', encoding='utf-8'):
line = re.sub("\[.*?\]", '*', line)
fullData += line
print fullData
This code does exactly I described in sample. Thanks all.
|
[
"Looks like you need to parse a generic textfile, looking for that marker to replace it -- the fact that other text outside the marker is HTML, at least from the way you phrased your task, does not seem to matter.\nIf so, and what you want is to replace every occurrence of [%anytext%] with loremipsum, then a simple:\nthenew = theold.replace('[%anytext%]', 'loremipsum')\n\nwill serve, if theold is the original string containing the file's text -- now thenew is a new string with all occurrences of that marker replaced - no need for regex, BS or anything else.\nIf your task is very different from this, pls edit your Question to explain it in more detail!-)\n",
"Regex does the trick if you are needing to replace any text between \"[%\" and \"%]\".\nThe code would look something like this:\nimport re\n\n\nnewstring = re.sub(\"\\[%.*?%\\]\",newtext,oldstring)\n\nThe regex used here is lazy so it would match everything between an occurrence of \"[%\" and the next occurrence of \"%]\". You could make it greedy by removing the question mark. This would match everything between the first occurrence of of \"[%\" and the last occurrence of \"%]\"\n"
] |
[
2,
2
] |
[] |
[] |
[
"html",
"parsing",
"python"
] |
stackoverflow_0002580841_html_parsing_python.txt
|
Q:
Live Updating Widget for 100+ concurrent users
what would you use if you had to have a div box on your website that would have to be updated constantly with new HTML content from the server.
simple polling is probably not very resource inefficient - imagine also having 10'000 users and the div has to update.
what is the most efficient or elegant solution for such a problem?
are there existing widgets which contain this "autoupdate" functionality?
A:
Consider using memcached. By caching content in memory
you will reduce the number of calls to the (database?) server that generates the content.
To keep the content up to date you should use the memcache pattern. A short expiration time will provide more up to date content, a long expiration time will provide better performance.
|
Live Updating Widget for 100+ concurrent users
|
what would you use if you had to have a div box on your website that would have to be updated constantly with new HTML content from the server.
simple polling is probably not very resource inefficient - imagine also having 10'000 users and the div has to update.
what is the most efficient or elegant solution for such a problem?
are there existing widgets which contain this "autoupdate" functionality?
|
[
"Consider using memcached. By caching content in memory\nyou will reduce the number of calls to the (database?) server that generates the content. \nTo keep the content up to date you should use the memcache pattern. A short expiration time will provide more up to date content, a long expiration time will provide better performance.\n"
] |
[
1
] |
[] |
[] |
[
"comet",
"python",
"scaling",
"tornado"
] |
stackoverflow_0002580669_comet_python_scaling_tornado.txt
|
Q:
Passing string with (accidental) escape character loses character even though it's a raw string
I have a function with a python doctest that fails because one of the test input strings has a backslash that's treated like an escape character even though I've encoded the string as a raw string.
My doctest looks like this:
>>> infile = [ "Todo: fix me", "/** todo: fix", "* me", "*/", r"""//\todo stuff to fix""", "TODO fix me too", "toDo bug 4663" ]
>>> find_todos( infile )
['fix me', 'fix', 'stuff to fix', 'fix me too', 'bug 4663']
And the function, which is intended to extract the todo texts from a single line following some variation over a todo specification, looks like this:
todos = list()
for line in infile:
print line
if todo_match_obj.search( line ):
todos.append( todo_match_obj.search( line ).group( 'todo' ) )
And the regular expression called todo_match_obj is:
r"""(?:/{0,2}\**\s?todo):?\s*(?P<todo>.+)"""
A quick conversation with my ipython shell gives me:
In [35]: print "//\todo"
// odo
In [36]: print r"""//\todo"""
//\todo
And, just in case the doctest implementation uses stdout (I haven't checked, sorry):
In [37]: sys.stdout.write( r"""//\todo""" )
//\todo
My regex-foo is not high by any standards, and I realize that I could be missing something here.
EDIT: Following Alex Martellis answer, I would like suggestions on what regular expression would actually match the blasted r"""//\todo fix me""". I know that I did not originally ask for someone to do my homework, and I will accept Alex's answer as it really did answer my question (or confirm my fears). But I promise to upvote any good solutions to my problem here :)
EDITEDIT: for reference, a bug has been filed with the kodos project: bug #437633
I'm using Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
Thank you for reading this far (If you skipped directly down here, I understand)
A:
Read your original regex carefully:
r"""(?:/{0,2}\**\s?todo):?\s*(?P<todo>.+)"""
It matches: zero to two slashes, then 0+ stars, then 0 or 1 "whitespace characters" (blanks, tabs etc), then the literal characters 'todo' (and so on).
Your rawstring is:
r"""//\todo stuff to fix"""
so there's a literal backslash between the slashes and the 'todo', therefore of course the regex doesn't match it. It can't -- nowhere in that regex are you expressing any desire to optionally match a literal backslash.
Edit:
A RE pattern, very close to yours, that would accept and ignore an optional backslash right before the 't' would be:
r"""(?:/{0,2}\**\s?\\?todo):?\s*(?P<todo>.+)"""
note that the backslash does have to be repeated, to "escape itself", in this case.
A:
This gets even more strange as I venture down the road of doctests.
Consider this python script.
If you uncomment the lines 22 and 23, the script passes just fine, as the method returns True, which is both asserted and explicitly compared.
But if you run the file as it stands in the link, the doctest will fail with the message:
% python doctest_test.py
**********************************************************************
File "doctest_test.py", line 3, in __main__.doctest_test
Failed example:
doctest_test( r"""// odo""" )
Exception raised:
Traceback (most recent call last):
File "/usr/lib/python2.6/doctest.py", line 1241, in __run
compileflags, 1) in test.globs
File "<doctest __main__.doctest_test[0]>", line 1, in <module>
doctest_test( r"""// odo""" )
File "doctest_test.py", line 14, in doctest_test
assert input_string == compare_string
AssertionError
**********************************************************************
1 items had failures:
1 of 1 in __main__.doctest_test
***Test Failed*** 1 failures.
Can someone enlighten me here?
I'm still using python 2.6.4 for this.
I'm placing this answer under 'community wiki', as it really does not reputation-wise relate to the question.
|
Passing string with (accidental) escape character loses character even though it's a raw string
|
I have a function with a python doctest that fails because one of the test input strings has a backslash that's treated like an escape character even though I've encoded the string as a raw string.
My doctest looks like this:
>>> infile = [ "Todo: fix me", "/** todo: fix", "* me", "*/", r"""//\todo stuff to fix""", "TODO fix me too", "toDo bug 4663" ]
>>> find_todos( infile )
['fix me', 'fix', 'stuff to fix', 'fix me too', 'bug 4663']
And the function, which is intended to extract the todo texts from a single line following some variation over a todo specification, looks like this:
todos = list()
for line in infile:
print line
if todo_match_obj.search( line ):
todos.append( todo_match_obj.search( line ).group( 'todo' ) )
And the regular expression called todo_match_obj is:
r"""(?:/{0,2}\**\s?todo):?\s*(?P<todo>.+)"""
A quick conversation with my ipython shell gives me:
In [35]: print "//\todo"
// odo
In [36]: print r"""//\todo"""
//\todo
And, just in case the doctest implementation uses stdout (I haven't checked, sorry):
In [37]: sys.stdout.write( r"""//\todo""" )
//\todo
My regex-foo is not high by any standards, and I realize that I could be missing something here.
EDIT: Following Alex Martellis answer, I would like suggestions on what regular expression would actually match the blasted r"""//\todo fix me""". I know that I did not originally ask for someone to do my homework, and I will accept Alex's answer as it really did answer my question (or confirm my fears). But I promise to upvote any good solutions to my problem here :)
EDITEDIT: for reference, a bug has been filed with the kodos project: bug #437633
I'm using Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
Thank you for reading this far (If you skipped directly down here, I understand)
|
[
"Read your original regex carefully:\nr\"\"\"(?:/{0,2}\\**\\s?todo):?\\s*(?P<todo>.+)\"\"\"\n\nIt matches: zero to two slashes, then 0+ stars, then 0 or 1 \"whitespace characters\" (blanks, tabs etc), then the literal characters 'todo' (and so on).\nYour rawstring is:\nr\"\"\"//\\todo stuff to fix\"\"\"\n\nso there's a literal backslash between the slashes and the 'todo', therefore of course the regex doesn't match it. It can't -- nowhere in that regex are you expressing any desire to optionally match a literal backslash.\nEdit:\nA RE pattern, very close to yours, that would accept and ignore an optional backslash right before the 't' would be:\nr\"\"\"(?:/{0,2}\\**\\s?\\\\?todo):?\\s*(?P<todo>.+)\"\"\"\n\nnote that the backslash does have to be repeated, to \"escape itself\", in this case.\n",
"This gets even more strange as I venture down the road of doctests.\nConsider this python script.\nIf you uncomment the lines 22 and 23, the script passes just fine, as the method returns True, which is both asserted and explicitly compared.\nBut if you run the file as it stands in the link, the doctest will fail with the message:\n% python doctest_test.py \n**********************************************************************\nFile \"doctest_test.py\", line 3, in __main__.doctest_test\nFailed example:\n doctest_test( r\"\"\"// odo\"\"\" )\nException raised:\n Traceback (most recent call last):\n File \"/usr/lib/python2.6/doctest.py\", line 1241, in __run\n compileflags, 1) in test.globs\n File \"<doctest __main__.doctest_test[0]>\", line 1, in <module>\n doctest_test( r\"\"\"// odo\"\"\" )\n File \"doctest_test.py\", line 14, in doctest_test\n assert input_string == compare_string\n AssertionError\n**********************************************************************\n1 items had failures:\n 1 of 1 in __main__.doctest_test\n***Test Failed*** 1 failures.\n\nCan someone enlighten me here?\nI'm still using python 2.6.4 for this.\nI'm placing this answer under 'community wiki', as it really does not reputation-wise relate to the question.\n"
] |
[
2,
1
] |
[] |
[] |
[
"doctest",
"escaping",
"python",
"rawstring",
"regex"
] |
stackoverflow_0002580654_doctest_escaping_python_rawstring_regex.txt
|
Q:
How can I load an MP3 or similar music file for display and analysis in wxWidgets?
I'm developing a GUI in wxPython which allows a user to generate sequences of colours for some toys I'm building. Part of the program needs to load an MP3 (and potentially other formats further down the line) and display it to the user. That should be sufficient to get started but later I'd like to add features like identifying beats and some crude frequency analysis.
Is there any simple way of loading / understanding an MP3's contents to display a plot of its amplitudes to the screen using wxWidgets?
I later intend to port to C++/wxWidgets for speed and to avoid having to distribute wxPython.
A:
It looks like Snack could be a good start. I've not used it.
edit: It's Tk based, but perhaps there are parts or ideas to be taken.
A:
After a little more googling, I think PyMedia might well be a good place to start at least as far as a Python implementation goes.
|
How can I load an MP3 or similar music file for display and analysis in wxWidgets?
|
I'm developing a GUI in wxPython which allows a user to generate sequences of colours for some toys I'm building. Part of the program needs to load an MP3 (and potentially other formats further down the line) and display it to the user. That should be sufficient to get started but later I'd like to add features like identifying beats and some crude frequency analysis.
Is there any simple way of loading / understanding an MP3's contents to display a plot of its amplitudes to the screen using wxWidgets?
I later intend to port to C++/wxWidgets for speed and to avoid having to distribute wxPython.
|
[
"It looks like Snack could be a good start. I've not used it.\nedit: It's Tk based, but perhaps there are parts or ideas to be taken.\n",
"After a little more googling, I think PyMedia might well be a good place to start at least as far as a Python implementation goes.\n"
] |
[
1,
1
] |
[] |
[] |
[
"analysis",
"c++",
"mp3",
"python",
"wxwidgets"
] |
stackoverflow_0002574183_analysis_c++_mp3_python_wxwidgets.txt
|
Q:
Getting data from external program
I need a method to get the data from an external editor.
def _get_content():
from subprocess import call
file = open(file, "w").write(some_name)
call(editor + " " + file, shell=True)
file.close()
file = open(file)
x = file.readlines()
[snip]
I personally think there should be a more elegant way. You see, I need to interact with an external editor and get the data.
Do you know any better approaches/have better ideas?
EDIT:
Marcelo brought me on the idea of using tempfile for doing that.
Here's how I do it:
def _tempfile_write(input):
from tempfile import NamedTemporaryFile
x = NamedTemporaryFile()
x.file.write(input)
x.close()
y = open(x)
[snip]
This does the job, but also not quite satisfying. Heard something about spawning?..
A:
This is the way all programs do it, AFAIK. Certainly all version control systems that I've used create a temporary file, pass it to the editor and retrieve the result when the editor exits, just as you have.
A:
I'd recommend using a list, not a string:
def _get_content(editor, initial=""):
from subprocess import call
from tempfile import NamedTemporaryFile
# Create the initial temporary file.
with NamedTemporaryFile(delete=False) as tf:
tfName = tf.name
tf.write(initial)
# Fire up the editor.
if call([editor, tfName]) != 0:
return None # Editor died or was killed.
# Get the modified content.
with open(tfName).readlines() as result:
os.remove(tfName)
return result
A:
an editor just lets you edit a file interactively. you can also edit files with Python. there's no need to call external editor.
for line in open("file"):
print "editing line ", line
# eg replace strings
line = line.replace("somestring","somenewstring")
print line
|
Getting data from external program
|
I need a method to get the data from an external editor.
def _get_content():
from subprocess import call
file = open(file, "w").write(some_name)
call(editor + " " + file, shell=True)
file.close()
file = open(file)
x = file.readlines()
[snip]
I personally think there should be a more elegant way. You see, I need to interact with an external editor and get the data.
Do you know any better approaches/have better ideas?
EDIT:
Marcelo brought me on the idea of using tempfile for doing that.
Here's how I do it:
def _tempfile_write(input):
from tempfile import NamedTemporaryFile
x = NamedTemporaryFile()
x.file.write(input)
x.close()
y = open(x)
[snip]
This does the job, but also not quite satisfying. Heard something about spawning?..
|
[
"This is the way all programs do it, AFAIK. Certainly all version control systems that I've used create a temporary file, pass it to the editor and retrieve the result when the editor exits, just as you have.\n",
"I'd recommend using a list, not a string:\ndef _get_content(editor, initial=\"\"):\n from subprocess import call\n from tempfile import NamedTemporaryFile\n\n # Create the initial temporary file.\n with NamedTemporaryFile(delete=False) as tf:\n tfName = tf.name\n tf.write(initial)\n\n # Fire up the editor.\n if call([editor, tfName]) != 0:\n return None # Editor died or was killed.\n\n # Get the modified content.\n with open(tfName).readlines() as result:\n os.remove(tfName)\n return result\n\n",
"an editor just lets you edit a file interactively. you can also edit files with Python. there's no need to call external editor.\nfor line in open(\"file\"):\n print \"editing line \", line\n # eg replace strings\n line = line.replace(\"somestring\",\"somenewstring\")\n print line\n\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002576956_python.txt
|
Q:
How does Django save decimal values?
What am I doing wrong?
class MyModel(models.Model):
name = models.CharField(max_length=100, verbose_name=_("Name"), blank=False, null=False)
rating = models.DecimalField(max_digits=2, decimal_places=2, default=0)
I do something like that:
average = count/len(votes)
mymodel.rating = average
mymodel.save()
count is the sum of all ratings of given MyModel and votes is an array of those ratings, their division gives an average rating for MyModel (sorry if I described it incorrectly due to my poor English).
If i change previous to:
mymodel.name = 'anything'
mymodel.save()
Then 'anything' ends up in the database, but rating does not.
Why? am I using wrong field type?
Alan.
A:
max_digits is a number of digits before and after the decimal point. With your settings it allows you to store numbers between 0.00 and 0.99. Is it right? I can not figure out the range of values for average variable.
A:
Models do no validation. The types you use pretty much deal with things like syncdb etc. rather than actual formatting of data, that's what a Form is for.
|
How does Django save decimal values?
|
What am I doing wrong?
class MyModel(models.Model):
name = models.CharField(max_length=100, verbose_name=_("Name"), blank=False, null=False)
rating = models.DecimalField(max_digits=2, decimal_places=2, default=0)
I do something like that:
average = count/len(votes)
mymodel.rating = average
mymodel.save()
count is the sum of all ratings of given MyModel and votes is an array of those ratings, their division gives an average rating for MyModel (sorry if I described it incorrectly due to my poor English).
If i change previous to:
mymodel.name = 'anything'
mymodel.save()
Then 'anything' ends up in the database, but rating does not.
Why? am I using wrong field type?
Alan.
|
[
"max_digits is a number of digits before and after the decimal point. With your settings it allows you to store numbers between 0.00 and 0.99. Is it right? I can not figure out the range of values for average variable.\n",
"Models do no validation. The types you use pretty much deal with things like syncdb etc. rather than actual formatting of data, that's what a Form is for.\n"
] |
[
2,
1
] |
[] |
[] |
[
"decimal",
"django",
"python"
] |
stackoverflow_0002581219_decimal_django_python.txt
|
Q:
Use multiple WSGI mount points in Apache with an Nginx reverse proxy
I am trying to set up multiple virtual hosts on the same server with Nginx and Apache and have run into a curious configuration issue.
I have nginx is configured with a generic upstream to apache.
upstream backend {
server 1.1.1.1:8080;
}
I'm trying to set up multiple subdomains in nginx that hit different mountpoints in apache. Each would act like the following examples.
server {
listen 80;
server_name foo.yoursite.com;
location / {
proxy_pass http://backend/bar/;
include /etc/nginx/proxy.conf;
}
...
}
server {
listen 80;
server_name delta.yoursite.com;
location / {
proxy_pass http://backend/gamma/;
include /etc/nginx/proxy.conf;
}
...
}
These mountpoints are pointed at django projects, however each of the url entries are coming back prepended with the apache mountpoint path. So, if I called the django url entry for foo.yoursite.com/wiki/biz/, django appears to be returning foo.yoursite.com/bar/wiki/biz/. Similarly, if I call for the url entry for delta.yoursite.com/wiki/biz/, I get delta.yoursite.com/gamma/wiki/biz/.
Is there any way get rid of the prefix being returned on the url entries by django and apache?
A:
Easiest way is to use following in WSGI script file:
... existing stuff
import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()
def application(environ, start_response):
# Wrapper to clear SCRIPT_NAME..
environ['SCRIPT_NAME'] = ''
return _application(environ, start_response)
Problem comes about because each server mounts at different URL. You thus have to make backend think it was actually mounted at root of server by clearing SCRIPT_NAME.
Note that this will cause problems if you are also accessing back end directly. In that situation you would need to modify above to only do this if request came via proxy.
|
Use multiple WSGI mount points in Apache with an Nginx reverse proxy
|
I am trying to set up multiple virtual hosts on the same server with Nginx and Apache and have run into a curious configuration issue.
I have nginx is configured with a generic upstream to apache.
upstream backend {
server 1.1.1.1:8080;
}
I'm trying to set up multiple subdomains in nginx that hit different mountpoints in apache. Each would act like the following examples.
server {
listen 80;
server_name foo.yoursite.com;
location / {
proxy_pass http://backend/bar/;
include /etc/nginx/proxy.conf;
}
...
}
server {
listen 80;
server_name delta.yoursite.com;
location / {
proxy_pass http://backend/gamma/;
include /etc/nginx/proxy.conf;
}
...
}
These mountpoints are pointed at django projects, however each of the url entries are coming back prepended with the apache mountpoint path. So, if I called the django url entry for foo.yoursite.com/wiki/biz/, django appears to be returning foo.yoursite.com/bar/wiki/biz/. Similarly, if I call for the url entry for delta.yoursite.com/wiki/biz/, I get delta.yoursite.com/gamma/wiki/biz/.
Is there any way get rid of the prefix being returned on the url entries by django and apache?
|
[
"Easiest way is to use following in WSGI script file:\n... existing stuff\n\nimport django.core.handlers.wsgi\n_application = django.core.handlers.wsgi.WSGIHandler()\n\ndef application(environ, start_response):\n # Wrapper to clear SCRIPT_NAME..\n environ['SCRIPT_NAME'] = ''\n return _application(environ, start_response)\n\nProblem comes about because each server mounts at different URL. You thus have to make backend think it was actually mounted at root of server by clearing SCRIPT_NAME.\nNote that this will cause problems if you are also accessing back end directly. In that situation you would need to modify above to only do this if request came via proxy.\n"
] |
[
1
] |
[] |
[] |
[
"apache",
"django",
"nginx",
"python",
"wsgi"
] |
stackoverflow_0002581474_apache_django_nginx_python_wsgi.txt
|
Q:
User management API
I am developing an application suite where users will need to connect to a server and depending on their account type they will be given some services. The server will run Linux. Can you please suggest me some user management API which I can use to develop the server program? By user management I mean user authentication and other related functionalities.
I prefer to work in C++ or python, but any other language should not be a problem. Please note that this application suite is not web based.
Due to security issues, I do not want to give each user a separate account on the linux server.
Thanks,
Akshey
A:
http://web.mit.edu/Kerberos/ Not a drop in solution, but not quite sure what you're looking for.
A:
Django is a python framework that provides all these services. It's very modular too, so you only have to use the components that what you want/need.
Its default admin tools provide authentication and authorization. Includes Users, Permissions, Groups, and message queueing.
If you don't want something as high level as a web front end. Twisted provides an authentication/credentials module. (http://twistedmatrix.com/documents/current/core/howto/cred.html)
A:
You should check out PAM.
For security, you should only do this over SSL so that the user's password is not sent over the wire in cleartext.
|
User management API
|
I am developing an application suite where users will need to connect to a server and depending on their account type they will be given some services. The server will run Linux. Can you please suggest me some user management API which I can use to develop the server program? By user management I mean user authentication and other related functionalities.
I prefer to work in C++ or python, but any other language should not be a problem. Please note that this application suite is not web based.
Due to security issues, I do not want to give each user a separate account on the linux server.
Thanks,
Akshey
|
[
"http://web.mit.edu/Kerberos/ Not a drop in solution, but not quite sure what you're looking for.\n",
"Django is a python framework that provides all these services. It's very modular too, so you only have to use the components that what you want/need.\nIts default admin tools provide authentication and authorization. Includes Users, Permissions, Groups, and message queueing.\nIf you don't want something as high level as a web front end. Twisted provides an authentication/credentials module. (http://twistedmatrix.com/documents/current/core/howto/cred.html)\n",
"You should check out PAM.\nFor security, you should only do this over SSL so that the user's password is not sent over the wire in cleartext.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"c++",
"linux",
"python",
"user_management"
] |
stackoverflow_0001961012_c++_linux_python_user_management.txt
|
Q:
Getting traceback from Python C API
I have a Python C API extension module which occassionally falls over with an uninformative "MemoryError". It's clearly not an error that's catered for by the module's exception handlers. How do I get a more informative error traceback so I can figure out what's gone wrong in the extension module?
Perhaps the question should be, given that I do have the extension module source code, what should I do to get a debuggable version of it with MSVC on MS Windows?
A:
Looks like the extension module is claiming to be out of memory -- whether that's true or false, of course, it's impossible to tell without looking at the extension's sources. Just in case it's true, so that the scarcity of memory might impede a traceback, an old trick is to get some memory earlier and drop it in the error case before reraising it, e.g:
reserve = [None] * 10000
try: amodule.somecall()
except MemoryError:
del reserve
raise
This won't tell you much more than which Python-visible function raised the error (and what Python function called it, etc). To go beyond that you'll need to compile the extension's C sources for debugging and use some tools such as gdb.
|
Getting traceback from Python C API
|
I have a Python C API extension module which occassionally falls over with an uninformative "MemoryError". It's clearly not an error that's catered for by the module's exception handlers. How do I get a more informative error traceback so I can figure out what's gone wrong in the extension module?
Perhaps the question should be, given that I do have the extension module source code, what should I do to get a debuggable version of it with MSVC on MS Windows?
|
[
"Looks like the extension module is claiming to be out of memory -- whether that's true or false, of course, it's impossible to tell without looking at the extension's sources. Just in case it's true, so that the scarcity of memory might impede a traceback, an old trick is to get some memory earlier and drop it in the error case before reraising it, e.g:\nreserve = [None] * 10000\ntry: amodule.somecall()\nexcept MemoryError:\n del reserve\n raise\n\nThis won't tell you much more than which Python-visible function raised the error (and what Python function called it, etc). To go beyond that you'll need to compile the extension's C sources for debugging and use some tools such as gdb.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"python_c_api"
] |
stackoverflow_0002581953_python_python_c_api.txt
|
Q:
How to setting Camera options in Blender
i try to create car's type game, but when i choose camera view , a view is not real every building have miss shape its look like perspective view .So i finding how to config it
A:
your grammar is really bad but i think i understand what you are asking. When you use a camera you have to zoom in until the box fills your screen.
|
How to setting Camera options in Blender
|
i try to create car's type game, but when i choose camera view , a view is not real every building have miss shape its look like perspective view .So i finding how to config it
|
[
"your grammar is really bad but i think i understand what you are asking. When you use a camera you have to zoom in until the box fills your screen. \n"
] |
[
1
] |
[] |
[] |
[
"blender",
"python"
] |
stackoverflow_0001865581_blender_python.txt
|
Q:
Python list as *args?
I have two Python functions, both of which take variable arguments in their function definitions. To give a simple example:
def func1(*args):
for arg in args:
print arg
def func2(*args):
return [2 * arg for arg in args]
I'd like to compose them -- as in func1(func2(3, 4, 5)) -- but I don't want args in func1 to be ([6, 7, 8],), I want it to be (6, 7, 8), as if it was called as func1(6, 7, 8) rather than func1([6, 7, 8]).
Normally, I would just use func1(*func2(3, 4, 5)) or have func1 check to see if args[0] was a list. Unfortunately, I can't use the first solution in this particular instance and to apply the second would require doing such a check in many places (there are a lot of functions in the role of func1).
Does anybody have an idea how to do this? I imagine some sort of introspection could be used, but I could be wrong.
A:
You can consider writing function decorator that checks if the first argument is a list. Applying decorator to existing functions is a bit simpler than modifying functions.
A:
You can use a Decorator as posted by Yaroslav.
Minimal example:
def unpack_args(func):
def deco_func(*args):
if isinstance(args, tuple):
args = args[0]
return func(*args)
return deco_func
def func1(*args):
return args
def func2(*args):
return args
@unpack_args
def func3(*args):
return args
print func1(1,2,3) # > (1,2,3)
print func2(1,2,3) # > (1,2,3)
print func1(*func2(1,2,3)) # > (1,2,3)
print func1(func2(1,2,3)) # > ( (1,2,3), )
print func3(func2(1,2,3)) # > (1,2,3)
A:
Normally, I would just use func1(*func2(3, 4, 5)) or have func1 check to see if args[0] was a list. Unfortunately, I can't use the first solution in this particular instance and to apply the second would require doing such a check in many places (there are a lot of functions in the role of func1).
Why can't you use the first solution?
>>> def func1(*args):
for arg in args:
print arg
>>> def func2(*args):
return [2 * arg for arg in args]
>>> func2(3, 4, 5)
[6, 8, 10]
>>> func1(1,2,3)
1
2
3
>>> func1(*func2(3, 4, 5))
6
8
10
>>>
If that wasn't possible, you could still have used func1(*tuple(func2(3, 4, 5))) (but you don't need to).
|
Python list as *args?
|
I have two Python functions, both of which take variable arguments in their function definitions. To give a simple example:
def func1(*args):
for arg in args:
print arg
def func2(*args):
return [2 * arg for arg in args]
I'd like to compose them -- as in func1(func2(3, 4, 5)) -- but I don't want args in func1 to be ([6, 7, 8],), I want it to be (6, 7, 8), as if it was called as func1(6, 7, 8) rather than func1([6, 7, 8]).
Normally, I would just use func1(*func2(3, 4, 5)) or have func1 check to see if args[0] was a list. Unfortunately, I can't use the first solution in this particular instance and to apply the second would require doing such a check in many places (there are a lot of functions in the role of func1).
Does anybody have an idea how to do this? I imagine some sort of introspection could be used, but I could be wrong.
|
[
"You can consider writing function decorator that checks if the first argument is a list. Applying decorator to existing functions is a bit simpler than modifying functions.\n",
"You can use a Decorator as posted by Yaroslav.\nMinimal example:\ndef unpack_args(func):\n def deco_func(*args):\n if isinstance(args, tuple):\n args = args[0]\n\n return func(*args)\n\n return deco_func\n\n\ndef func1(*args):\n return args\n\ndef func2(*args):\n return args\n\n@unpack_args\ndef func3(*args):\n return args\n\nprint func1(1,2,3) # > (1,2,3)\nprint func2(1,2,3) # > (1,2,3)\nprint func1(*func2(1,2,3)) # > (1,2,3)\nprint func1(func2(1,2,3)) # > ( (1,2,3), )\nprint func3(func2(1,2,3)) # > (1,2,3)\n\n",
"\nNormally, I would just use func1(*func2(3, 4, 5)) or have func1 check to see if args[0] was a list. Unfortunately, I can't use the first solution in this particular instance and to apply the second would require doing such a check in many places (there are a lot of functions in the role of func1).\n\nWhy can't you use the first solution?\n>>> def func1(*args):\n for arg in args:\n print arg\n\n>>> def func2(*args):\n return [2 * arg for arg in args]\n\n>>> func2(3, 4, 5)\n[6, 8, 10]\n>>> func1(1,2,3)\n1\n2\n3\n>>> func1(*func2(3, 4, 5))\n6\n8\n10\n>>> \n\nIf that wasn't possible, you could still have used func1(*tuple(func2(3, 4, 5))) (but you don't need to).\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"function_composition",
"python"
] |
stackoverflow_0002581217_function_composition_python.txt
|
Q:
Python: combining making two scripts into one
I have two separately made python scripts one that makes a sine wave sound based off time, and another that produces a sine wave graph that is based off the same time factors. I need help combining them into one running file.
Here's the first:
from struct import pack
from math import sin, pi
import time
def au_file(name, freq, freq1, dur, vol):
fout = open(name, 'wb')
# header needs size, encoding=2, sampling_rate=8000, channel=1
fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))
factor = 2 * pi * freq/8000
factor1 = 2 * pi * freq1/8000
# write data
for seg in range(8 * dur):
# sine wave calculations
sin_seg = sin(seg * factor) + sin(seg * factor1)
fout.write(pack('b', vol * 64 * sin_seg))
fout.close()
t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis * 100
tim = float(ti)
tim = tim * 100
if __name__ == '__main__':
au_file(name='timeSound.au', freq=tim, freq1=tis, dur=1000, vol=1.0)
import os
os.startfile('timeSound.au')
and the second is this:
from Tkinter import *
import math
import time
t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis / 100
tim = float(ti)
tim = tim / 100
root = Tk()
root.title("This very moment")
width = 400
height = 300
center = height//2
x_increment = 1
# width stretch
x_factor1 = tis
x_factor2 = tim
# height stretch
y_amplitude = 50
c = Canvas(width=width, height=height, bg='black')
c.pack()
str1 = "sin(x)=white"
c.create_text(10, 20, anchor=SW, text=str1)
center_line = c.create_line(0, center, width, center, fill='red')
# create the coordinate list for the sin() curve, have to be integers
xy1 = []
xy2 = []
for x in range(400):
# x coordinates
xy1.append(x * x_increment)
xy2.append(x * x_increment)
# y coordinates
xy1.append(int(math.sin(x * x_factor1) * y_amplitude) + center)
xy2.append(int(math.sin(x * x_factor2) * y_amplitude) + center)
sinS_line = c.create_line(xy1, fill='white')
sinM_line = c.create_line(xy2, fill='yellow')
root.mainloop()
A:
from Tkinter import *
from struct import pack
from math import sin, pi
import math
import time
import os
def wave():
t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis / 100
tim = float(ti)
tim = tim / 100
root = Tk()
root.title("This very moment")
width = 400
height = 300
center = height//2
x_increment = 1
# width stretch
x_factor1 = tis
x_factor2 = tim
# height stretch
y_amplitude = 50
c = Canvas(width=width, height=height, bg='black')
c.pack()
str1 = "sin(x)=white"
c.create_text(10, 20, anchor=SW, text=str1)
center_line = c.create_line(0, center, width, center, fill='red')
# create the coordinate list for the sin() curve, have to be integers
xy1 = []
xy2 = []
for x in range(400):
# x coordinates
xy1.append(x * x_increment)
xy2.append(x * x_increment)
# y coordinates
xy1.append(int(math.sin(x * x_factor1) * y_amplitude) + center)
xy2.append(int(math.sin(x * x_factor2) * y_amplitude) + center)
sinS_line = c.create_line(xy1, fill='white')
sinM_line = c.create_line(xy2, fill='yellow')
root.mainloop()
def au_file(name, freq, freq1, dur, vol):
fout = open(name, 'wb')
# header needs size, encoding=2, sampling_rate=8000, channel=1
fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))
factor = 2 * pi * freq/8000
factor1 = 2 * pi * freq1/8000
# write data
for seg in range(8 * dur):
# sine wave calculations
sin_seg = sin(seg * factor) + sin(seg * factor1)
fout.write(pack('b', vol * 64 * sin_seg))
fout.close()
t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis * 100
tim = float(ti)
tim = tim * 100
os.startfile('timeSound.au')
def main():
au_file(name='timeSound.au', freq=tim, freq1=tis, dur=1000, vol=1.0)
wave()
main()
|
Python: combining making two scripts into one
|
I have two separately made python scripts one that makes a sine wave sound based off time, and another that produces a sine wave graph that is based off the same time factors. I need help combining them into one running file.
Here's the first:
from struct import pack
from math import sin, pi
import time
def au_file(name, freq, freq1, dur, vol):
fout = open(name, 'wb')
# header needs size, encoding=2, sampling_rate=8000, channel=1
fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))
factor = 2 * pi * freq/8000
factor1 = 2 * pi * freq1/8000
# write data
for seg in range(8 * dur):
# sine wave calculations
sin_seg = sin(seg * factor) + sin(seg * factor1)
fout.write(pack('b', vol * 64 * sin_seg))
fout.close()
t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis * 100
tim = float(ti)
tim = tim * 100
if __name__ == '__main__':
au_file(name='timeSound.au', freq=tim, freq1=tis, dur=1000, vol=1.0)
import os
os.startfile('timeSound.au')
and the second is this:
from Tkinter import *
import math
import time
t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis / 100
tim = float(ti)
tim = tim / 100
root = Tk()
root.title("This very moment")
width = 400
height = 300
center = height//2
x_increment = 1
# width stretch
x_factor1 = tis
x_factor2 = tim
# height stretch
y_amplitude = 50
c = Canvas(width=width, height=height, bg='black')
c.pack()
str1 = "sin(x)=white"
c.create_text(10, 20, anchor=SW, text=str1)
center_line = c.create_line(0, center, width, center, fill='red')
# create the coordinate list for the sin() curve, have to be integers
xy1 = []
xy2 = []
for x in range(400):
# x coordinates
xy1.append(x * x_increment)
xy2.append(x * x_increment)
# y coordinates
xy1.append(int(math.sin(x * x_factor1) * y_amplitude) + center)
xy2.append(int(math.sin(x * x_factor2) * y_amplitude) + center)
sinS_line = c.create_line(xy1, fill='white')
sinM_line = c.create_line(xy2, fill='yellow')
root.mainloop()
|
[
"from Tkinter import *\nfrom struct import pack\nfrom math import sin, pi\nimport math\nimport time\nimport os\n\n\ndef wave():\n t = time.strftime(\"%S\", time.localtime())\n ti = time.strftime(\"%M\", time.localtime())\n tis = float(t)\n tis = tis / 100\n tim = float(ti)\n tim = tim / 100\n\n root = Tk()\n root.title(\"This very moment\")\n\n width = 400\n height = 300\n center = height//2\n x_increment = 1\n # width stretch\n x_factor1 = tis\n x_factor2 = tim\n # height stretch\n y_amplitude = 50\n\n c = Canvas(width=width, height=height, bg='black')\n c.pack()\n\n str1 = \"sin(x)=white\"\n c.create_text(10, 20, anchor=SW, text=str1)\n\n center_line = c.create_line(0, center, width, center, fill='red')\n\n # create the coordinate list for the sin() curve, have to be integers\n xy1 = []\n xy2 = []\n for x in range(400):\n # x coordinates\n xy1.append(x * x_increment)\n xy2.append(x * x_increment)\n # y coordinates\n xy1.append(int(math.sin(x * x_factor1) * y_amplitude) + center)\n xy2.append(int(math.sin(x * x_factor2) * y_amplitude) + center)\n\n sinS_line = c.create_line(xy1, fill='white')\n sinM_line = c.create_line(xy2, fill='yellow')\n\n root.mainloop()\n\ndef au_file(name, freq, freq1, dur, vol):\n fout = open(name, 'wb')\n # header needs size, encoding=2, sampling_rate=8000, channel=1\n fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))\n factor = 2 * pi * freq/8000\n factor1 = 2 * pi * freq1/8000\n # write data\n for seg in range(8 * dur):\n # sine wave calculations\n sin_seg = sin(seg * factor) + sin(seg * factor1)\n fout.write(pack('b', vol * 64 * sin_seg))\n fout.close()\n\nt = time.strftime(\"%S\", time.localtime())\nti = time.strftime(\"%M\", time.localtime())\ntis = float(t)\ntis = tis * 100\ntim = float(ti)\ntim = tim * 100\nos.startfile('timeSound.au')\n\ndef main():\n au_file(name='timeSound.au', freq=tim, freq1=tis, dur=1000, vol=1.0)\n wave()\n\nmain()\n\n"
] |
[
1
] |
[] |
[] |
[
"class",
"partial_classes",
"python"
] |
stackoverflow_0002582269_class_partial_classes_python.txt
|
Q:
How to skip interstitial in a django view if a user hits the back button?
I have an application with an interstitial page to hold the user while an intensive operation runs in the background (takes anywhere from 30 secs to 1 minute). Once the operation is done, the user is redirected to the results page.
Once on the result page, typical user behavior is to hit the 'back' button to perform the operation on a different input set. However, the back button takes them to the interstitial, not the original form. The desired behavior is to go back to the original form, skipping the interstitial entirely. I'd like this to be default behavior if the user goes to the interstitial page from anywhere but the original form.
I thought I could create this by using the @never_cache function decorator in my view for the interstitial, and logic based on request.META['HTTP_REFERER'], however the page doesn't respect these. The browser's back button still trumps this behavior.
Any ideas on how to solve this issue?
A:
How do you keep the interstitial page from entering the flow? Eliminate it.
I'm only recently wrapping my head around AJAX, so wish I could give you a more concrete answer, but the general approach is to use something like jQuery to replace the contents of the form <div> after submission with a "hey, I'm working here" indication and then a load of the new page when ready.
jQuery very kindly appends a unique, junk parameter to certain requests to explicitly thwart caching of volatile pages.
|
How to skip interstitial in a django view if a user hits the back button?
|
I have an application with an interstitial page to hold the user while an intensive operation runs in the background (takes anywhere from 30 secs to 1 minute). Once the operation is done, the user is redirected to the results page.
Once on the result page, typical user behavior is to hit the 'back' button to perform the operation on a different input set. However, the back button takes them to the interstitial, not the original form. The desired behavior is to go back to the original form, skipping the interstitial entirely. I'd like this to be default behavior if the user goes to the interstitial page from anywhere but the original form.
I thought I could create this by using the @never_cache function decorator in my view for the interstitial, and logic based on request.META['HTTP_REFERER'], however the page doesn't respect these. The browser's back button still trumps this behavior.
Any ideas on how to solve this issue?
|
[
"How do you keep the interstitial page from entering the flow? Eliminate it.\nI'm only recently wrapping my head around AJAX, so wish I could give you a more concrete answer, but the general approach is to use something like jQuery to replace the contents of the form <div> after submission with a \"hey, I'm working here\" indication and then a load of the new page when ready.\njQuery very kindly appends a unique, junk parameter to certain requests to explicitly thwart caching of volatile pages.\n"
] |
[
2
] |
[] |
[] |
[
"caching",
"django",
"header",
"interstitial",
"python"
] |
stackoverflow_0002580905_caching_django_header_interstitial_python.txt
|
Q:
how to make python load dylib on osx
Trying to load a shared lib out of the current '.' dir in a unit test on osx.
What works on Linux and Netbsd there is a symlink _mymodule.so --> ../.libs/libmymodule.so
but on osx, python's import mymodule won't find
_mymodule.dylib --> ../.libs/libmymodule.dylib
I've tried adding
export DYLD_LIBRARY_PATH=.:$DYLD_LIBRARY_PATH
to the script env, nogo. Any help appreciated.
-Ed
update 4/6/10:
Solved with the info from krunk below. But just copying or ln -s'ing the dylib to a .so name didn't solve it completely. Still wouldn't load. But telling libtool to link the lib with the -module flag created a .so lib that would load. Python version of the lib works now.
Now if I could just get the perl lib working. I'm building swig perl, python, ruby, and lua libs and this fix only got python and lua working.
A:
Just use *.so as your module extensions in OS X too. I have a vague memory of not being able to load .dylib's and it turning out to be an issue with python itself. . . but I can't find the mailing list post now.
However, rest assured you're following standard practice by using *.so's even on OS X. The only *.dylib's in the entire framework are the libsvn_swig ones.
find /System/Library/Frameworks/Python.framework/Versions/2.6/ -name "*.so"
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/X11/xcb/xcb.0.0.0.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/X11/xcb/xcb.0.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/X11/xcb/xcb.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/CoreGraphics/_CoreGraphics.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/OpenSSL/SSL.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/OpenSSL/crypto.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/OpenSSL/rand.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_appmain.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_carbon.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_inlines.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsbezierpath.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsbitmap.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsfont.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsquickdrawview.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsview.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nswindow.so
/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/CFNetwork/_manual.so
|
how to make python load dylib on osx
|
Trying to load a shared lib out of the current '.' dir in a unit test on osx.
What works on Linux and Netbsd there is a symlink _mymodule.so --> ../.libs/libmymodule.so
but on osx, python's import mymodule won't find
_mymodule.dylib --> ../.libs/libmymodule.dylib
I've tried adding
export DYLD_LIBRARY_PATH=.:$DYLD_LIBRARY_PATH
to the script env, nogo. Any help appreciated.
-Ed
update 4/6/10:
Solved with the info from krunk below. But just copying or ln -s'ing the dylib to a .so name didn't solve it completely. Still wouldn't load. But telling libtool to link the lib with the -module flag created a .so lib that would load. Python version of the lib works now.
Now if I could just get the perl lib working. I'm building swig perl, python, ruby, and lua libs and this fix only got python and lua working.
|
[
"Just use *.so as your module extensions in OS X too. I have a vague memory of not being able to load .dylib's and it turning out to be an issue with python itself. . . but I can't find the mailing list post now.\nHowever, rest assured you're following standard practice by using *.so's even on OS X. The only *.dylib's in the entire framework are the libsvn_swig ones. \nfind /System/Library/Frameworks/Python.framework/Versions/2.6/ -name \"*.so\"\n\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/X11/xcb/xcb.0.0.0.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/X11/xcb/xcb.0.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/X11/xcb/xcb.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/CoreGraphics/_CoreGraphics.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/OpenSSL/SSL.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/OpenSSL/crypto.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/OpenSSL/rand.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_appmain.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_carbon.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_inlines.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsbezierpath.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsbitmap.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsfont.so\n /System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsquickdrawview.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nsview.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/AppKit/_nswindow.so\n/System/Library/Frameworks/Python.framework/Versions/2.6//Extras/lib/python/PyObjC/CFNetwork/_manual.so\n\n"
] |
[
13
] |
[] |
[] |
[
"dylib",
"macos",
"python"
] |
stackoverflow_0002488016_dylib_macos_python.txt
|
Q:
Python beginner confused by a complex line of code
I understand the gist of the code, that it forms permutations; however, I was wondering if someone could explain exactly what is going on in the return statement.
def perm(l):
sz = len(l)
print (l)
if sz <= 1:
print ('sz <= 1')
return [l]
return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]
A:
This return is returning a list comprehension whose items are made by inserting the first item of l into each position of p, from the first to the last -- p in turn is a list of lists, obtained by a recursive call to perm which excludes the first item of l (and thus permutes all other items in all possible ways).
If you don't understand recursion, it's not really trivial to explain;-). If you don't understand list comprehensions, they are trivial to explain -- that return is semantically equivalent to
result = []
for i in range(sz):
for p in perm(l[1:]):
result.append(p[:i]+[l[0]]+p[i:])
return result
this also shows how inefficient this code is: it's calling perm recursively sz times, and obviously there's no need for it. Much better would be to simply swap the two for loops:
result = []
for p in perm(l[1:]):
for i in range(sz):
result.append(p[:i]+[l[0]]+p[i:])
return result
and the equivalent of this, much better code, is a list comprehension with the two for clauses swapped:
return [p[:i]+[l[0]]+p[i:] for p in perm(l[1:]) for i in range(sz)]
A:
The return statement is using a list comprehension. It's a bit easier to understand if you put it into actual loops:
value = []
for i in range(sz):
# call this function using all but the first item in l
for p in perm(l[1:]):
# now place the first item in l between index i-1 and index i in p
value.append(p[:i] + [l[0]] + p[i:])
return value
A:
Look at this:
>>> l = [1, 2, 3, 4, 5, 6]
>>> p = l[1:]
>>> p
[2, 3, 4, 5, 6]
>>> i = 3
>>> p[:i]
[2, 3, 4]
>>> p[i:]
[5, 6]
>>> p[:i]+[l[0]]+p[i:]
[2, 3, 4, 1, 5, 6]
>>>
So, here's the thing, p stands for all permutations of l[1:] (ie, l minus the first element). Next, i is range(sz), which means it varies from 0 to the length of l. That will split p in two lists of all possible sizes (0 and sz, 1 and sz -1, 2 and sz - 2, etc), and insert the first element of l -- the one that didn't get permuted -- between these two lists.
A:
Okay, let's begin.
Starting code
(minus print statements)
def perm(l):
sz = len(l)
if sz <= 1:
return [l]
return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]
Revision 1
def perm(s):
# Base case: an empty list or a list with only one item has only one
# permutation
if len(s) <= 1:
return [s]
return [p[:i] + [s[0]] + p[i:]
for i in range(len(s)) for p in perm(s[1:])]
Rename l to s
Remove sz, instead using len(s) directly. We might lose a tiny bit of efficiency, but we gain a huge amount of readability
Fix spacing in list comprehension
Revision 2
def perm(s):
# Base case: an empty list or a list with only one item has only one
# permutation
if len(s) <= 1:
return [s]
# A list of permutations
permutations = []
for i in range(len(s)):
# Recursively find all permutations of s[1:]
for p in perm(s[1:]):
# Insert s[0] in position i
permutations.append(p[:i] + [s[0]] + p[i:])
return permutations
Break apart the list comprehension
Revision 3
def perm(s):
# Base case: an empty list or a list with only one item has only one
# permutation
if len(s) <= 1:
return [s]
# A list of permutations
permutations = []
# Recursively find all permutations of s[1:]
for p in perm(s[1:]):
for i in range(len(s)):
# Insert s[0] in position i
permutations.append(p[:i] + [s[0]] + p[i:])
return permutations
Change the nesting of the for loops. Now, you can say: for each permutation, take each position i, and add a copy of that permutation with s[0] inserted in each position i. This gets clearer in the next few revisions.
Revision 4
def perm(s):
# Base case: an empty list or a list with only one item has only one
# permutation
if len(s) <= 1:
return [s]
# Recursively find all permutations of s[1:]
shortperms = perm(s[1:])
# A list of permutations
permutations = []
for shortperm in shortperms:
for i in range(len(s)):
# Make a copy of shortperm
spcopy = shortperm[:]
# Insert s[0] in position i
spcopy.insert(s[0], i)
# Add this to the list of permutations
permutations.append(spcopy)
return permutations
Moved the perm function call. Now, the shortperms variable will contain all the permutations of s[1:], which is s minus the first item.
Changed the list addition into three operations:
Make a copy of shortperm
Insert the first item in s
Add that list to permutations
Revision 5
def perm(s):
# Base case: an empty list or a list with only one item has only one
# permutation
if len(s) <= 1:
return [s]
# Recursively find all permutations of s[1:]
shortperms = perm(s[1:])
# A list of permutations
permutations = []
for shortperm in shortperms:
for i in range(len(shortperm) + 1):
# Make a copy of shortperm
spcopy = shortperm[:]
# Insert s[0] in position i
spcopy.insert(s[0], i)
# Add this to the list of permutations
permutations.append(spcopy)
return permutations
len(s) is the same as len(shortperm) + 1, because each shortperm is a permutation of the items in s, minus the first one. However, this is probably more readable.
Final code
With a docstring comment
def perm(s):
"""Return a list of all permutations of the items in the input
sequence."""
# Base case: an empty list or a list with only one item has only one
# permutation
if len(s) <= 1:
return [s]
# Recursively find all permutations of s[1:]
shortperms = perm(s[1:])
# A list of permutations
permutations = []
for shortperm in shortperms:
for i in range(len(shortperm) + 1):
# Make a copy of shortperm
spcopy = shortperm[:]
# Insert s[0] in position i
spcopy.insert(s[0], i)
# Add this to the list of permutations
permutations.append(spcopy)
return permutations
A:
There are a couple of examples in the Python documentation for the itertools.permutations() function that are easier to digest. Note that this function is new in Python 2.6, so it won't be available for you if you're using anything older.
There are also many examples and explanations in SO conversations that have already occurred in the not-too-distant past that also represent good reading:
algorithm for python itertools.permutations
How to generate all permutations of a list in Python
|
Python beginner confused by a complex line of code
|
I understand the gist of the code, that it forms permutations; however, I was wondering if someone could explain exactly what is going on in the return statement.
def perm(l):
sz = len(l)
print (l)
if sz <= 1:
print ('sz <= 1')
return [l]
return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]
|
[
"This return is returning a list comprehension whose items are made by inserting the first item of l into each position of p, from the first to the last -- p in turn is a list of lists, obtained by a recursive call to perm which excludes the first item of l (and thus permutes all other items in all possible ways).\nIf you don't understand recursion, it's not really trivial to explain;-). If you don't understand list comprehensions, they are trivial to explain -- that return is semantically equivalent to\nresult = []\nfor i in range(sz):\n for p in perm(l[1:]):\n result.append(p[:i]+[l[0]]+p[i:])\nreturn result\n\nthis also shows how inefficient this code is: it's calling perm recursively sz times, and obviously there's no need for it. Much better would be to simply swap the two for loops:\nresult = []\nfor p in perm(l[1:]):\n for i in range(sz):\n result.append(p[:i]+[l[0]]+p[i:])\nreturn result\n\nand the equivalent of this, much better code, is a list comprehension with the two for clauses swapped:\nreturn [p[:i]+[l[0]]+p[i:] for p in perm(l[1:]) for i in range(sz)]\n\n",
"The return statement is using a list comprehension. It's a bit easier to understand if you put it into actual loops:\nvalue = []\nfor i in range(sz):\n # call this function using all but the first item in l\n for p in perm(l[1:]):\n # now place the first item in l between index i-1 and index i in p\n value.append(p[:i] + [l[0]] + p[i:])\nreturn value\n\n",
"Look at this:\n>>> l = [1, 2, 3, 4, 5, 6]\n>>> p = l[1:]\n>>> p\n[2, 3, 4, 5, 6]\n>>> i = 3\n>>> p[:i]\n[2, 3, 4]\n>>> p[i:]\n[5, 6]\n>>> p[:i]+[l[0]]+p[i:]\n[2, 3, 4, 1, 5, 6]\n>>> \n\nSo, here's the thing, p stands for all permutations of l[1:] (ie, l minus the first element). Next, i is range(sz), which means it varies from 0 to the length of l. That will split p in two lists of all possible sizes (0 and sz, 1 and sz -1, 2 and sz - 2, etc), and insert the first element of l -- the one that didn't get permuted -- between these two lists.\n",
"Okay, let's begin.\nStarting code\n(minus print statements)\ndef perm(l):\n sz = len(l)\n if sz <= 1:\n return [l]\n return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]\n\nRevision 1\ndef perm(s):\n # Base case: an empty list or a list with only one item has only one\n # permutation\n if len(s) <= 1:\n return [s]\n return [p[:i] + [s[0]] + p[i:]\n for i in range(len(s)) for p in perm(s[1:])]\n\n\nRename l to s\nRemove sz, instead using len(s) directly. We might lose a tiny bit of efficiency, but we gain a huge amount of readability\nFix spacing in list comprehension\n\nRevision 2\ndef perm(s):\n # Base case: an empty list or a list with only one item has only one\n # permutation\n if len(s) <= 1:\n return [s]\n\n # A list of permutations\n permutations = []\n for i in range(len(s)):\n # Recursively find all permutations of s[1:]\n for p in perm(s[1:]):\n # Insert s[0] in position i\n permutations.append(p[:i] + [s[0]] + p[i:])\n return permutations\n\n\nBreak apart the list comprehension\n\nRevision 3\ndef perm(s):\n # Base case: an empty list or a list with only one item has only one\n # permutation\n if len(s) <= 1:\n return [s]\n\n # A list of permutations\n permutations = []\n # Recursively find all permutations of s[1:]\n for p in perm(s[1:]):\n for i in range(len(s)):\n # Insert s[0] in position i\n permutations.append(p[:i] + [s[0]] + p[i:])\n return permutations\n\n\nChange the nesting of the for loops. Now, you can say: for each permutation, take each position i, and add a copy of that permutation with s[0] inserted in each position i. This gets clearer in the next few revisions.\n\nRevision 4\ndef perm(s):\n # Base case: an empty list or a list with only one item has only one\n # permutation\n if len(s) <= 1:\n return [s]\n\n # Recursively find all permutations of s[1:]\n shortperms = perm(s[1:])\n # A list of permutations\n permutations = []\n for shortperm in shortperms:\n for i in range(len(s)):\n # Make a copy of shortperm\n spcopy = shortperm[:]\n # Insert s[0] in position i\n spcopy.insert(s[0], i)\n # Add this to the list of permutations\n permutations.append(spcopy)\n return permutations\n\n\nMoved the perm function call. Now, the shortperms variable will contain all the permutations of s[1:], which is s minus the first item.\nChanged the list addition into three operations:\n\n\nMake a copy of shortperm\nInsert the first item in s\nAdd that list to permutations\n\n\nRevision 5\ndef perm(s):\n # Base case: an empty list or a list with only one item has only one\n # permutation\n if len(s) <= 1:\n return [s]\n\n # Recursively find all permutations of s[1:]\n shortperms = perm(s[1:])\n # A list of permutations\n permutations = []\n for shortperm in shortperms:\n for i in range(len(shortperm) + 1):\n # Make a copy of shortperm\n spcopy = shortperm[:]\n # Insert s[0] in position i\n spcopy.insert(s[0], i)\n # Add this to the list of permutations\n permutations.append(spcopy)\n return permutations\n\n\nlen(s) is the same as len(shortperm) + 1, because each shortperm is a permutation of the items in s, minus the first one. However, this is probably more readable.\n\nFinal code\nWith a docstring comment\ndef perm(s):\n \"\"\"Return a list of all permutations of the items in the input\n sequence.\"\"\"\n # Base case: an empty list or a list with only one item has only one\n # permutation\n if len(s) <= 1:\n return [s]\n\n # Recursively find all permutations of s[1:]\n shortperms = perm(s[1:])\n # A list of permutations\n permutations = []\n for shortperm in shortperms:\n for i in range(len(shortperm) + 1):\n # Make a copy of shortperm\n spcopy = shortperm[:]\n # Insert s[0] in position i\n spcopy.insert(s[0], i)\n # Add this to the list of permutations\n permutations.append(spcopy)\n return permutations\n\n",
"There are a couple of examples in the Python documentation for the itertools.permutations() function that are easier to digest. Note that this function is new in Python 2.6, so it won't be available for you if you're using anything older.\nThere are also many examples and explanations in SO conversations that have already occurred in the not-too-distant past that also represent good reading:\nalgorithm for python itertools.permutations\nHow to generate all permutations of a list in Python\n"
] |
[
10,
4,
1,
1,
0
] |
[] |
[] |
[
"list_comprehension",
"python"
] |
stackoverflow_0002581965_list_comprehension_python.txt
|
Q:
Python beginner, strange output problem
I'm having a weird problem with the following piece of code.
from math import sqrt
def Permute(array):
result1 = []
result2 = []
if len(array) <= 1:
return array
for subarray in Permute(array[1:]):
for i in range(len(array)):
temp1 = subarray[:i]+array[0]+subarray[i:]
temp2 = [0]
for num in range(len(array)-1):
temp2[0] += (sqrt(pow((temp1[num+1][1][0]-temp1[num][1][0]),2) + pow((temp1[num+1][1][1]-temp1[num][1][1]),2)))
result1.append(temp1+temp2)
return result1
a = [['A',[50,1]]]
b = [['B',[1,1]]]
c = [['C',[100,1]]]
array = [a,b,c]
result1 = Permute(array)
for i in range(len(result1)):
print (result1[i])
print (len(result1))
What it does is find all the permutations of the points abc and then returns them along with the sum of the distances between each ordered point. It does this; however, it also seems to report a strange additional value, 99. I figure that the 99 is coming from the computation of the distance between point a and c but I don't understand why it is appearing in the final output as it does.
A:
The problem is that you recursively call Permute(array[1:]), then use the recursive result to calculate temp1. Why is this a problem? Your function outputs an array of arrays, where the last subarray is temp2, the distance sum. So, every level of recursion, you will add more and more extra distances to your final result.
If you really want to calculate all the permutations and distances in the same function, then I suggest you return a tuple (permutation, distance). You can then use the first part of the tuple when assigning temp1, so that you don't accidentally add in extra distances. See this page if you aren't familiar with tuples.
A:
I agree with what Justin Ardini said, but I would also suggest that you learn to use a Python debugger like pdb. Then you can go through functions like this and figure out what is going on for yourself. You'll learn a lot more that way.
A:
I think what you're trying to do is:
from math import sqrt
def Permute(array):
result1 = []
result2 = []
if len(array) <= 1:
for subarray in array:
for i in range(len(array)):
temp1 = subarray[:i]+array[0]+subarray[i:]
temp2 = [0]
for num in range(len(array)-1):
temp2[0] += (sqrt(pow((temp1[num+1][1][0]-temp1[num][1][0]),2) + pow((temp1[num+1][1][1]-temp1[num][1][1]),2)))
result1.append(temp1+temp2)
return result1
a = [['A',[50,1]]]
b = [['B',[1,1]]]
c = [['C',[100,1]]]
array = [a,b,c]
result1 = Permute(array)
for i in range(len(result1)):
print (result1[i])
print (len(result1))
I changed:
if len(array) <= 1:
return array
for subarray in Permute(array[1:]):
to:
if len(array) <= 1:
for subarray in array:
|
Python beginner, strange output problem
|
I'm having a weird problem with the following piece of code.
from math import sqrt
def Permute(array):
result1 = []
result2 = []
if len(array) <= 1:
return array
for subarray in Permute(array[1:]):
for i in range(len(array)):
temp1 = subarray[:i]+array[0]+subarray[i:]
temp2 = [0]
for num in range(len(array)-1):
temp2[0] += (sqrt(pow((temp1[num+1][1][0]-temp1[num][1][0]),2) + pow((temp1[num+1][1][1]-temp1[num][1][1]),2)))
result1.append(temp1+temp2)
return result1
a = [['A',[50,1]]]
b = [['B',[1,1]]]
c = [['C',[100,1]]]
array = [a,b,c]
result1 = Permute(array)
for i in range(len(result1)):
print (result1[i])
print (len(result1))
What it does is find all the permutations of the points abc and then returns them along with the sum of the distances between each ordered point. It does this; however, it also seems to report a strange additional value, 99. I figure that the 99 is coming from the computation of the distance between point a and c but I don't understand why it is appearing in the final output as it does.
|
[
"The problem is that you recursively call Permute(array[1:]), then use the recursive result to calculate temp1. Why is this a problem? Your function outputs an array of arrays, where the last subarray is temp2, the distance sum. So, every level of recursion, you will add more and more extra distances to your final result.\nIf you really want to calculate all the permutations and distances in the same function, then I suggest you return a tuple (permutation, distance). You can then use the first part of the tuple when assigning temp1, so that you don't accidentally add in extra distances. See this page if you aren't familiar with tuples.\n",
"I agree with what Justin Ardini said, but I would also suggest that you learn to use a Python debugger like pdb. Then you can go through functions like this and figure out what is going on for yourself. You'll learn a lot more that way. \n",
"I think what you're trying to do is:\nfrom math import sqrt\n\ndef Permute(array):\n result1 = []\n result2 = []\n if len(array) <= 1:\n for subarray in array:\n for i in range(len(array)):\n temp1 = subarray[:i]+array[0]+subarray[i:]\n temp2 = [0]\n for num in range(len(array)-1):\n temp2[0] += (sqrt(pow((temp1[num+1][1][0]-temp1[num][1][0]),2) + pow((temp1[num+1][1][1]-temp1[num][1][1]),2)))\n result1.append(temp1+temp2)\n return result1\n\na = [['A',[50,1]]]\nb = [['B',[1,1]]]\nc = [['C',[100,1]]]\narray = [a,b,c]\n\nresult1 = Permute(array)\nfor i in range(len(result1)):\n print (result1[i])\nprint (len(result1))\n\nI changed:\nif len(array) <= 1:\n return array\nfor subarray in Permute(array[1:]):\n\nto:\nif len(array) <= 1:\n for subarray in array:\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002582756_python.txt
|
Q:
Does wx.DC line has events?
A line created using the DrawLine method of wx.DC has the onClick and onMouseOver events?
A:
No wx.DC just draw to a device and those are all plain pixels, wx.DC doesn't track mouse events or any other events.
If you want such behavior you will have to track mouse movement on your drawing area and on click check which area it may have clicked e.g. if near by the line show a msg etc.
|
Does wx.DC line has events?
|
A line created using the DrawLine method of wx.DC has the onClick and onMouseOver events?
|
[
"No wx.DC just draw to a device and those are all plain pixels, wx.DC doesn't track mouse events or any other events.\nIf you want such behavior you will have to track mouse movement on your drawing area and on click check which area it may have clicked e.g. if near by the line show a msg etc.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002583646_python_wxpython.txt
|
Q:
How to draw text in a bitmap using wxpython?
I want to draw a number centered inside a wx.EmptyBitmap.
How can I do it using wxpython?
Thanks in advance :)
import wx
app = None
class Size(wx.Frame):
def __init__(self, parent, id, title):
frame = wx.Frame.__init__(self, parent, id, title, size=(250, 200))
bmp = wx.EmptyBitmap(100, 100)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.DrawText("whatever", 50, 50)
dc.SelectObject(wx.NullBitmap)
wx.StaticBitmap(self, -1, bmp)
self.Show(True)
app = wx.App()
Size(None, -1, 'Size')
app.MainLoop()
This code only gives me a black image, what am I doing wrong?
What's missing here..
A:
Select the bmp in a wx.MemoryDC, draw anything on that dc and then select that bitmap out e.g.
import wx
app = None
class Size(wx.Frame):
def __init__(self, parent, id, title):
frame = wx.Frame.__init__(self, parent, id, title, size=(250, 200))
w, h = 100, 100
bmp = wx.EmptyBitmap(w, h)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.Clear()
text = "whatever"
tw, th = dc.GetTextExtent(text)
dc.DrawText(text, (w-tw)/2, (h-th)/2)
dc.SelectObject(wx.NullBitmap)
wx.StaticBitmap(self, -1, bmp)
self.Show(True)
app = wx.App()
app.MainLoop()
A:
You use a wx.MemoryDC
|
How to draw text in a bitmap using wxpython?
|
I want to draw a number centered inside a wx.EmptyBitmap.
How can I do it using wxpython?
Thanks in advance :)
import wx
app = None
class Size(wx.Frame):
def __init__(self, parent, id, title):
frame = wx.Frame.__init__(self, parent, id, title, size=(250, 200))
bmp = wx.EmptyBitmap(100, 100)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.DrawText("whatever", 50, 50)
dc.SelectObject(wx.NullBitmap)
wx.StaticBitmap(self, -1, bmp)
self.Show(True)
app = wx.App()
Size(None, -1, 'Size')
app.MainLoop()
This code only gives me a black image, what am I doing wrong?
What's missing here..
|
[
"Select the bmp in a wx.MemoryDC, draw anything on that dc and then select that bitmap out e.g.\nimport wx\n\napp = None\n\nclass Size(wx.Frame):\n def __init__(self, parent, id, title):\n frame = wx.Frame.__init__(self, parent, id, title, size=(250, 200))\n w, h = 100, 100\n bmp = wx.EmptyBitmap(w, h)\n dc = wx.MemoryDC()\n dc.SelectObject(bmp)\n dc.Clear()\n text = \"whatever\"\n tw, th = dc.GetTextExtent(text)\n dc.DrawText(text, (w-tw)/2, (h-th)/2)\n dc.SelectObject(wx.NullBitmap)\n wx.StaticBitmap(self, -1, bmp)\n self.Show(True)\n\n\napp = wx.App()\napp.MainLoop()\n\n",
"You use a wx.MemoryDC\n"
] |
[
5,
1
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002583549_python_wxpython.txt
|
Q:
Comments in string and strings in comments
I am trying to count characters in comments included in C code using Python and Regex, but no success. I can erase strings first to get rid of comments in strings, but this will erase string in comments too and result will be bad ofc. Is there any chance to ask by using regex to not match strings in comments or vice versa?
A:
No, not really.
Regex is not the correct tool to parse nested structures like you describe; instead you will need to parse the C syntax (or the "dumb subset" of it you're interested in, anyway), and you might find regex helpful in that. A relatively simple state machine with three states (CODE, STRING, COMMENT) would do it.
A:
Regular expressions are not always a replacement for a real parser.
A:
You can strip out all strings that aren't in comments by searching for the regular expression:
'[^'\r\n]+'|(//.*|/\*(?s:.*?)\*/)
and replacing with:
$1
Essentially, this searches for the regex string|(comment) which matches a string or a comment, capturing the comment. The replacement is either nothing if a string was matched or the comment if a comment was matched.
Though regular expressions are not a replacement for a real parser you can quickly build a rudimentary parser by creating a giant regex that alternates all of the tokens you're interested in (comments and strings in this case). If you're writing a bit of code to handle comments, but not those in strings, iterate over all the matches of the above regex, and count the characters in the first capturing group if it participated in the match.
|
Comments in string and strings in comments
|
I am trying to count characters in comments included in C code using Python and Regex, but no success. I can erase strings first to get rid of comments in strings, but this will erase string in comments too and result will be bad ofc. Is there any chance to ask by using regex to not match strings in comments or vice versa?
|
[
"No, not really.\nRegex is not the correct tool to parse nested structures like you describe; instead you will need to parse the C syntax (or the \"dumb subset\" of it you're interested in, anyway), and you might find regex helpful in that. A relatively simple state machine with three states (CODE, STRING, COMMENT) would do it.\n",
"Regular expressions are not always a replacement for a real parser.\n",
"You can strip out all strings that aren't in comments by searching for the regular expression:\n'[^'\\r\\n]+'|(//.*|/\\*(?s:.*?)\\*/)\n\nand replacing with:\n$1\n\nEssentially, this searches for the regex string|(comment) which matches a string or a comment, capturing the comment. The replacement is either nothing if a string was matched or the comment if a comment was matched.\nThough regular expressions are not a replacement for a real parser you can quickly build a rudimentary parser by creating a giant regex that alternates all of the tokens you're interested in (comments and strings in this case). If you're writing a bit of code to handle comments, but not those in strings, iterate over all the matches of the above regex, and count the characters in the first capturing group if it participated in the match.\n"
] |
[
6,
2,
2
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002575810_python_regex.txt
|
Q:
File io error Python
I have a program that monitors a folder with word documents for any modifications made on the files. The error -Windows Error[2] The system cannot find the file specified- comes when I run the program, open a .doc within the folder make some changes and save it. Any suggestions on how to fix this?
Edit1: the actual error code is like this
File "C:\Users\keinsfield\Desktop\docu.py", line 27, in check
if info[0]==os.stat(os.path.join(r"C:\Users\keinsfield\Desktop\colegio",file
).st_ctime:
WindowsError: [Error 2] The system cannot find the file specified: 'C:\\Users\\k
insfield\\Desktop\\colegio\\~WRD1761.tmp'
Here's the code:
def archivar():
txt = open('archivo.txt', 'r+' )
for rootdir, dirs, files in os.walk(r"C:\Users\keinsfield\Desktop\colegio"):
for file in files:
time = os.stat(os.path.join(rootdir, file)).st_ctime
txt.write(file +','+str(time) + '\n')
def check():
txt = [col.split(',') for col in (open('archivo.txt', 'r+').read().split('\n'))]
files = os.listdir(r"C:\Users\keinsfield\Desktop\colegio")
for file in files:
for info in txt:
if info[0]==os.stat(os.path.join(r"C:\Users\keinsfield\Desktop\colegio",file)).st_ctime:
print "modified"
A:
try to use os.path.join() eg
root="c:\\"
path=os.path.join(root,"Users","keinsfield","Desktop","colegio")
....
for rootdir, dirs, files in os.walk(path):
....
A:
I think from the traceback it's quite clear that the temporary file was deleted between os.walk and os.stat calls. You don't really need to use the os.walk if you're not recursing into the subdirectories. You could use glob.iglob to obtain the list of only doc files:
for file in glob.iglob(os.path.join(root, '*.doc')):
print(file)
|
File io error Python
|
I have a program that monitors a folder with word documents for any modifications made on the files. The error -Windows Error[2] The system cannot find the file specified- comes when I run the program, open a .doc within the folder make some changes and save it. Any suggestions on how to fix this?
Edit1: the actual error code is like this
File "C:\Users\keinsfield\Desktop\docu.py", line 27, in check
if info[0]==os.stat(os.path.join(r"C:\Users\keinsfield\Desktop\colegio",file
).st_ctime:
WindowsError: [Error 2] The system cannot find the file specified: 'C:\\Users\\k
insfield\\Desktop\\colegio\\~WRD1761.tmp'
Here's the code:
def archivar():
txt = open('archivo.txt', 'r+' )
for rootdir, dirs, files in os.walk(r"C:\Users\keinsfield\Desktop\colegio"):
for file in files:
time = os.stat(os.path.join(rootdir, file)).st_ctime
txt.write(file +','+str(time) + '\n')
def check():
txt = [col.split(',') for col in (open('archivo.txt', 'r+').read().split('\n'))]
files = os.listdir(r"C:\Users\keinsfield\Desktop\colegio")
for file in files:
for info in txt:
if info[0]==os.stat(os.path.join(r"C:\Users\keinsfield\Desktop\colegio",file)).st_ctime:
print "modified"
|
[
"try to use os.path.join() eg\nroot=\"c:\\\\\"\npath=os.path.join(root,\"Users\",\"keinsfield\",\"Desktop\",\"colegio\")\n....\n for rootdir, dirs, files in os.walk(path):\n ....\n\n",
"I think from the traceback it's quite clear that the temporary file was deleted between os.walk and os.stat calls. You don't really need to use the os.walk if you're not recursing into the subdirectories. You could use glob.iglob to obtain the list of only doc files:\nfor file in glob.iglob(os.path.join(root, '*.doc')):\n print(file)\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"file_io",
"python"
] |
stackoverflow_0002582550_file_io_python.txt
|
Q:
python unichr problem
I've got some problem with unichr() on my server. Please see below:
On my server (Ubuntu 9.04):
>>> print unichr(255)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128)
On my desktop (Ubuntu 9.10):
>>> print unichr(255)
ÿ
I'm fairly new to python so I don't know how to solve this. Anyone care to help? Thanks.
A:
When using the "print" keyword, you'll be writing to the sys.stdout output stream. sys.stdout can usually only display Unicode strings if the characters can be converted to ascii using str(message).
You'll need to encode to your OS's terminal encoding when printing to be able to do this.
The locale module can sometimes detect the encoding of the output console:
import locale
print unichr(0xff).encode(locale.getdefaultlocale()[1], 'replace')
but it's usually better to just specify the encoding yourself, as python often gets it wrong:
print unichr(0xff).encode('latin-1', 'replace')
UTF-8 or latin-1 I think is often used in many modern linux distros.
If you know the encoding of your console, the lines below will encode Unicode strings automatically when you use "print":
import sys
import codecs
sys.stdout = codecs.getwriter(ENCODING)(sys.stdout)
If the encoding is ascii or something similar, you may need to change the console encoding of your OS to be able to display that character.
See also: http://wiki.python.org/moin/PrintFails
A:
The terminal settings on your server are different, probably set to 7-bit US ASCII.
A:
It's not really unichr() related. Problem is with locale setting in your server environment, as it's probably set to something like en_US and it's not unicode aware.
A:
Consider using an explicit encoding when printing unicode strings where OS settings are not uniform.
unicode.encode([encoding[, errors]])
Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Codec Base Classes. For a list of possible encodings, see section Standard Encodings.
For example,
>>> print unichr(0xff).encode('iso8859-1')
����??
>>>
|
python unichr problem
|
I've got some problem with unichr() on my server. Please see below:
On my server (Ubuntu 9.04):
>>> print unichr(255)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128)
On my desktop (Ubuntu 9.10):
>>> print unichr(255)
ÿ
I'm fairly new to python so I don't know how to solve this. Anyone care to help? Thanks.
|
[
"When using the \"print\" keyword, you'll be writing to the sys.stdout output stream. sys.stdout can usually only display Unicode strings if the characters can be converted to ascii using str(message). \nYou'll need to encode to your OS's terminal encoding when printing to be able to do this.\nThe locale module can sometimes detect the encoding of the output console:\nimport locale\nprint unichr(0xff).encode(locale.getdefaultlocale()[1], 'replace')\n\nbut it's usually better to just specify the encoding yourself, as python often gets it wrong:\nprint unichr(0xff).encode('latin-1', 'replace')\n\nUTF-8 or latin-1 I think is often used in many modern linux distros.\nIf you know the encoding of your console, the lines below will encode Unicode strings automatically when you use \"print\":\nimport sys\nimport codecs\nsys.stdout = codecs.getwriter(ENCODING)(sys.stdout)\n\nIf the encoding is ascii or something similar, you may need to change the console encoding of your OS to be able to display that character.\nSee also: http://wiki.python.org/moin/PrintFails\n",
"The terminal settings on your server are different, probably set to 7-bit US ASCII.\n",
"It's not really unichr() related. Problem is with locale setting in your server environment, as it's probably set to something like en_US and it's not unicode aware.\n",
"Consider using an explicit encoding when printing unicode strings where OS settings are not uniform.\n\nunicode.encode([encoding[, errors]])\nReturn an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Codec Base Classes. For a list of possible encodings, see section Standard Encodings.\n\nFor example,\n>>> print unichr(0xff).encode('iso8859-1')\n����??\n>>> \n\n"
] |
[
6,
2,
2,
1
] |
[] |
[] |
[
"python",
"ubuntu",
"unicode"
] |
stackoverflow_0002583425_python_ubuntu_unicode.txt
|
Q:
Dynamically create class attributes
I need to dynamically create class attributes from a DEFAULTS dictionary.
defaults = {
'default_value1':True,
'default_value2':True,
'default_value3':True,
}
class Settings(object):
default_value1 = some_complex_init_function(defaults[default_value1], ...)
default_value2 = some_complex_init_function(defaults[default_value2], ...)
default_value3 = some_complex_init_function(defaults[default_value3], ...)
I could also achive this by having sth. like __init__ for class creation, in order to dynamically create these attributes from dictionary and save a lot of code and stupid work.
How would you do this?
Thank you very much in advance!
A:
You could do it without metaclasses using decorators. This way is a bit more clear IMO:
def apply_defaults(cls):
defaults = {
'default_value1':True,
'default_value2':True,
'default_value3':True,
}
for name, value in defaults.items():
setattr(cls, name, some_complex_init_function(value, ...))
return cls
@apply_defaults
class Settings(object):
pass
Prior to Python 2.6 class decorators were unavailable. So you can write:
class Settings(object):
pass
Settings = apply_defaults(Settings)
in older versions of python.
In the provided example apply_defaults is reusable… Well, except that the defaults are hard-coded in the decorator's body :) If you have just a single case you can even simplify your code to this:
defaults = {
'default_value1':True,
'default_value2':True,
'default_value3':True,
}
class Settings(object):
"""Your implementation goes here as usual"""
for name, value in defaults.items():
setattr(Settings, name, some_complex_init_function(value, ...))
This is possible since classes (in the sense of types) are objects themselves in Python.
A:
I think that's case for metaclass:
class SettingsMeta(type):
def __new__(cls, name, bases, dct):
for name, value in defaults.items():
dct[name] = some_complex_init_function(value, ...)
return type.__new__(cls, name, bases, dct)
class Settings(object):
__metaclass__ = SettingsMeta
A:
When defining a class, the local namespace will be converted into the class namespace at the conclusion of the class body. As such, you can accomplish this with:
class Settings(object):
for key, val in defaults.iteritems():
locals()[key] = some_complex_init_function(val, ...)
|
Dynamically create class attributes
|
I need to dynamically create class attributes from a DEFAULTS dictionary.
defaults = {
'default_value1':True,
'default_value2':True,
'default_value3':True,
}
class Settings(object):
default_value1 = some_complex_init_function(defaults[default_value1], ...)
default_value2 = some_complex_init_function(defaults[default_value2], ...)
default_value3 = some_complex_init_function(defaults[default_value3], ...)
I could also achive this by having sth. like __init__ for class creation, in order to dynamically create these attributes from dictionary and save a lot of code and stupid work.
How would you do this?
Thank you very much in advance!
|
[
"You could do it without metaclasses using decorators. This way is a bit more clear IMO:\ndef apply_defaults(cls):\n defaults = {\n 'default_value1':True,\n 'default_value2':True,\n 'default_value3':True,\n }\n for name, value in defaults.items():\n setattr(cls, name, some_complex_init_function(value, ...))\n return cls\n\n@apply_defaults\nclass Settings(object):\n pass\n\nPrior to Python 2.6 class decorators were unavailable. So you can write:\nclass Settings(object):\n pass\nSettings = apply_defaults(Settings)\n\nin older versions of python.\nIn the provided example apply_defaults is reusable… Well, except that the defaults are hard-coded in the decorator's body :) If you have just a single case you can even simplify your code to this:\ndefaults = {\n 'default_value1':True,\n 'default_value2':True,\n 'default_value3':True,\n}\n\nclass Settings(object):\n \"\"\"Your implementation goes here as usual\"\"\"\n\nfor name, value in defaults.items():\n setattr(Settings, name, some_complex_init_function(value, ...))\n\nThis is possible since classes (in the sense of types) are objects themselves in Python.\n",
"I think that's case for metaclass:\nclass SettingsMeta(type):\n def __new__(cls, name, bases, dct):\n for name, value in defaults.items():\n dct[name] = some_complex_init_function(value, ...)\n return type.__new__(cls, name, bases, dct)\n\nclass Settings(object):\n __metaclass__ = SettingsMeta\n\n",
"When defining a class, the local namespace will be converted into the class namespace at the conclusion of the class body. As such, you can accomplish this with:\nclass Settings(object):\n for key, val in defaults.iteritems():\n locals()[key] = some_complex_init_function(val, ...)\n\n"
] |
[
31,
5,
2
] |
[] |
[] |
[
"class_attributes",
"python"
] |
stackoverflow_0002583620_class_attributes_python.txt
|
Q:
Python Windows File Copy with Wildcard Support
I've been doing this all the time:
result = subprocess.call(['copy', '123*.xml', 'out_folder\\.', '/y'])
if result == 0:
do_something()
else:
do_something_else()
Until today I started to look into pywin32 modules, then I saw functions like win32file.CopyFiles(), but then I found it may not support copying files to a directory. Maybe this functionality is hidden somewhere, but I haven't found it yet.
I've also tried "glob" and "shutil" combination, but "glob" is incredibly slow if there are many files.
So, how do you emulate this Windows command with Python?
copy 123*.xml out_folder\. /y
A:
The following code provides a portable implementation.
Note that I'm using iglob (added in Python 2.5) which creates a generator, so it does not load the entire list of files in memory first (which is what glob does).
from glob import iglob
from shutil import copy
from os.path import join
def copy_files(src_glob, dst_folder):
for fname in iglob(src_glob):
copy(fname, join(dst_folder, fname))
if __name__=='__main__':
copy_files("123*.xml", "out_folder")
Additional documentation:
shutil.copy
os.path.join
glob.iglob
A:
The below example is fairly naive - doesn't do any checking if something goes wrong, and doesn't create any directories, but might do what you want:
import glob
import shutil
for path in glob.iglob('123*.xml'):
shutil.copy(path, 'out_folder/%s' % path)
See also: http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
Using win32file/SHFileOperation copy seems to be more functional, but aren't as portable and are more complicated to use.
A:
Look at glob and shutil before going any further.
Forking a subprocess to copy a file is relatively inefficient. Using shutil will be more efficient.
A:
"glob" is incredibly slow if there are
many files.
glob is slow is there are a lot of results because it returns one huge list of all the results in a "big bang" approach. If there are a lot of results this will use a lot of memory and take a long time.
Use iglob instead, as suggested by a previous poster. iglob constructs and returns one iterator object that can be used to loop over the results, without ever having them all in memory at the same time. It's much more efficient if there are a lot of matches.
In general, whenever you write code like "for x in [glob.glob ...]" you should be using glob.iglob instead.
A:
import os
import shutil
path=os.path.join("/home","mypath")
destination=os.path.join("/destination","dir")
for r,d,f in os.walk(path):
for files in f:
if files.endswith(".xml"):
try:
shutil.copy(os.path.join(r,files) , destination)
except IOError,e:
print e
|
Python Windows File Copy with Wildcard Support
|
I've been doing this all the time:
result = subprocess.call(['copy', '123*.xml', 'out_folder\\.', '/y'])
if result == 0:
do_something()
else:
do_something_else()
Until today I started to look into pywin32 modules, then I saw functions like win32file.CopyFiles(), but then I found it may not support copying files to a directory. Maybe this functionality is hidden somewhere, but I haven't found it yet.
I've also tried "glob" and "shutil" combination, but "glob" is incredibly slow if there are many files.
So, how do you emulate this Windows command with Python?
copy 123*.xml out_folder\. /y
|
[
"The following code provides a portable implementation. \nNote that I'm using iglob (added in Python 2.5) which creates a generator, so it does not load the entire list of files in memory first (which is what glob does).\nfrom glob import iglob\nfrom shutil import copy\nfrom os.path import join\n\ndef copy_files(src_glob, dst_folder):\n for fname in iglob(src_glob):\n copy(fname, join(dst_folder, fname))\n\nif __name__=='__main__':\n copy_files(\"123*.xml\", \"out_folder\")\n\nAdditional documentation:\n\nshutil.copy\nos.path.join\nglob.iglob\n\n",
"The below example is fairly naive - doesn't do any checking if something goes wrong, and doesn't create any directories, but might do what you want:\nimport glob\nimport shutil\n\nfor path in glob.iglob('123*.xml'):\n shutil.copy(path, 'out_folder/%s' % path)\n\nSee also: http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html\nUsing win32file/SHFileOperation copy seems to be more functional, but aren't as portable and are more complicated to use.\n",
"Look at glob and shutil before going any further.\nForking a subprocess to copy a file is relatively inefficient. Using shutil will be more efficient.\n",
"\n\"glob\" is incredibly slow if there are\n many files.\n\nglob is slow is there are a lot of results because it returns one huge list of all the results in a \"big bang\" approach. If there are a lot of results this will use a lot of memory and take a long time.\nUse iglob instead, as suggested by a previous poster. iglob constructs and returns one iterator object that can be used to loop over the results, without ever having them all in memory at the same time. It's much more efficient if there are a lot of matches.\nIn general, whenever you write code like \"for x in [glob.glob ...]\" you should be using glob.iglob instead.\n",
"import os\nimport shutil\npath=os.path.join(\"/home\",\"mypath\")\ndestination=os.path.join(\"/destination\",\"dir\")\nfor r,d,f in os.walk(path):\n for files in f:\n if files.endswith(\".xml\"):\n try:\n shutil.copy(os.path.join(r,files) , destination)\n except IOError,e:\n print e\n\n"
] |
[
10,
7,
3,
1,
1
] |
[] |
[] |
[
"file",
"python",
"pywin32",
"wildcard"
] |
stackoverflow_0002584414_file_python_pywin32_wildcard.txt
|
Q:
Search jpeg files using python
My requirement is to search for jpeg images files in a directory using python script and list the file names. Can anyone help me on how to identify jpeg images files.
Thanks in advance...
A:
If you need to search a single folder non-recursively you can simply do
>>> import glob
>>> glob.glob("D:\\bluetooth\*.jpg")
['D:\\bluetooth\\Image1475.jpg', 'D:\\bluetooth\\Image1514.jpg']
Read more about glob here, you use do unix like wildcard searches e.g.
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
A:
If you want to scan subfolders:
import os
for root, subdirs, files in os.walk(DIRECTORY):
for file in files:
if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg'):
print os.path.join(root, file)
Otherwise, using one of the other glob functions in the other answers, or this:
import os
for f in os.listdir(DIRECTORY):
if os.path.splitext(f)[1].lower() in ('.jpg', '.jpeg'):
print os.path.join(DIRECTORY, f)
should work OK.
A:
Use the magic module to get the MIME type, and look for image/jpeg.
A:
import os
path=os.path.join("/home","mypath","to_search")
for r,d,f in os.walk(path):
for files in f:
if files[-3:].lower()=='jpg' of files[-4:].lower() =="jpeg":
print "found: ",os.path.join(r,files)
A:
If you want to determine the image format by file contents, you can use the Python Imaging Library:
import Image
try:
img = Image.open('maybe_jpeg_file')
print img.format # Will return 'JPEG' for JPEG files.
except IOError:
print "Not an image file or unreadable."
|
Search jpeg files using python
|
My requirement is to search for jpeg images files in a directory using python script and list the file names. Can anyone help me on how to identify jpeg images files.
Thanks in advance...
|
[
"If you need to search a single folder non-recursively you can simply do\n>>> import glob\n>>> glob.glob(\"D:\\\\bluetooth\\*.jpg\")\n['D:\\\\bluetooth\\\\Image1475.jpg', 'D:\\\\bluetooth\\\\Image1514.jpg']\n\nRead more about glob here, you use do unix like wildcard searches e.g.\n>>> import glob\n>>> glob.glob('./[0-9].*')\n['./1.gif', './2.txt']\n>>> glob.glob('*.gif')\n['1.gif', 'card.gif']\n>>> glob.glob('?.gif')\n['1.gif']\n\n",
"If you want to scan subfolders:\nimport os\n\nfor root, subdirs, files in os.walk(DIRECTORY):\n for file in files:\n if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg'):\n print os.path.join(root, file)\n\nOtherwise, using one of the other glob functions in the other answers, or this:\nimport os\n\nfor f in os.listdir(DIRECTORY):\n if os.path.splitext(f)[1].lower() in ('.jpg', '.jpeg'):\n print os.path.join(DIRECTORY, f)\n\nshould work OK.\n",
"Use the magic module to get the MIME type, and look for image/jpeg.\n",
"import os\npath=os.path.join(\"/home\",\"mypath\",\"to_search\")\nfor r,d,f in os.walk(path):\n for files in f:\n if files[-3:].lower()=='jpg' of files[-4:].lower() ==\"jpeg\":\n print \"found: \",os.path.join(r,files)\n\n",
"If you want to determine the image format by file contents, you can use the Python Imaging Library:\nimport Image\ntry:\n img = Image.open('maybe_jpeg_file')\n print img.format # Will return 'JPEG' for JPEG files.\nexcept IOError:\n print \"Not an image file or unreadable.\"\n\n"
] |
[
10,
6,
2,
1,
1
] |
[] |
[] |
[
"file",
"python",
"search"
] |
stackoverflow_0002584589_file_python_search.txt
|
Q:
Handling import errors when using doctest
every now and then when I code in Python, I have to do without certain third-party modules.
Eg. when I'm writing user authentication, it can be done in several ways and one of them is by using LDAP. However if the user does not want to use LDAP auth., he can choose a different option in a config file and in that case he should not have to have ldap module installed.
Generally I solve this by:
if config.foo:
import ldap_auth as auth
elif config.foo2:
import other_auth as auth
...
auth.do_stuff(...)
and I import ldap module in ldap_auth module only. I personally find this quite nice, however, of course, doctests raise an ImportError when trying to execute ldap_auth.
Now, I know I could catch it by try-ing to import the ldap module in ldap_auth, but that just kinda messes up the nice looking code (the whole point of doing the whole "import ldap_auth as auth" bussiness was to avoid ImportErrors).
Is there any more elegant way to prevent doctests from raising ImportErrors when using this "pattern"?
Cheers,
Tom
A:
The recommended way is
try:
import foo as auth
except ImportError:
import bar as auth
It avoids race conditions and I don't think it looks bad.
|
Handling import errors when using doctest
|
every now and then when I code in Python, I have to do without certain third-party modules.
Eg. when I'm writing user authentication, it can be done in several ways and one of them is by using LDAP. However if the user does not want to use LDAP auth., he can choose a different option in a config file and in that case he should not have to have ldap module installed.
Generally I solve this by:
if config.foo:
import ldap_auth as auth
elif config.foo2:
import other_auth as auth
...
auth.do_stuff(...)
and I import ldap module in ldap_auth module only. I personally find this quite nice, however, of course, doctests raise an ImportError when trying to execute ldap_auth.
Now, I know I could catch it by try-ing to import the ldap module in ldap_auth, but that just kinda messes up the nice looking code (the whole point of doing the whole "import ldap_auth as auth" bussiness was to avoid ImportErrors).
Is there any more elegant way to prevent doctests from raising ImportErrors when using this "pattern"?
Cheers,
Tom
|
[
"The recommended way is\ntry:\n import foo as auth\nexcept ImportError:\n import bar as auth\n\nIt avoids race conditions and I don't think it looks bad.\n"
] |
[
1
] |
[] |
[] |
[
"doctest",
"python"
] |
stackoverflow_0002584780_doctest_python.txt
|
Q:
python: can't terminate a thread hung in socket.recvfrom() call
I cannot get a way to terminate a thread that is hung in a socket.recvfrom() call. For example, ctrl+c that should trigger KeyboardInterrupt exception can't be caught. Here is a script I've used for testing:
from socket import *
from threading import Thread
from sys import exit
class TestThread(Thread):
def __init__(self,host="localhost",port=9999):
self.sock = socket(AF_INET,SOCK_DGRAM)
self.sock.bind((host,port))
super(TestThread,self).__init__()
def run(self):
while True:
try:
recv_data,addr = self.sock.recvfrom(1024)
except (KeyboardInterrupt, SystemExit):
sys.exit()
if __name__ == "__main__":
server_thread = TestThread()
server_thread.start()
while True: pass
The main thread (the one that executes infinite loop) exits. However the thread that I explicitly create, keeps hanging in recvfrom().
Please, help me resolve this.
A:
Keyboard interrupts are always caught on the main thread -- never on "child" threads. To avoid server_thread keeping the process alive when the main thread exits, do
server_thread.daemon = True
before you call server_thread.start().
BTW, your while True: pass in the main thread is needlessly burning CPU cycles. You should at least change it to something like while True: time.sleep(1.0). But that doesn't change the semantics of your code -- just gets it down from 99% CPU or so, to (I'd guess) < 5%;-).
A:
You should open a pipe from the main thread to the network thread and 'select' on both the socket and the pipe. When you want to terminate the network thread, just send a byte through the pipe from the main thread and act accordingly in the network thread.
Just my 2 cents.
|
python: can't terminate a thread hung in socket.recvfrom() call
|
I cannot get a way to terminate a thread that is hung in a socket.recvfrom() call. For example, ctrl+c that should trigger KeyboardInterrupt exception can't be caught. Here is a script I've used for testing:
from socket import *
from threading import Thread
from sys import exit
class TestThread(Thread):
def __init__(self,host="localhost",port=9999):
self.sock = socket(AF_INET,SOCK_DGRAM)
self.sock.bind((host,port))
super(TestThread,self).__init__()
def run(self):
while True:
try:
recv_data,addr = self.sock.recvfrom(1024)
except (KeyboardInterrupt, SystemExit):
sys.exit()
if __name__ == "__main__":
server_thread = TestThread()
server_thread.start()
while True: pass
The main thread (the one that executes infinite loop) exits. However the thread that I explicitly create, keeps hanging in recvfrom().
Please, help me resolve this.
|
[
"Keyboard interrupts are always caught on the main thread -- never on \"child\" threads. To avoid server_thread keeping the process alive when the main thread exits, do\nserver_thread.daemon = True\n\nbefore you call server_thread.start().\nBTW, your while True: pass in the main thread is needlessly burning CPU cycles. You should at least change it to something like while True: time.sleep(1.0). But that doesn't change the semantics of your code -- just gets it down from 99% CPU or so, to (I'd guess) < 5%;-).\n",
"You should open a pipe from the main thread to the network thread and 'select' on both the socket and the pipe. When you want to terminate the network thread, just send a byte through the pipe from the main thread and act accordingly in the network thread.\nJust my 2 cents.\n"
] |
[
4,
1
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0002585680_multithreading_python.txt
|
Q:
How to process python generated error messages my own way?
For some code as follows,
opts, args = getopt.getopt(sys.argv[1:], "c:", ...
for o,v in opts:
...
elif o in ("-c", "--%s" % checkString):
kCheckOnly = True
clientTemp = v
If I don't give the parameter after the -c, I get the error messages as follows.
Traceback (most recent call last):
File "niFpgaTimingViolationMain.py", line 100, in
opts, args = getopt.getopt(sys.argv[1:], "hdc:t:",[helpString, debugString, checkString, twxString])
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getopt.py", line 91, in getopt
opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getopt.py", line 195, in do_shorts
opt)
getopt.GetoptError: option -c requires argument
Is there any way to catch this error, and process it to print something like this? It seems that just wrapping the code in try/except doesn't work.
ERROR: You forgot to give the file name after -c option
A:
You can catch getopt.GetoptError and check the 'opt' and 'msg' attributes yourself:
try:
opts, args = getopt.getopt(sys.argv[1:], "c:", ...
except getopt.GetoptError, e:
if e.opt == 'c' and 'requires argument' in e.msg:
print >>sys.stderr, 'ERROR: You forgot to give the file name after -c option'
sys.exit(-1)
A:
the correct answer is to use the OptionParser module instead of trying to "roll your own".
|
How to process python generated error messages my own way?
|
For some code as follows,
opts, args = getopt.getopt(sys.argv[1:], "c:", ...
for o,v in opts:
...
elif o in ("-c", "--%s" % checkString):
kCheckOnly = True
clientTemp = v
If I don't give the parameter after the -c, I get the error messages as follows.
Traceback (most recent call last):
File "niFpgaTimingViolationMain.py", line 100, in
opts, args = getopt.getopt(sys.argv[1:], "hdc:t:",[helpString, debugString, checkString, twxString])
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getopt.py", line 91, in getopt
opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getopt.py", line 195, in do_shorts
opt)
getopt.GetoptError: option -c requires argument
Is there any way to catch this error, and process it to print something like this? It seems that just wrapping the code in try/except doesn't work.
ERROR: You forgot to give the file name after -c option
|
[
"You can catch getopt.GetoptError and check the 'opt' and 'msg' attributes yourself:\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], \"c:\", ...\nexcept getopt.GetoptError, e:\n if e.opt == 'c' and 'requires argument' in e.msg:\n print >>sys.stderr, 'ERROR: You forgot to give the file name after -c option'\n sys.exit(-1)\n\n",
"the correct answer is to use the OptionParser module instead of trying to \"roll your own\".\n"
] |
[
3,
3
] |
[] |
[] |
[
"getopt",
"python"
] |
stackoverflow_0002585803_getopt_python.txt
|
Q:
Python Memory leak - Solved, but still puzzled
I have successfully debugged my own memory leak problems. However, I have noticed some very strange occurence.
for fid, fv in freqDic.iteritems():
outf.write(fid+"\t") #ID
for i, term in enumerate(domain): #Vector
tfidf = self.tf(term, fv) * self.idf( term, docFreqDic)
if i == len(domain) - 1:
outf.write("%f\n" % tfidf)
else:
outf.write("%f\t" % tfidf)
outf.flush()
print "Memory increased by", int(self.memory_mon.usage()) - startMemory
outf.close()
def tf(self, term, freqVector):
total = freqVector[TOTAL]
if total == 0:
return 0
if term not in freqVector: ## When you don't have these lines memory leaks occurs
return 0 ##
return float(freqVector[term]) / freqVector[TOTAL]
def idf(self, term, docFrequencyPerTerm):
if term not in docFrequencyPerTerm:
return 0
return math.log( float(docFrequencyPerTerm[TOTAL])/docFrequencyPerTerm[term])
Basically let me describe my problem:
1) I am doing tfidf calculations
2) I traced that the source of memory leaks is coming from defaultdict.
3) I am using the memory_mon from How to get current CPU and RAM usage in Python?
4) The reason for my memory leaks is as follows: a) in self.tf, if the lines: if term not in freqVector: return 0 are not added that will cause the memory leak. (I verified this myself using memory_mon and noticed a sharp increase in memory that kept on increasing)
The solution to my problem was 1) since fv is a defaultdict, any reference to it that are not found in fv will create an entry. Over a very large domain, this will cause memory leaks.
I decided to use dict instead of default dict and the memory problem did go away.
My only puzzle is: since fv is created in "for fid, fv in freqDic.iteritems():" shouldn't fv be destroyed at the end of every for loop? I tried putting gc.collect() at the end of the for loop but gc was not able to collect everything (returns 0). Yes, the hypothesis is right, but the memory should stay fairly consistent with ever for loop if for loops do destroy all temp variables.
This is what it looks like with that two line in self.tf:
Memory increased by 12
Memory increased by 948
Memory increased by 28
Memory increased by 36
Memory increased by 36
Memory increased by 32
Memory increased by 28
Memory increased by 32
Memory increased by 32
Memory increased by 32
Memory increased by 40
Memory increased by 32
Memory increased by 32
Memory increased by 28
and without the the two line:
Memory increased by 1652
Memory increased by 3576
Memory increased by 4220
Memory increased by 5760
Memory increased by 7296
Memory increased by 8840
Memory increased by 10456
Memory increased by 12824
Memory increased by 13460
Memory increased by 15000
Memory increased by 17448
Memory increased by 18084
Memory increased by 19628
Memory increased by 22080
Memory increased by 22708
Memory increased by 24248
Memory increased by 26704
Memory increased by 27332
Memory increased by 28864
Memory increased by 30404
Memory increased by 32856
Memory increased by 33552
Memory increased by 35024
Memory increased by 36564
Memory increased by 39016
Memory increased by 39924
Memory increased by 42104
Memory increased by 42724
Memory increased by 44268
Memory increased by 46720
Memory increased by 47352
Memory increased by 48952
Memory increased by 50428
Memory increased by 51964
Memory increased by 53508
Memory increased by 55960
Memory increased by 56584
Memory increased by 58404
Memory increased by 59668
Memory increased by 61208
Memory increased by 62744
Memory increased by 64400
I look forward to your answer
EDIT:
It appears that my terminology might have been wrong (or appear to be wrong).
The memory leak I was referring to was NOT generated from freqVector[term]. (Looking up an nonexistent key in a defaultdict).
The actual memory leak I was talking about was the memory leak from for fid, fv in freqDic.iteritems()!! I know fv increased in size because of 1), but it should still be destroyed at the end of the loop! memory shouldn't keep on expanding. Is this not memory leak?
A:
Iterating over freqDict does not generate new values, but passes references to the values already held by the dict. This means you add new values to the fv which is held by freqDict even after the loop.
Another solution would be to clear freqDict after looping over it.
In general, Python does pass everything by reference, although it sometimes it appears otherwise. Strings and Integers are immutable and the object, which they represent, gets replaced if they are changed.
A:
I suspect that the memory usage of Python might be increasing because floating point numbers are also objects in Python, and the interpreter maintains a freelist of floats which is unbounded and immortal. Therefore, whenever a float calculation results in a new float that did not occur before, Python allocates a new float object in the freelist and then it keeps the object around in case it might need it later.
See a similar discussion in the Python bug tracker here.
A:
It is not a memory leak, as memory is not leaking, it is being taken by your default dict e.g.
from collections import defaultdict
d = defaultdict(int)
for i in xrange(10**7):
a = d[i]
Do you think it is a memory leak? you are assigning values to a dict and memory usage should increase due to it, it is similar to this
d = {}
for i in xrange(10**7):
d[i] = 0
which is not a memory leak.
|
Python Memory leak - Solved, but still puzzled
|
I have successfully debugged my own memory leak problems. However, I have noticed some very strange occurence.
for fid, fv in freqDic.iteritems():
outf.write(fid+"\t") #ID
for i, term in enumerate(domain): #Vector
tfidf = self.tf(term, fv) * self.idf( term, docFreqDic)
if i == len(domain) - 1:
outf.write("%f\n" % tfidf)
else:
outf.write("%f\t" % tfidf)
outf.flush()
print "Memory increased by", int(self.memory_mon.usage()) - startMemory
outf.close()
def tf(self, term, freqVector):
total = freqVector[TOTAL]
if total == 0:
return 0
if term not in freqVector: ## When you don't have these lines memory leaks occurs
return 0 ##
return float(freqVector[term]) / freqVector[TOTAL]
def idf(self, term, docFrequencyPerTerm):
if term not in docFrequencyPerTerm:
return 0
return math.log( float(docFrequencyPerTerm[TOTAL])/docFrequencyPerTerm[term])
Basically let me describe my problem:
1) I am doing tfidf calculations
2) I traced that the source of memory leaks is coming from defaultdict.
3) I am using the memory_mon from How to get current CPU and RAM usage in Python?
4) The reason for my memory leaks is as follows: a) in self.tf, if the lines: if term not in freqVector: return 0 are not added that will cause the memory leak. (I verified this myself using memory_mon and noticed a sharp increase in memory that kept on increasing)
The solution to my problem was 1) since fv is a defaultdict, any reference to it that are not found in fv will create an entry. Over a very large domain, this will cause memory leaks.
I decided to use dict instead of default dict and the memory problem did go away.
My only puzzle is: since fv is created in "for fid, fv in freqDic.iteritems():" shouldn't fv be destroyed at the end of every for loop? I tried putting gc.collect() at the end of the for loop but gc was not able to collect everything (returns 0). Yes, the hypothesis is right, but the memory should stay fairly consistent with ever for loop if for loops do destroy all temp variables.
This is what it looks like with that two line in self.tf:
Memory increased by 12
Memory increased by 948
Memory increased by 28
Memory increased by 36
Memory increased by 36
Memory increased by 32
Memory increased by 28
Memory increased by 32
Memory increased by 32
Memory increased by 32
Memory increased by 40
Memory increased by 32
Memory increased by 32
Memory increased by 28
and without the the two line:
Memory increased by 1652
Memory increased by 3576
Memory increased by 4220
Memory increased by 5760
Memory increased by 7296
Memory increased by 8840
Memory increased by 10456
Memory increased by 12824
Memory increased by 13460
Memory increased by 15000
Memory increased by 17448
Memory increased by 18084
Memory increased by 19628
Memory increased by 22080
Memory increased by 22708
Memory increased by 24248
Memory increased by 26704
Memory increased by 27332
Memory increased by 28864
Memory increased by 30404
Memory increased by 32856
Memory increased by 33552
Memory increased by 35024
Memory increased by 36564
Memory increased by 39016
Memory increased by 39924
Memory increased by 42104
Memory increased by 42724
Memory increased by 44268
Memory increased by 46720
Memory increased by 47352
Memory increased by 48952
Memory increased by 50428
Memory increased by 51964
Memory increased by 53508
Memory increased by 55960
Memory increased by 56584
Memory increased by 58404
Memory increased by 59668
Memory increased by 61208
Memory increased by 62744
Memory increased by 64400
I look forward to your answer
EDIT:
It appears that my terminology might have been wrong (or appear to be wrong).
The memory leak I was referring to was NOT generated from freqVector[term]. (Looking up an nonexistent key in a defaultdict).
The actual memory leak I was talking about was the memory leak from for fid, fv in freqDic.iteritems()!! I know fv increased in size because of 1), but it should still be destroyed at the end of the loop! memory shouldn't keep on expanding. Is this not memory leak?
|
[
"Iterating over freqDict does not generate new values, but passes references to the values already held by the dict. This means you add new values to the fv which is held by freqDict even after the loop.\nAnother solution would be to clear freqDict after looping over it.\nIn general, Python does pass everything by reference, although it sometimes it appears otherwise. Strings and Integers are immutable and the object, which they represent, gets replaced if they are changed.\n",
"I suspect that the memory usage of Python might be increasing because floating point numbers are also objects in Python, and the interpreter maintains a freelist of floats which is unbounded and immortal. Therefore, whenever a float calculation results in a new float that did not occur before, Python allocates a new float object in the freelist and then it keeps the object around in case it might need it later.\nSee a similar discussion in the Python bug tracker here.\n",
"It is not a memory leak, as memory is not leaking, it is being taken by your default dict e.g.\nfrom collections import defaultdict\n\nd = defaultdict(int)\nfor i in xrange(10**7):\n a = d[i]\n\nDo you think it is a memory leak? you are assigning values to a dict and memory usage should increase due to it, it is similar to this \nd = {}\nfor i in xrange(10**7):\n d[i] = 0\n\nwhich is not a memory leak.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"memory_leaks",
"python"
] |
stackoverflow_0002585712_memory_leaks_python.txt
|
Q:
Python HTTPSConnection.close() does not appear to close the connection?
I'm not sure if this is a bug or if I'm just doing something wrong. If I were to do an HTTP connection like this:
import httplib
http_connection = httplib.HTTPConnection("192.168.192.196")
http_connection.request("GET", "/")
http_connection.sock.settimeout(20)
response = http_connection.getresponse()
data = response.read()
http_connection.close()
Then at a DOS prompt, I do this:
netstat -ano | find /i "192.168.192.196:80" | find /i "ESTABLISHED"
I get nothing.
However, if I do the same thing, but change it to an HTTPSConnection:
import httplib
http_connection = httplib.HTTPSConnection("192.168.192.196")
http_connection.request("GET", "/")
http_connection.sock.settimeout(20)
response = http_connection.getresponse()
data = response.read()
http_connection.close()
Then do this:
netstat -ano | find /i "192.168.192.196:443" | find /i "ESTABLISHED"
I will actually see that the connection remains established until I actually ^Z out of the Python shell.
This is happening in one of the applications I'm responsible for. Python isn't actually hanging there - it's simply leaving the connection open.
Am I doing something wrong here? Do I need extra code to close the HTTPS connection?
This is Python 2.6.4, btw.
A:
Turns out that if you send the "Connection: close" HTTP header, this isn't an issue - although I still think that .close() should actually close the connection like it does for HTTPConnection.
|
Python HTTPSConnection.close() does not appear to close the connection?
|
I'm not sure if this is a bug or if I'm just doing something wrong. If I were to do an HTTP connection like this:
import httplib
http_connection = httplib.HTTPConnection("192.168.192.196")
http_connection.request("GET", "/")
http_connection.sock.settimeout(20)
response = http_connection.getresponse()
data = response.read()
http_connection.close()
Then at a DOS prompt, I do this:
netstat -ano | find /i "192.168.192.196:80" | find /i "ESTABLISHED"
I get nothing.
However, if I do the same thing, but change it to an HTTPSConnection:
import httplib
http_connection = httplib.HTTPSConnection("192.168.192.196")
http_connection.request("GET", "/")
http_connection.sock.settimeout(20)
response = http_connection.getresponse()
data = response.read()
http_connection.close()
Then do this:
netstat -ano | find /i "192.168.192.196:443" | find /i "ESTABLISHED"
I will actually see that the connection remains established until I actually ^Z out of the Python shell.
This is happening in one of the applications I'm responsible for. Python isn't actually hanging there - it's simply leaving the connection open.
Am I doing something wrong here? Do I need extra code to close the HTTPS connection?
This is Python 2.6.4, btw.
|
[
"Turns out that if you send the \"Connection: close\" HTTP header, this isn't an issue - although I still think that .close() should actually close the connection like it does for HTTPConnection.\n"
] |
[
0
] |
[] |
[] |
[
"https",
"python"
] |
stackoverflow_0002567974_https_python.txt
|
Q:
Is there an easy way to "append()" two dictionaries together in Python?
If I have two dictionaries I'd like to combine in Python, i.e.
a = {'1': 1, '2': 2}
b = {'3': 3, '4': 4}
If I run update on them it reorders the list:
a.update(b)
{'1': 1, '3': 3, '2': 2, '4': 4}
when what I really want is attach "b" to the end of "a":
{'1': 1, '2': 2, '3': 3, '4': 4}
Is there an easy way to attach "b" to the end of "a" without having to manually combine them like so:
for key in b:
a[key]=b[key]
Something like += or append() would be ideal, but of course neither works on dictionaries.
A:
A python dictionary has no ordering -- if in practice items appear in a particular order, that's purely a side-effect of the particular implementation and shouldn't be relied on.
A:
Dictionaries are unordered: they do not have a beginning or an end. Whether you use update or the for loop, the end result will still be unordered.
If you need ordering, use a list of tuples instead. Python 3.1 has an OrderedDict type which will also be in Python 2.7.
A:
Dictionaries are not ordered. If you need ordering, you might try something like a list.
A:
There is an ordered dictionary in the standard library as of Python 3.1.1, but the use-cases for it are limited. Typically if you are using a dictionary, you are simply interested in the mapping of keys to values, and not order. There are various recipes out there for ordered dictionaries as well if you aren't using Python 3.x but you should really first ask yourself if order is important and if so, whether or not you are using the right data structure.
A:
I think you're misunderstanding the use of dictionaries. You do not access them sequence or location. You access them from the keys, which in your case also happen to be numbers. They are hash tables and are supposed to work like this. You're doing it correctly.
|
Is there an easy way to "append()" two dictionaries together in Python?
|
If I have two dictionaries I'd like to combine in Python, i.e.
a = {'1': 1, '2': 2}
b = {'3': 3, '4': 4}
If I run update on them it reorders the list:
a.update(b)
{'1': 1, '3': 3, '2': 2, '4': 4}
when what I really want is attach "b" to the end of "a":
{'1': 1, '2': 2, '3': 3, '4': 4}
Is there an easy way to attach "b" to the end of "a" without having to manually combine them like so:
for key in b:
a[key]=b[key]
Something like += or append() would be ideal, but of course neither works on dictionaries.
|
[
"A python dictionary has no ordering -- if in practice items appear in a particular order, that's purely a side-effect of the particular implementation and shouldn't be relied on.\n",
"Dictionaries are unordered: they do not have a beginning or an end. Whether you use update or the for loop, the end result will still be unordered.\nIf you need ordering, use a list of tuples instead. Python 3.1 has an OrderedDict type which will also be in Python 2.7.\n",
"Dictionaries are not ordered. If you need ordering, you might try something like a list.\n",
"There is an ordered dictionary in the standard library as of Python 3.1.1, but the use-cases for it are limited. Typically if you are using a dictionary, you are simply interested in the mapping of keys to values, and not order. There are various recipes out there for ordered dictionaries as well if you aren't using Python 3.x but you should really first ask yourself if order is important and if so, whether or not you are using the right data structure.\n",
"I think you're misunderstanding the use of dictionaries. You do not access them sequence or location. You access them from the keys, which in your case also happen to be numbers. They are hash tables and are supposed to work like this. You're doing it correctly.\n"
] |
[
11,
2,
2,
1,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0002586273_dictionary_python.txt
|
Q:
Python analyze method calls from other classes/modules
I've got a Codebase of around 5,3k LOC with around 30 different classe. The code is already very well formatted and I want to improve it further by prefixing methods that are only called in the module that were defined in with a "_", in order to indicate that. Yes it would have been a good idea to do that from the beginning on but now it's too late :D
Basically I'm searching for a tool that will tell me if a method is not called outside of the module it was defined in, I'm not looking for stuff that will automatically convert the whole thing to use underscores, just a "simple" thing that tells me where I have to look for prefixing stuff.
I'd took a look at the AST module, but there's no easy way to get a list of method definitions and calls, also parsing the plain text yields just too many false positives. I don't insist in spending day(s) on reinventing the wheel when there might be an already existing solution to my problem.
A:
For me, this sounds like special case of coverage.
Thus I'd take a look at coverage.py or figleaf and modify it to ignore inter-module calls.
|
Python analyze method calls from other classes/modules
|
I've got a Codebase of around 5,3k LOC with around 30 different classe. The code is already very well formatted and I want to improve it further by prefixing methods that are only called in the module that were defined in with a "_", in order to indicate that. Yes it would have been a good idea to do that from the beginning on but now it's too late :D
Basically I'm searching for a tool that will tell me if a method is not called outside of the module it was defined in, I'm not looking for stuff that will automatically convert the whole thing to use underscores, just a "simple" thing that tells me where I have to look for prefixing stuff.
I'd took a look at the AST module, but there's no easy way to get a list of method definitions and calls, also parsing the plain text yields just too many false positives. I don't insist in spending day(s) on reinventing the wheel when there might be an already existing solution to my problem.
|
[
"For me, this sounds like special case of coverage.\nThus I'd take a look at coverage.py or figleaf and modify it to ignore inter-module calls. \n"
] |
[
0
] |
[] |
[] |
[
"code_analysis",
"methods",
"python"
] |
stackoverflow_0002586959_code_analysis_methods_python.txt
|
Q:
float change from python 3.0.1 to 3.1.2
I'm trying to learn python. I am using 3.1.2 and the o'reilly book is using 3.0.1
here is my code:
import urllib.request
price = (99.99)
while price > 4.74:
page = urllib.request.urlopen ("http://www.beans-r-us.biz/prices-loyalty.html")
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 6
price = float(text[start_of_price:end_of_price])
print ("Buy!")
Here is my error:
Traceback (most recent call last):
File "/Users/odin/Desktop/Coffe.py", line 14, in <module>
price = float(text[start_of_price:end_of_price])
ValueError: invalid literal for float(): 4.59</
>>>
What is wrong?
A:
The problem is that you have extra characters at the end of your float, probably because the content of the page changed since the code was written (the number appears to change every fifteen minute). You could try changing the following line to make the code slightly more robust:
end_of_price = text.find('<', start_of_price)
For an even better solution you should use something like BeautifulSoup to parse the HTML.
A:
You are calculating end_of_price as start_of_price + 6. Actually your price value seems to be only 4 characters long, so that you also include the two characters following in the string you want to convert to a float. Python then complains that 4.59</ is not a number.
If you instead set end_of_price to start_of_price + 4 it should work.
|
float change from python 3.0.1 to 3.1.2
|
I'm trying to learn python. I am using 3.1.2 and the o'reilly book is using 3.0.1
here is my code:
import urllib.request
price = (99.99)
while price > 4.74:
page = urllib.request.urlopen ("http://www.beans-r-us.biz/prices-loyalty.html")
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 6
price = float(text[start_of_price:end_of_price])
print ("Buy!")
Here is my error:
Traceback (most recent call last):
File "/Users/odin/Desktop/Coffe.py", line 14, in <module>
price = float(text[start_of_price:end_of_price])
ValueError: invalid literal for float(): 4.59</
>>>
What is wrong?
|
[
"The problem is that you have extra characters at the end of your float, probably because the content of the page changed since the code was written (the number appears to change every fifteen minute). You could try changing the following line to make the code slightly more robust:\nend_of_price = text.find('<', start_of_price)\n\nFor an even better solution you should use something like BeautifulSoup to parse the HTML.\n",
"You are calculating end_of_price as start_of_price + 6. Actually your price value seems to be only 4 characters long, so that you also include the two characters following in the string you want to convert to a float. Python then complains that 4.59</ is not a number.\nIf you instead set end_of_price to start_of_price + 4 it should work.\n"
] |
[
5,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002587010_python.txt
|
Q:
How to match a variable list of items separated by commas
I want to turn something like this
CS 240, CS 246, ECE 222, ... (more or less); Software Engineering students only
into
('CS 240', 'CS 246', 'ECE 222', 'ECE 220')
in Python, code that matches a single course looks like
>>> re.search('([A-Z]{2,5} \d{3})', 'SE 112').groups()
('SE 112',)
I prefer a regular expression only method because I have a bunch of other alternate reg exps using '|' to combine them. However, a method with split is acceptable.
A:
>>> a="CS 240, CS 246, ECE 222"
>>> b=tuple(a.strip() for a in a.split(','))
>>> b
('CS 240', 'CS 246', 'ECE 222')
>>>
A:
Isn't the csv standard library module ( http://docs.python.org/library/csv.html ) what you are looking for?
A:
This method uses regular expressions and matches your input:
>>> import re
>>> re.findall("\w+\s\d+", "CS 240, CS 246, ECE 222")
['CS 240', 'CS 246', 'ECE 222']
It does not look for the comma. Instead it looks for anything but the comma: it first matches multiple word characters, then a space character, then multiple digits. Findall looks for all occurrences of this pattern.
|
How to match a variable list of items separated by commas
|
I want to turn something like this
CS 240, CS 246, ECE 222, ... (more or less); Software Engineering students only
into
('CS 240', 'CS 246', 'ECE 222', 'ECE 220')
in Python, code that matches a single course looks like
>>> re.search('([A-Z]{2,5} \d{3})', 'SE 112').groups()
('SE 112',)
I prefer a regular expression only method because I have a bunch of other alternate reg exps using '|' to combine them. However, a method with split is acceptable.
|
[
">>> a=\"CS 240, CS 246, ECE 222\"\n>>> b=tuple(a.strip() for a in a.split(','))\n>>> b\n('CS 240', 'CS 246', 'ECE 222')\n>>> \n\n",
"Isn't the csv standard library module ( http://docs.python.org/library/csv.html ) what you are looking for?\n",
"This method uses regular expressions and matches your input:\n>>> import re\n>>> re.findall(\"\\w+\\s\\d+\", \"CS 240, CS 246, ECE 222\")\n['CS 240', 'CS 246', 'ECE 222']\n\nIt does not look for the comma. Instead it looks for anything but the comma: it first matches multiple word characters, then a space character, then multiple digits. Findall looks for all occurrences of this pattern.\n"
] |
[
5,
3,
0
] |
[] |
[] |
[
"pattern_matching",
"python",
"regex"
] |
stackoverflow_0002586849_pattern_matching_python_regex.txt
|
Q:
Python: Picking an element without replacement
I would like to slice random letters from a string.
Given
s="howdy"
I would like to pick elements from 's' without replacement but keep the index number.
For example
>>> random.sample(s,len(s))
['w', 'h', 'o', 'd', 'y']
is close to what I want, but I would actually prefer something like
[('w',2), ('h',0), ('o',1), ('d',3), ('y',4)]
with letter-index pairs. This is important because the same letter appears in 's' more than once. ie) "letter" where 't' appears twice but I need to distinguish the first 't' from the second.
Ideally I actually only need to generate/pick letters as I need them but scrambling and calculating all the letters at once (ie: in a list as shown above) is ok.
A:
>>> random.sample(list(enumerate(a)), 5)
[(1, 'o'), (0, 'h'), (3, 'd'), (2, 'w'), (4, 'y')]
A:
You could just enumerate the list before sampling:
>>> random.sample(list(enumerate(l)), 5)
[(1, 'o'), (2, 'w'), (0, 'h'), (3, 'd'), (4, 'y')]
A:
It's probably easier to do something like this:
def sample_with_indices(s):
indices = range(len(s))
random.shuffle(indices)
return [(s[i], i) for i in indices]
This will basically shuffle all the indices for a string and then just return the character at that index. Going from character to index is a little more difficult.
|
Python: Picking an element without replacement
|
I would like to slice random letters from a string.
Given
s="howdy"
I would like to pick elements from 's' without replacement but keep the index number.
For example
>>> random.sample(s,len(s))
['w', 'h', 'o', 'd', 'y']
is close to what I want, but I would actually prefer something like
[('w',2), ('h',0), ('o',1), ('d',3), ('y',4)]
with letter-index pairs. This is important because the same letter appears in 's' more than once. ie) "letter" where 't' appears twice but I need to distinguish the first 't' from the second.
Ideally I actually only need to generate/pick letters as I need them but scrambling and calculating all the letters at once (ie: in a list as shown above) is ok.
|
[
">>> random.sample(list(enumerate(a)), 5)\n[(1, 'o'), (0, 'h'), (3, 'd'), (2, 'w'), (4, 'y')]\n\n",
"You could just enumerate the list before sampling:\n>>> random.sample(list(enumerate(l)), 5)\n[(1, 'o'), (2, 'w'), (0, 'h'), (3, 'd'), (4, 'y')]\n\n",
"It's probably easier to do something like this:\ndef sample_with_indices(s):\n indices = range(len(s))\n random.shuffle(indices)\n return [(s[i], i) for i in indices]\n\nThis will basically shuffle all the indices for a string and then just return the character at that index. Going from character to index is a little more difficult.\n"
] |
[
19,
9,
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002587387_python.txt
|
Q:
How to write outline data into .otf files?
I need to edit or completely replace outline data (bezier curves) of OpenType fonts. the input data is an EPS file that i have to write it into one specified glyph of an otf file with a certain scaling. (The glyph is specified by PostScript name OR Unicode value.)
I need something like an encoder (or just a library of file structure of OpenType)?
where to find about structure of otf and ttf files?
Note: python-realated tools and libraries are performed :-?
A:
Try the FontForge python extensions.
|
How to write outline data into .otf files?
|
I need to edit or completely replace outline data (bezier curves) of OpenType fonts. the input data is an EPS file that i have to write it into one specified glyph of an otf file with a certain scaling. (The glyph is specified by PostScript name OR Unicode value.)
I need something like an encoder (or just a library of file structure of OpenType)?
where to find about structure of otf and ttf files?
Note: python-realated tools and libraries are performed :-?
|
[
"Try the FontForge python extensions.\n"
] |
[
2
] |
[] |
[] |
[
"bezier",
"opentype",
"postscript",
"python"
] |
stackoverflow_0002587530_bezier_opentype_postscript_python.txt
|
Q:
Emulating a web browser
we are tasked with basically emulating a browser to fetch webpages, looking to automate tests on different web pages. This will be used for (ideally) console-ish applications that run in the background and generate reports.
We tried going with .NET and the WatiN library, but it was built on a Marshalled IE, and so it lacked many features that we hacked in with calls to unmanaged native code, but at the end of the day IE is not thread safe nor process safe, and many of the needed features could only be implemented by changing registry values and it was just terribly unflexible.
Proxy support
JavaScript support- we have to be able to parse the actual DOM after any javascript has executed (and hopefully an event is raised to handle any ajax calls)
Ability to save entire contents of page including images FROM THE loaded page's CACHE to a separate location
ability to clear cookies/cache, get the cookies/cache, etc.
Ability to set headers and alter post data for any browser call
Process and/or thread safe would be ideal
And for the love of drogs, an API that isn't completely cryptic
Languages acceptable C++, C#, Python, anything that can be a simple little background application that is somewhat bearable and doesn't have a completely "untraditional" syntax like Ruby.
From my own research, and believe me I am terrible at google searches, I have heard good things about WebKit... would the Qt module QtWebKit handle all these features?
A:
You might try one of these:
http://code.google.com/p/spynner/
http://code.google.com/p/pywebkitgtk/
A:
I know you mentioned you don't like Ruby syntax (neither do I), but I just have to chime in and say that Watir is probably the best thing out there for what you are trying to do.
EDIT: There appears to be a Java counter-part called Watij
A:
I've only been digging into this recently myself, so I couldn't say that this does everything you've listed, but check out GeckoFx.
From the site: GeckoFX is an open-source component which makes it easy to embed Mozilla Gecko (Firefox) into any .NET Windows Forms application. Written in clean, fully commented C#, GeckoFX is the perfect replacement for the default Internet Explorer-based WebBrowser control.
As for my own impressions: it has blown away the default .NET WebBrowser in both performance and stability.
|
Emulating a web browser
|
we are tasked with basically emulating a browser to fetch webpages, looking to automate tests on different web pages. This will be used for (ideally) console-ish applications that run in the background and generate reports.
We tried going with .NET and the WatiN library, but it was built on a Marshalled IE, and so it lacked many features that we hacked in with calls to unmanaged native code, but at the end of the day IE is not thread safe nor process safe, and many of the needed features could only be implemented by changing registry values and it was just terribly unflexible.
Proxy support
JavaScript support- we have to be able to parse the actual DOM after any javascript has executed (and hopefully an event is raised to handle any ajax calls)
Ability to save entire contents of page including images FROM THE loaded page's CACHE to a separate location
ability to clear cookies/cache, get the cookies/cache, etc.
Ability to set headers and alter post data for any browser call
Process and/or thread safe would be ideal
And for the love of drogs, an API that isn't completely cryptic
Languages acceptable C++, C#, Python, anything that can be a simple little background application that is somewhat bearable and doesn't have a completely "untraditional" syntax like Ruby.
From my own research, and believe me I am terrible at google searches, I have heard good things about WebKit... would the Qt module QtWebKit handle all these features?
|
[
"You might try one of these:\nhttp://code.google.com/p/spynner/\nhttp://code.google.com/p/pywebkitgtk/\n",
"I know you mentioned you don't like Ruby syntax (neither do I), but I just have to chime in and say that Watir is probably the best thing out there for what you are trying to do.\nEDIT: There appears to be a Java counter-part called Watij\n",
"I've only been digging into this recently myself, so I couldn't say that this does everything you've listed, but check out GeckoFx.\nFrom the site: GeckoFX is an open-source component which makes it easy to embed Mozilla Gecko (Firefox) into any .NET Windows Forms application. Written in clean, fully commented C#, GeckoFX is the perfect replacement for the default Internet Explorer-based WebBrowser control.\nAs for my own impressions: it has blown away the default .NET WebBrowser in both performance and stability.\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
".net",
"c#",
"c++",
"python",
"qt"
] |
stackoverflow_0002587423_.net_c#_c++_python_qt.txt
|
Q:
Python Ephem / Datetime calculation
the output should process the first date as "day" and second as "night". I've been playing with this for a few hours now and can't figure out what I'm doing wrong. Any ideas?
Edit
I assume that the problem is due to my date comparison implementation
Output:
$ python time_of_day.py
* should be day:
event date: 2010/4/6 16:00:59
prev rising: 2010/4/6 09:24:24
prev setting: 2010/4/5 23:33:03
next rise: 2010/4/7 09:22:27
next set: 2010/4/6 23:34:27
day
* should be night:
event date: 2010/4/6 00:01:00
prev rising: 2010/4/5 09:26:22
prev setting: 2010/4/5 23:33:03
next rise: 2010/4/6 09:24:24
next set: 2010/4/6 23:34:27
day
time_of_day.py
import datetime
import ephem # install from http://pypi.python.org/pypi/pyephem/
#event_time is just a date time corresponding to an sql timestamp
def type_of_light(latitude, longitude, event_time, utc_time, horizon):
o = ephem.Observer()
o.lat, o.long, o.date, o.horizon = latitude, longitude, event_time, horizon
print "event date ", o.date
print "prev rising: ", o.previous_rising(ephem.Sun())
print "prev setting: ", o.previous_setting(ephem.Sun())
print "next rise: ", o.next_rising(ephem.Sun())
print "next set: ", o.next_setting(ephem.Sun())
if o.previous_rising(ephem.Sun()) <= o.date <= o.next_setting(ephem.Sun()):
return "day"
elif o.previous_setting(ephem.Sun()) <= o.date <= o.next_rising(ephem.Sun()):
return "night"
else:
return "error"
print "should be day: ", type_of_light('45.959','-66.6405','2010/4/6 16:01','-4', '-6')
print "should be night: ", type_of_light('45.959','-66.6405','2010/4/6 00:01','-4', '-6')
A:
o.date will always be between o.previous_settings and o.next_rising ;), so you can check it this way:
if o.previous_rising(ephem.Sun()) > o.previous_setting(ephem.Sun()):
return "day"
elif:
return "night"
|
Python Ephem / Datetime calculation
|
the output should process the first date as "day" and second as "night". I've been playing with this for a few hours now and can't figure out what I'm doing wrong. Any ideas?
Edit
I assume that the problem is due to my date comparison implementation
Output:
$ python time_of_day.py
* should be day:
event date: 2010/4/6 16:00:59
prev rising: 2010/4/6 09:24:24
prev setting: 2010/4/5 23:33:03
next rise: 2010/4/7 09:22:27
next set: 2010/4/6 23:34:27
day
* should be night:
event date: 2010/4/6 00:01:00
prev rising: 2010/4/5 09:26:22
prev setting: 2010/4/5 23:33:03
next rise: 2010/4/6 09:24:24
next set: 2010/4/6 23:34:27
day
time_of_day.py
import datetime
import ephem # install from http://pypi.python.org/pypi/pyephem/
#event_time is just a date time corresponding to an sql timestamp
def type_of_light(latitude, longitude, event_time, utc_time, horizon):
o = ephem.Observer()
o.lat, o.long, o.date, o.horizon = latitude, longitude, event_time, horizon
print "event date ", o.date
print "prev rising: ", o.previous_rising(ephem.Sun())
print "prev setting: ", o.previous_setting(ephem.Sun())
print "next rise: ", o.next_rising(ephem.Sun())
print "next set: ", o.next_setting(ephem.Sun())
if o.previous_rising(ephem.Sun()) <= o.date <= o.next_setting(ephem.Sun()):
return "day"
elif o.previous_setting(ephem.Sun()) <= o.date <= o.next_rising(ephem.Sun()):
return "night"
else:
return "error"
print "should be day: ", type_of_light('45.959','-66.6405','2010/4/6 16:01','-4', '-6')
print "should be night: ", type_of_light('45.959','-66.6405','2010/4/6 00:01','-4', '-6')
|
[
"o.date will always be between o.previous_settings and o.next_rising ;), so you can check it this way:\nif o.previous_rising(ephem.Sun()) > o.previous_setting(ephem.Sun()):\n return \"day\"\nelif:\n return \"night\"\n\n"
] |
[
7
] |
[] |
[] |
[
"astronomy",
"datetime",
"pyephem",
"python"
] |
stackoverflow_0002587640_astronomy_datetime_pyephem_python.txt
|
Q:
How to validate a bunch of proxies against a URL?
I have a list of 100 proxies. The URL I am interested in is abc.com. I want to check the number of proxies which can successfully fetch this URL and the time taken for the same. I am hoping I made sense. I am a Python noob. I am looking for a code snippet. A helping hand is really appreciated :)
Proxies :
200.43.54.212
200.43.54.212
200.43.54.212
200.43.54.212
URL :
abc.com
Desired result :
Proxy isGood Time
200.43.54.112 n 23.12
200.43.54.222 n 12.34
200.43.54.102 y 11.09
200.43.54.111 y 8.85
p.s : All the above proxies have ports either 80 or 8080
A:
You can fetch URLs using urllib2. To get the amount of time taken, you can use the time module. Here's a simple example that does what you seem to want:
import urllib2
import time
def testProxies(url, proxies):
# prepare the request
req = urllib2.Request(url)
# run the request for each proxy
results = ["Proxy isGood Time"]
for proxy in (proxies):
# now set the proxy
req.set_proxy(proxy, "http")
# time it
start = time.time()
# try to open the URL
try:
urllib2.urlopen(req)
# format the results for success
results.append("%s y %.2f" % (proxy, time.time()-start))
except urllib2.URLError:
# format the results for failure
results.append("%s n %.2f" % (proxy, time.time()-start))
return results
testResults = testProxies("http://www.abc.com", ["200.43.54.112", "200.43.54.222",
"200.43.54.102", "200.43.54.111"])
for result in testResults:
print result
The main points are creating the request with urllib2.Request(url) and using the set_proxy() function, which lets you set a proxy for the request.
|
How to validate a bunch of proxies against a URL?
|
I have a list of 100 proxies. The URL I am interested in is abc.com. I want to check the number of proxies which can successfully fetch this URL and the time taken for the same. I am hoping I made sense. I am a Python noob. I am looking for a code snippet. A helping hand is really appreciated :)
Proxies :
200.43.54.212
200.43.54.212
200.43.54.212
200.43.54.212
URL :
abc.com
Desired result :
Proxy isGood Time
200.43.54.112 n 23.12
200.43.54.222 n 12.34
200.43.54.102 y 11.09
200.43.54.111 y 8.85
p.s : All the above proxies have ports either 80 or 8080
|
[
"You can fetch URLs using urllib2. To get the amount of time taken, you can use the time module. Here's a simple example that does what you seem to want:\nimport urllib2\nimport time\n\n\ndef testProxies(url, proxies):\n # prepare the request\n req = urllib2.Request(url)\n # run the request for each proxy\n results = [\"Proxy isGood Time\"]\n for proxy in (proxies):\n # now set the proxy\n req.set_proxy(proxy, \"http\")\n # time it\n start = time.time()\n # try to open the URL\n try:\n urllib2.urlopen(req)\n # format the results for success\n results.append(\"%s y %.2f\" % (proxy, time.time()-start))\n except urllib2.URLError:\n # format the results for failure\n results.append(\"%s n %.2f\" % (proxy, time.time()-start))\n\n return results\n\ntestResults = testProxies(\"http://www.abc.com\", [\"200.43.54.112\", \"200.43.54.222\",\n \"200.43.54.102\", \"200.43.54.111\"])\nfor result in testResults:\n print result\n\nThe main points are creating the request with urllib2.Request(url) and using the set_proxy() function, which lets you set a proxy for the request.\n"
] |
[
4
] |
[] |
[] |
[
"curl",
"proxy",
"python"
] |
stackoverflow_0002588093_curl_proxy_python.txt
|
Q:
Is it possible to detect the browser version from Django server side?
in server side, not browser.
A:
You can use the HTTP_USER_AGENT in HttpRequest
A:
request.env['HTTP_USER_AGENT'] will give the user agent string the browser sent.
A:
Unfortunately request.env won't work.
However, you can get it through request.META.get("HTTP_USER_AGENT")
|
Is it possible to detect the browser version from Django server side?
|
in server side, not browser.
|
[
"You can use the HTTP_USER_AGENT in HttpRequest\n",
"request.env['HTTP_USER_AGENT'] will give the user agent string the browser sent.\n",
"Unfortunately request.env won't work. \nHowever, you can get it through request.META.get(\"HTTP_USER_AGENT\")\n"
] |
[
4,
2,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002522774_django_python.txt
|
Q:
A Combinations of Items in Given List
I'm currently in Python land. This is what I need to do. I have already looked into the itertools library but it seems to only do permutations.
I want to take an input list, like ['yahoo', 'wikipedia', 'freebase'] and generate every unique combination of one item with zero or more other items...
['yahoo', 'wikipedia', 'freebase']
['yahoo', 'wikipedia']
['yahoo', 'freebase']
['wikipedia', 'freebase']
['yahoo']
['freebase']
['wikipedia']
A few notes. Order does not matter and I am trying to design the method to take a list of any size. Also, is there a name for this kind of combination?
Thanks for your help!
A:
>>> l = ['yahoo', 'wikipedia', 'freebase']
>>> import itertools
>>> for i in range(1, len(l) +1):
print(list(itertools.combinations(l, r=i)))
[('yahoo',), ('wikipedia',), ('freebase',)]
[('yahoo', 'wikipedia'), ('yahoo', 'freebase'), ('wikipedia', 'freebase')]
[('yahoo', 'wikipedia', 'freebase')]
P.S. why is this wiki?
A:
It's called a powerset. This is an implementation from the itertools docs:
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
A:
That is called a power set. Just follow this algorithm. Here's a simple implementation:
def powerset(seq):
if len(seq):
head = powerset(seq[:-1])
return head + [item + [seq[-1]] for item in head]
else:
return [[]]
>>> powerset(['yahoo', 'wikipedia', 'freebase'])
[[], ['yahoo'], ['wikipedia'], ['yahoo', 'wikipedia'], ['freebase'], ['yahoo', 'freebase'], ['wikipedia', 'freebase'], ['yahoo', 'wikipedia', 'freebase']]
And another:
def powerset(s):
sets = []
indicator = lambda x: x & 1
for element in xrange(2**len(s)):
n = element
subset = []
for x in s:
if indicator(n):
subset.append(x)
n >>= 1
sets.append(subset)
return sets
A:
You're basically counting from 1 to 2n-1 in binary:
0 0 1 ['freebase']
0 1 0 ['wikipedia']
0 1 1 ['wikipedia', 'freebase']
1 0 0 ['yahoo']
1 0 1 ['yahoo', 'freebase']
1 1 0 ['yahoo', 'wikipedia']
1 1 1 ['yahoo', 'wikipedia', 'freebase']
|
A Combinations of Items in Given List
|
I'm currently in Python land. This is what I need to do. I have already looked into the itertools library but it seems to only do permutations.
I want to take an input list, like ['yahoo', 'wikipedia', 'freebase'] and generate every unique combination of one item with zero or more other items...
['yahoo', 'wikipedia', 'freebase']
['yahoo', 'wikipedia']
['yahoo', 'freebase']
['wikipedia', 'freebase']
['yahoo']
['freebase']
['wikipedia']
A few notes. Order does not matter and I am trying to design the method to take a list of any size. Also, is there a name for this kind of combination?
Thanks for your help!
|
[
">>> l = ['yahoo', 'wikipedia', 'freebase']\n>>> import itertools\n>>> for i in range(1, len(l) +1):\n print(list(itertools.combinations(l, r=i)))\n\n\n[('yahoo',), ('wikipedia',), ('freebase',)]\n[('yahoo', 'wikipedia'), ('yahoo', 'freebase'), ('wikipedia', 'freebase')]\n[('yahoo', 'wikipedia', 'freebase')]\n\nP.S. why is this wiki?\n",
"It's called a powerset. This is an implementation from the itertools docs:\ndef powerset(iterable):\n \"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n s = list(iterable)\n return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))\n\n",
"That is called a power set. Just follow this algorithm. Here's a simple implementation:\ndef powerset(seq):\n if len(seq):\n head = powerset(seq[:-1])\n return head + [item + [seq[-1]] for item in head]\n else:\n return [[]]\n\n>>> powerset(['yahoo', 'wikipedia', 'freebase'])\n[[], ['yahoo'], ['wikipedia'], ['yahoo', 'wikipedia'], ['freebase'], ['yahoo', 'freebase'], ['wikipedia', 'freebase'], ['yahoo', 'wikipedia', 'freebase']]\n\nAnd another:\ndef powerset(s):\n sets = []\n indicator = lambda x: x & 1\n for element in xrange(2**len(s)):\n n = element\n subset = []\n for x in s:\n if indicator(n):\n subset.append(x)\n n >>= 1\n sets.append(subset)\n return sets\n\n",
"You're basically counting from 1 to 2n-1 in binary:\n0 0 1 ['freebase']\n0 1 0 ['wikipedia']\n0 1 1 ['wikipedia', 'freebase']\n1 0 0 ['yahoo']\n1 0 1 ['yahoo', 'freebase']\n1 1 0 ['yahoo', 'wikipedia']\n1 1 1 ['yahoo', 'wikipedia', 'freebase']\n\n"
] |
[
3,
3,
0,
0
] |
[] |
[] |
[
"combinations",
"permutation",
"python"
] |
stackoverflow_0002588247_combinations_permutation_python.txt
|
Q:
easiest way to setup XEmacs on Gentoo for Python
I want to use (X)Emacs on my Gentoo system and wonder about the "correct" (or easiest) way to setup it to be used for Python development (i.e. intelligent auto-completion via tab and all those usual stuff).
I want to avoid installing anything by hand - I want to use my Portage/emerge as far as possible.
I have installed xemacs, python-mode and python-modes so far. Seems that I had to manually enable syntax highlighting and the syntax highlighting support seems kind of limited. And auto completion via tab doesn't work at all (I guess it's also not enabled or python-mode(s) doesn't have that?).
Thanks for your help!
A:
I used this tutorial myself at EnigmaCurry.
You can use easy_install to install rope and ropemacs. And then I believe you only need to copy the autocomplete.el script on that site.
good luck.
|
easiest way to setup XEmacs on Gentoo for Python
|
I want to use (X)Emacs on my Gentoo system and wonder about the "correct" (or easiest) way to setup it to be used for Python development (i.e. intelligent auto-completion via tab and all those usual stuff).
I want to avoid installing anything by hand - I want to use my Portage/emerge as far as possible.
I have installed xemacs, python-mode and python-modes so far. Seems that I had to manually enable syntax highlighting and the syntax highlighting support seems kind of limited. And auto completion via tab doesn't work at all (I guess it's also not enabled or python-mode(s) doesn't have that?).
Thanks for your help!
|
[
"I used this tutorial myself at EnigmaCurry.\nYou can use easy_install to install rope and ropemacs. And then I believe you only need to copy the autocomplete.el script on that site.\ngood luck.\n"
] |
[
0
] |
[] |
[] |
[
"emacs",
"python",
"xemacs"
] |
stackoverflow_0002566834_emacs_python_xemacs.txt
|
Q:
What is the purpose of subclassing the class "object" in Python?
All the Python built-ins are subclasses of object and I come across many user-defined classes which are too. Why? What is the purpose of the class object? It's just an empty class, right?
A:
In short, it sets free magical ponies.
In long, Python 2.2 and earlier used "old style classes". They were a particular implementation of classes, and they had a few limitations (for example, you couldn't subclass builtin types). The fix for this was to create a new style of class. But, doing this would involve some backwards-incompatible changes. So, to make sure that code which is written for old style classes will still work, the object class was created to act as a superclass for all new-style classes.
So, in Python 2.X, class Foo: pass will create an old-style class and class Foo(object): pass will create a new style class.
In longer, see Guido's Unifying types and classes in Python 2.2.
And, in general, it's a good idea to get into the habit of making all your classes new-style, because some things (the @property decorator is one that comes to mind) won't work with old-style classes.
A:
Short answer: subclassing object effectively makes it a new-style class (note that this is unnecessary since automatic in Python 3.x)
For the difference between new style classes and old style classes: see this stackoverflow question. For the complete story: see this nice writeup on Python Types and Objects.
A:
It has to do with the "new-style" of classes. You can read more about it here: http://docs.python.org/tutorial/classes.html#multiple-inheritance and also here: http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes
Using new-style classes will allow you to use "Python's newer, versatile features like __slots__, descriptors, properties, and __getattribute__()."
A:
Right, but it marks the class as a new-style class. Newly developed classes should use the object base because it costs little and future-proofs your code.
A:
The short version is that classic classes, which didn't need a superclass, had limitations that couldn't be worked around without breaking a lot of old code. So they created the concept of new-style classes which subclass from object, and now you can do cool things like define properties, and subclassing dict is no longer an exercise in pain and strange bugs.
The details are in section 3.3 of the Python docs: New-style and classic classes.
A:
Python 2.2 introduced "new style classes" which had a number of additional features relative to the old style classes which did not subclass object. Subclasses object was the chosen way to indicate that your class should be a new style class, not an old style one.
|
What is the purpose of subclassing the class "object" in Python?
|
All the Python built-ins are subclasses of object and I come across many user-defined classes which are too. Why? What is the purpose of the class object? It's just an empty class, right?
|
[
"In short, it sets free magical ponies.\nIn long, Python 2.2 and earlier used \"old style classes\". They were a particular implementation of classes, and they had a few limitations (for example, you couldn't subclass builtin types). The fix for this was to create a new style of class. But, doing this would involve some backwards-incompatible changes. So, to make sure that code which is written for old style classes will still work, the object class was created to act as a superclass for all new-style classes.\nSo, in Python 2.X, class Foo: pass will create an old-style class and class Foo(object): pass will create a new style class.\nIn longer, see Guido's Unifying types and classes in Python 2.2.\nAnd, in general, it's a good idea to get into the habit of making all your classes new-style, because some things (the @property decorator is one that comes to mind) won't work with old-style classes.\n",
"Short answer: subclassing object effectively makes it a new-style class (note that this is unnecessary since automatic in Python 3.x)\nFor the difference between new style classes and old style classes: see this stackoverflow question. For the complete story: see this nice writeup on Python Types and Objects.\n",
"It has to do with the \"new-style\" of classes. You can read more about it here: http://docs.python.org/tutorial/classes.html#multiple-inheritance and also here: http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes\nUsing new-style classes will allow you to use \"Python's newer, versatile features like __slots__, descriptors, properties, and __getattribute__().\"\n",
"Right, but it marks the class as a new-style class. Newly developed classes should use the object base because it costs little and future-proofs your code.\n",
"The short version is that classic classes, which didn't need a superclass, had limitations that couldn't be worked around without breaking a lot of old code. So they created the concept of new-style classes which subclass from object, and now you can do cool things like define properties, and subclassing dict is no longer an exercise in pain and strange bugs.\nThe details are in section 3.3 of the Python docs: New-style and classic classes.\n",
"Python 2.2 introduced \"new style classes\" which had a number of additional features relative to the old style classes which did not subclass object. Subclasses object was the chosen way to indicate that your class should be a new style class, not an old style one.\n"
] |
[
61,
13,
4,
3,
1,
0
] |
[] |
[] |
[
"deprecated",
"future_proof",
"new_style_class",
"object",
"python"
] |
stackoverflow_0002588628_deprecated_future_proof_new_style_class_object_python.txt
|
Q:
Deploying a PyQt application on Windows Vista x64
I'm working on an application for a client/friend using PyQt. I've been working on Linux and testing on Vista, but the target computer is Vista x64. Now, Python comes with compiled binaries of Python 2.6 for 64 bit Windows, but Riverbank don't provide 64 bit binaries for PyQt.
I don't have much access to the target computer, so I can't really go through the hassle of compiling PyQt. This Google code project might be the solution, but I'm not sure if it's going to work.
Can I use something like py2exe from 32 bit Vista, or would I have to have to make the executable from a 64 bit machine with PyQt 64 bit installed? Basically, am I going to have to compile PyQt on the target machine?
A:
You should be able to compile to the 32-bit (x86) and include 32-bit PyQt binaries and all will be well. 64-bit Windoze will run the project in a WOW64 process, and there shouldn't be compatibility issues.
A:
From the same link you posted, the guy made a binary for Python 2.6
http://www.ozgurfx.com/downloads/PyQt-Py2.6-gpl-4.5.4-1_amd64.exe
Here's my source:
http://www.mail-archive.com/python_inside_maya@googlegroups.com/msg01977.html
Note: do not forget the Microsoft Visual C++ 2005 SP1 Redistributable Package (x64), but I guess most computer already have it installed ... just a reminder.
|
Deploying a PyQt application on Windows Vista x64
|
I'm working on an application for a client/friend using PyQt. I've been working on Linux and testing on Vista, but the target computer is Vista x64. Now, Python comes with compiled binaries of Python 2.6 for 64 bit Windows, but Riverbank don't provide 64 bit binaries for PyQt.
I don't have much access to the target computer, so I can't really go through the hassle of compiling PyQt. This Google code project might be the solution, but I'm not sure if it's going to work.
Can I use something like py2exe from 32 bit Vista, or would I have to have to make the executable from a 64 bit machine with PyQt 64 bit installed? Basically, am I going to have to compile PyQt on the target machine?
|
[
"You should be able to compile to the 32-bit (x86) and include 32-bit PyQt binaries and all will be well. 64-bit Windoze will run the project in a WOW64 process, and there shouldn't be compatibility issues.\n",
"From the same link you posted, the guy made a binary for Python 2.6 \nhttp://www.ozgurfx.com/downloads/PyQt-Py2.6-gpl-4.5.4-1_amd64.exe\nHere's my source:\nhttp://www.mail-archive.com/python_inside_maya@googlegroups.com/msg01977.html\nNote: do not forget the Microsoft Visual C++ 2005 SP1 Redistributable Package (x64), but I guess most computer already have it installed ... just a reminder.\n"
] |
[
1,
1
] |
[] |
[] |
[
"64_bit",
"pyqt",
"python"
] |
stackoverflow_0002588424_64_bit_pyqt_python.txt
|
Q:
Python TEA implementation
Anybody knows proper python implementation of TEA (Tiny Encryption Algorithm)? I tried the one I've found here: http://sysadminco.com/code/python-tea/ - but it does not seem to work properly.
It returns different results than other implementations in C or Java. I guess it's caused by completely different data types in python (or no data types in fact).
Here's the code and an example:
def encipher(v, k):
y=v[0];z=v[1];sum=0;delta=0x9E3779B9;n=32
w=[0,0]
while(n>0):
y += (z << 4 ^ z >> 5) + z ^ sum + k[sum & 3]
y &= 4294967295L # maxsize of 32-bit integer
sum += delta
z += (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3]
z &= 4294967295L
n -= 1
w[0]=y; w[1]=z
return w
def decipher(v, k):
y=v[0]
z=v[1]
sum=0xC6EF3720
delta=0x9E3779B9
n=32
w=[0,0]
# sum = delta<<5, in general sum = delta * n
while(n>0):
z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3]
z &= 4294967295L
sum -= delta
y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3]
y &= 4294967295L
n -= 1
w[0]=y; w[1]=z
return w
Python example:
>>> import tea
>>> key = [0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805]
>>> v = [0xe15034c8, 0x260fd6d5]
>>> res = tea.encipher(v, key)
>>> "%X %X" % (res[0], res[1])
**'70D16811 F935148F'**
C example:
#include <unistd.h>
#include <stdio.h>
void encipher(unsigned long *const v,unsigned long *const w,
const unsigned long *const k)
{
register unsigned long y=v[0],z=v[1],sum=0,delta=0x9E3779B9,
a=k[0],b=k[1],c=k[2],d=k[3],n=32;
while(n-->0)
{
sum += delta;
y += (z << 4)+a ^ z+sum ^ (z >> 5)+b;
z += (y << 4)+c ^ y+sum ^ (y >> 5)+d;
}
w[0]=y; w[1]=z;
}
int main()
{
unsigned long v[] = {0xe15034c8, 0x260fd6d5};
unsigned long key[] = {0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805};
unsigned long res[2];
encipher(v, res, key);
printf("%X %X\n", res[0], res[1]);
return 0;
}
$ ./tea
**D6942D68 6F87870D**
Please note, that both examples were run with the same input data (v and key), but results were different. I'm pretty sure C implementation is correct - it comes from a site referenced by wikipedia (I couldn't post a link to it because I don't have enough reputation points yet - some antispam thing)
A:
I fixed it. Here is working TEA implementation in python:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
from ctypes import *
def encipher(v, k):
y = c_uint32(v[0])
z = c_uint32(v[1])
sum = c_uint32(0)
delta = 0x9e3779b9
n = 32
w = [0,0]
while(n>0):
sum.value += delta
y.value += ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1]
z.value += ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3]
n -= 1
w[0] = y.value
w[1] = z.value
return w
def decipher(v, k):
y = c_uint32(v[0])
z = c_uint32(v[1])
sum = c_uint32(0xc6ef3720)
delta = 0x9e3779b9
n = 32
w = [0,0]
while(n>0):
z.value -= ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3]
y.value -= ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1]
sum.value -= delta
n -= 1
w[0] = y.value
w[1] = z.value
return w
if __name__ == "__main__":
key = [1,2,3,4]
v = [1385482522,639876499]
enc = encipher(v,key)
print enc
print decipher(enc,key)
And a small sample:
>>> v
[1385482522, 639876499]
>>> tea.decipher(tea.encipher(v,key),key)
[1385482522L, 639876499L]
A:
Since TEA is a block cipher and your v is a very small block, I'd guess there may be block padding differences, or as Wikipedia notes:
http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm:
Note that the reference implementation
is bound to a specific microprocessor
architecture meaning that byte order
considerations are important when
cyphertext is shared and processed on
different systems. The original paper
does not specify any details about
microprocessor architecture and so
anyone implementing a system using TEA
would need to make those
specifications for themselves.
I didn't inspect either implementation in detail. Your &= statements feel suspicious, too.
A:
Tea is broken, do not use it.
XXTEA which is secure does not define endianess and stuff and you should should reinvent whell when you can use AES.
There is no point in using unsecure cryptography.
I strongy advice you to apply AES, it can be implemented in 8bit microcontolers whit just few kB of code
EDIT
Did you checked this code?
http://sysadminco.com/code/python-tea/
|
Python TEA implementation
|
Anybody knows proper python implementation of TEA (Tiny Encryption Algorithm)? I tried the one I've found here: http://sysadminco.com/code/python-tea/ - but it does not seem to work properly.
It returns different results than other implementations in C or Java. I guess it's caused by completely different data types in python (or no data types in fact).
Here's the code and an example:
def encipher(v, k):
y=v[0];z=v[1];sum=0;delta=0x9E3779B9;n=32
w=[0,0]
while(n>0):
y += (z << 4 ^ z >> 5) + z ^ sum + k[sum & 3]
y &= 4294967295L # maxsize of 32-bit integer
sum += delta
z += (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3]
z &= 4294967295L
n -= 1
w[0]=y; w[1]=z
return w
def decipher(v, k):
y=v[0]
z=v[1]
sum=0xC6EF3720
delta=0x9E3779B9
n=32
w=[0,0]
# sum = delta<<5, in general sum = delta * n
while(n>0):
z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3]
z &= 4294967295L
sum -= delta
y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3]
y &= 4294967295L
n -= 1
w[0]=y; w[1]=z
return w
Python example:
>>> import tea
>>> key = [0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805]
>>> v = [0xe15034c8, 0x260fd6d5]
>>> res = tea.encipher(v, key)
>>> "%X %X" % (res[0], res[1])
**'70D16811 F935148F'**
C example:
#include <unistd.h>
#include <stdio.h>
void encipher(unsigned long *const v,unsigned long *const w,
const unsigned long *const k)
{
register unsigned long y=v[0],z=v[1],sum=0,delta=0x9E3779B9,
a=k[0],b=k[1],c=k[2],d=k[3],n=32;
while(n-->0)
{
sum += delta;
y += (z << 4)+a ^ z+sum ^ (z >> 5)+b;
z += (y << 4)+c ^ y+sum ^ (y >> 5)+d;
}
w[0]=y; w[1]=z;
}
int main()
{
unsigned long v[] = {0xe15034c8, 0x260fd6d5};
unsigned long key[] = {0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805};
unsigned long res[2];
encipher(v, res, key);
printf("%X %X\n", res[0], res[1]);
return 0;
}
$ ./tea
**D6942D68 6F87870D**
Please note, that both examples were run with the same input data (v and key), but results were different. I'm pretty sure C implementation is correct - it comes from a site referenced by wikipedia (I couldn't post a link to it because I don't have enough reputation points yet - some antispam thing)
|
[
"I fixed it. Here is working TEA implementation in python:\n#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport sys\nfrom ctypes import *\n\ndef encipher(v, k):\n y = c_uint32(v[0])\n z = c_uint32(v[1])\n sum = c_uint32(0)\n delta = 0x9e3779b9\n n = 32\n w = [0,0]\n\n while(n>0):\n sum.value += delta\n y.value += ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1]\n z.value += ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3]\n n -= 1\n\n w[0] = y.value\n w[1] = z.value\n return w\n\ndef decipher(v, k):\n y = c_uint32(v[0])\n z = c_uint32(v[1])\n sum = c_uint32(0xc6ef3720)\n delta = 0x9e3779b9\n n = 32\n w = [0,0]\n\n while(n>0):\n z.value -= ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3]\n y.value -= ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1]\n sum.value -= delta\n n -= 1\n\n w[0] = y.value\n w[1] = z.value\n return w\n\nif __name__ == \"__main__\":\n key = [1,2,3,4]\n v = [1385482522,639876499]\n enc = encipher(v,key)\n print enc\n print decipher(enc,key)\n\nAnd a small sample:\n>>> v\n[1385482522, 639876499]\n>>> tea.decipher(tea.encipher(v,key),key)\n[1385482522L, 639876499L]\n\n",
"Since TEA is a block cipher and your v is a very small block, I'd guess there may be block padding differences, or as Wikipedia notes:\nhttp://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm:\n\nNote that the reference implementation\n is bound to a specific microprocessor\n architecture meaning that byte order\n considerations are important when\n cyphertext is shared and processed on\n different systems. The original paper\n does not specify any details about\n microprocessor architecture and so\n anyone implementing a system using TEA\n would need to make those\n specifications for themselves.\n\nI didn't inspect either implementation in detail. Your &= statements feel suspicious, too.\n",
"Tea is broken, do not use it. \nXXTEA which is secure does not define endianess and stuff and you should should reinvent whell when you can use AES. \nThere is no point in using unsecure cryptography.\nI strongy advice you to apply AES, it can be implemented in 8bit microcontolers whit just few kB of code \nEDIT\nDid you checked this code?\nhttp://sysadminco.com/code/python-tea/\n"
] |
[
11,
1,
0
] |
[] |
[] |
[
"c",
"encryption",
"python"
] |
stackoverflow_0002588364_c_encryption_python.txt
|
Q:
What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
I'm writing a scientific application in Python with a very processor-intensive loop at its core. I would like to optimise this as far as possible, at minimum inconvenience to end users, who will probably use it as an uncompiled collection of Python scripts, and will be using Windows, Mac, and (mainly Ubuntu) Linux.
It is currently written in Python with a dash of NumPy, and I've included the code below.
Is there a solution which would be reasonably fast which would not require compilation? This would seem to be the easiest way to maintain platform-independence.
If using something like Pyrex, which does require compilation, is there an easy way to bundle many modules and have Python choose between them depending on detected OS and Python version? Is there an easy way to build the collection of modules without needing access to every system with every version of Python?
Does one method lend itself particularly to multi-processor optimisation?
(If you're interested, the loop is to calculate the magnetic field at a given point inside a crystal by adding together the contributions of a large number of nearby magnetic ions, treated as tiny bar magnets. Basically, a massive sum of these.)
# calculate_dipole
# -------------------------
# calculate_dipole works out the dipole field at a given point within the crystal unit cell
# ---
# INPUT
# mu = position at which to calculate the dipole field
# r_i = array of atomic positions
# mom_i = corresponding array of magnetic moments
# ---
# OUTPUT
# B = the B-field at this point
def calculate_dipole(mu, r_i, mom_i):
relative = mu - r_i
r_unit = unit_vectors(relative)
#4pi / mu0 (at the front of the dipole eqn)
A = 1e-7
#initalise dipole field
B = zeros(3,float)
for i in range(len(relative)):
#work out the dipole field and add it to the estimate so far
B += A*(3*dot(mom_i[i],r_unit[i])*r_unit[i] - mom_i[i]) / sqrt(dot(relative[i],relative[i]))**3
return B
A:
You can get this to run much, much faster if you eliminate the loop and use Numpy's vectorized operations. Put your data in numpy arrays of shape (3,N) and try the following:
import numpy as np
N = 20000
mu = np.random.random((3,1))
r_i = np.random.random((3,N))
mom_i = np.random.random((3,N))
def unit_vectors(r):
return r / np.sqrt((r*r).sum(0))
def calculate_dipole(mu, r_i, mom_i):
relative = mu - r_i
r_unit = unit_vectors(relative)
A = 1e-7
num = A*(3*np.sum(mom_i*r_unit, 0)*r_unit - mom_i)
den = np.sqrt(np.sum(relative*relative, 0))**3
B = np.sum(num/den, 1)
return B
This runs about 50 times faster for me than using a for loop.
A:
Numpy does use some native optimization for array processing. You can use Numpy array with Cython to gain some speed-ups.
A:
Your python code could probably be speeded up a bit by replacing your loop with a generator expression and removing all the lookups of mom_i[i], relative[i] and r_unit[i] by iterating through all three sequences in parallel using itertools.izip.
i.e. replace
B = zeros(3,float)
for i in range(len(relative)):
#work out the dipole field and add it to the estimate so far
B += A*(3*dot(mom_i[i],r_unit[i])*r_unit[i] - mom_i[i]) / sqrt(dot(relative[i],relative[i]))**3
return B
with:
from itertools import izip
...
return sum((A*(3*dot(mom,ru)*ru - mom) / sqrt(dot(rel,rel))**3
for mom, ru, rel in izip(mom_i, r_unit, relative)),
zeros(3,float))
This is also more readable IMHO since the core equation is not cluttered with [i] everywhere..
I suspect however that this will only get you marginal gains compared to doing the whole function in a compiled language such as Cython.
A:
One simple, but significant speed-up is to take the multiplication by A outside of your sum. You can just times the B with it as you return it:
for i in range(len(relative)):
#work out the dipole field and add it to the estimate so far
B += (3*dot(mom_i[i],r_unit[i])*r_unit[i] - mom_i[i]) / sqrt(dot(relative[i],relative[i]))**3
return A*B
This gave about an 8% speed-up using 20,000 random dipoles.
Beyond that easy speed-up, I would recommend using Cython (which is generally recommended over using Pyrex) or Weave from Scipy. Take a look at the Performance Python for some examples and comparisons of various ways to speed-up Numpy/Scipy.
If you want to try making this parallel, I would recommend looking at Scipy's Parallel Programming to get started.
It's good to see another physicist on SO. There aren't very many on here.
Edit:
I decided to take this as a challenge to develop some Cython skills and got about a 10x time improvement over a Psyco optimized version. Let me know if you'd like to see my code.
Edit2:
Okay, went back and found what was slowing things up in my Cython version. Now the speed-up is well over 100x. If you want or need another factor of 2x or so over Ray's sped-up Numpy version, let me know and I will post my code.
Cython source code:
Here's the Cython code that I drummed up:
import numpy as np
cimport numpy as np
cimport cython
cdef extern from "math.h":
double sqrt(double theta)
ctypedef np.float64_t dtype_t
@cython.boundscheck(False)
@cython.wraparound(False)
def calculate_dipole_cython(np.ndarray[dtype_t,ndim=2,mode="c"] mu,
np.ndarray[dtype_t,ndim=2,mode="c"] r_i,
np.ndarray[dtype_t,ndim=2,mode="c"] mom_i):
cdef Py_ssize_t i
cdef np.ndarray[dtype_t,ndim=1,mode="c"] tmp = np.empty(3,np.float64)
cdef np.ndarray[dtype_t,ndim=1,mode="c"] relative = np.empty(3,np.float64)
cdef double A = 1e-7
cdef double C, D, F
cdef np.ndarray[dtype_t,ndim=1,mode="c"] B = np.zeros(3,np.float64)
for i in xrange(r_i.shape[0]):
relative[0] = mu[0,0] - r_i[i,0]
relative[1] = mu[0,1] - r_i[i,1]
relative[2] = mu[0,2] - r_i[i,2]
C = relative[0]*relative[0] + relative[1]*relative[1] + relative[2]*relative[2]
C = 1.0/sqrt(C)
D = C**3
tmp[0] = relative[0]*C
F = mom_i[i,0]*tmp[0]
tmp[1] = relative[1]*C
F += mom_i[i,1]*tmp[1]
tmp[2] = relative[2]*C
F += mom_i[i,2]*tmp[2]
F *= 3
B[0] += (F*tmp[0] - mom_i[i,0])*D
B[1] += (F*tmp[1] - mom_i[i,1])*D
B[2] += (F*tmp[2] - mom_i[i,2])*D
return A*B
I've optimized it quite a bit I think, but there might be a little more you can get out of it. You can still maybe replace the np.zeros and np.empty with direct calls from the Numpy C API, but that shouldn't make much of a difference. As it stands, this code gives a 2-3 times improvement over the Numpy optimized code you have. However, you need to pass the numbers in correctly. The arrays need to be in C format (which is the default for Numpy arrays, but in Numpy the transpose of a C formatted array is a Fortran formatted array).
For instance, to run the code from your other question, you will need to replace the np.random.random((3,N))s with np.random.random((N,3)). Also, `
r_test_fast = reshape_vector(r_test)
needs to be changed to
r_test_fast = np.array(np.matrix(r_test))
This last line can be made simpler/faster, but this would be premature optimization in my opinion.
If you haven't used Cython before and don't know how to compile this, then let me know and I'll be glad to help.
Lastly, I would recommend looking at this paper. I used it as a guide for my optimizations. The next step would be to try to use BLAS functions that make use of the SSE2 instruction set, trying to use the SSE API, or trying to use more of the Numpy C API which interfaces with the SSE2 stuff. Also, you can look into parallelizing.
A:
Python isn't intended for high-performance computation. Write the core loop in C and call it from Python.
|
What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
|
I'm writing a scientific application in Python with a very processor-intensive loop at its core. I would like to optimise this as far as possible, at minimum inconvenience to end users, who will probably use it as an uncompiled collection of Python scripts, and will be using Windows, Mac, and (mainly Ubuntu) Linux.
It is currently written in Python with a dash of NumPy, and I've included the code below.
Is there a solution which would be reasonably fast which would not require compilation? This would seem to be the easiest way to maintain platform-independence.
If using something like Pyrex, which does require compilation, is there an easy way to bundle many modules and have Python choose between them depending on detected OS and Python version? Is there an easy way to build the collection of modules without needing access to every system with every version of Python?
Does one method lend itself particularly to multi-processor optimisation?
(If you're interested, the loop is to calculate the magnetic field at a given point inside a crystal by adding together the contributions of a large number of nearby magnetic ions, treated as tiny bar magnets. Basically, a massive sum of these.)
# calculate_dipole
# -------------------------
# calculate_dipole works out the dipole field at a given point within the crystal unit cell
# ---
# INPUT
# mu = position at which to calculate the dipole field
# r_i = array of atomic positions
# mom_i = corresponding array of magnetic moments
# ---
# OUTPUT
# B = the B-field at this point
def calculate_dipole(mu, r_i, mom_i):
relative = mu - r_i
r_unit = unit_vectors(relative)
#4pi / mu0 (at the front of the dipole eqn)
A = 1e-7
#initalise dipole field
B = zeros(3,float)
for i in range(len(relative)):
#work out the dipole field and add it to the estimate so far
B += A*(3*dot(mom_i[i],r_unit[i])*r_unit[i] - mom_i[i]) / sqrt(dot(relative[i],relative[i]))**3
return B
|
[
"You can get this to run much, much faster if you eliminate the loop and use Numpy's vectorized operations. Put your data in numpy arrays of shape (3,N) and try the following:\nimport numpy as np\n\nN = 20000\nmu = np.random.random((3,1))\nr_i = np.random.random((3,N))\nmom_i = np.random.random((3,N))\n\ndef unit_vectors(r):\n return r / np.sqrt((r*r).sum(0))\n\ndef calculate_dipole(mu, r_i, mom_i):\n relative = mu - r_i\n r_unit = unit_vectors(relative)\n A = 1e-7\n\n num = A*(3*np.sum(mom_i*r_unit, 0)*r_unit - mom_i)\n den = np.sqrt(np.sum(relative*relative, 0))**3\n B = np.sum(num/den, 1)\n return B\n\nThis runs about 50 times faster for me than using a for loop.\n",
"Numpy does use some native optimization for array processing. You can use Numpy array with Cython to gain some speed-ups.\n",
"Your python code could probably be speeded up a bit by replacing your loop with a generator expression and removing all the lookups of mom_i[i], relative[i] and r_unit[i] by iterating through all three sequences in parallel using itertools.izip.\ni.e. replace\nB = zeros(3,float)\n\nfor i in range(len(relative)):\n #work out the dipole field and add it to the estimate so far\n B += A*(3*dot(mom_i[i],r_unit[i])*r_unit[i] - mom_i[i]) / sqrt(dot(relative[i],relative[i]))**3\nreturn B\n\nwith:\nfrom itertools import izip\n...\nreturn sum((A*(3*dot(mom,ru)*ru - mom) / sqrt(dot(rel,rel))**3 \n for mom, ru, rel in izip(mom_i, r_unit, relative)),\n zeros(3,float)) \n\nThis is also more readable IMHO since the core equation is not cluttered with [i] everywhere.. \nI suspect however that this will only get you marginal gains compared to doing the whole function in a compiled language such as Cython.\n",
"One simple, but significant speed-up is to take the multiplication by A outside of your sum. You can just times the B with it as you return it:\nfor i in range(len(relative)):\n #work out the dipole field and add it to the estimate so far\n B += (3*dot(mom_i[i],r_unit[i])*r_unit[i] - mom_i[i]) / sqrt(dot(relative[i],relative[i]))**3\n\nreturn A*B\n\nThis gave about an 8% speed-up using 20,000 random dipoles.\nBeyond that easy speed-up, I would recommend using Cython (which is generally recommended over using Pyrex) or Weave from Scipy. Take a look at the Performance Python for some examples and comparisons of various ways to speed-up Numpy/Scipy.\nIf you want to try making this parallel, I would recommend looking at Scipy's Parallel Programming to get started.\nIt's good to see another physicist on SO. There aren't very many on here.\nEdit:\nI decided to take this as a challenge to develop some Cython skills and got about a 10x time improvement over a Psyco optimized version. Let me know if you'd like to see my code.\nEdit2:\nOkay, went back and found what was slowing things up in my Cython version. Now the speed-up is well over 100x. If you want or need another factor of 2x or so over Ray's sped-up Numpy version, let me know and I will post my code.\nCython source code:\nHere's the Cython code that I drummed up:\nimport numpy as np\ncimport numpy as np\ncimport cython\ncdef extern from \"math.h\":\n double sqrt(double theta)\nctypedef np.float64_t dtype_t\n\n@cython.boundscheck(False)\n@cython.wraparound(False)\ndef calculate_dipole_cython(np.ndarray[dtype_t,ndim=2,mode=\"c\"] mu, \n np.ndarray[dtype_t,ndim=2,mode=\"c\"] r_i, \n np.ndarray[dtype_t,ndim=2,mode=\"c\"] mom_i):\n cdef Py_ssize_t i\n cdef np.ndarray[dtype_t,ndim=1,mode=\"c\"] tmp = np.empty(3,np.float64)\n cdef np.ndarray[dtype_t,ndim=1,mode=\"c\"] relative = np.empty(3,np.float64)\n cdef double A = 1e-7\n cdef double C, D, F\n cdef np.ndarray[dtype_t,ndim=1,mode=\"c\"] B = np.zeros(3,np.float64)\n for i in xrange(r_i.shape[0]):\n relative[0] = mu[0,0] - r_i[i,0]\n relative[1] = mu[0,1] - r_i[i,1]\n relative[2] = mu[0,2] - r_i[i,2]\n C = relative[0]*relative[0] + relative[1]*relative[1] + relative[2]*relative[2]\n C = 1.0/sqrt(C)\n D = C**3\n tmp[0] = relative[0]*C\n F = mom_i[i,0]*tmp[0]\n tmp[1] = relative[1]*C\n F += mom_i[i,1]*tmp[1]\n tmp[2] = relative[2]*C\n F += mom_i[i,2]*tmp[2]\n F *= 3\n B[0] += (F*tmp[0] - mom_i[i,0])*D\n B[1] += (F*tmp[1] - mom_i[i,1])*D\n B[2] += (F*tmp[2] - mom_i[i,2])*D\n return A*B\n\nI've optimized it quite a bit I think, but there might be a little more you can get out of it. You can still maybe replace the np.zeros and np.empty with direct calls from the Numpy C API, but that shouldn't make much of a difference. As it stands, this code gives a 2-3 times improvement over the Numpy optimized code you have. However, you need to pass the numbers in correctly. The arrays need to be in C format (which is the default for Numpy arrays, but in Numpy the transpose of a C formatted array is a Fortran formatted array).\nFor instance, to run the code from your other question, you will need to replace the np.random.random((3,N))s with np.random.random((N,3)). Also, `\nr_test_fast = reshape_vector(r_test) \n\nneeds to be changed to\nr_test_fast = np.array(np.matrix(r_test))\n\nThis last line can be made simpler/faster, but this would be premature optimization in my opinion. \nIf you haven't used Cython before and don't know how to compile this, then let me know and I'll be glad to help.\nLastly, I would recommend looking at this paper. I used it as a guide for my optimizations. The next step would be to try to use BLAS functions that make use of the SSE2 instruction set, trying to use the SSE API, or trying to use more of the Numpy C API which interfaces with the SSE2 stuff. Also, you can look into parallelizing.\n",
"Python isn't intended for high-performance computation. Write the core loop in C and call it from Python.\n"
] |
[
10,
4,
3,
2,
1
] |
[] |
[] |
[
"optimization",
"python"
] |
stackoverflow_0002586749_optimization_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.