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 l... | 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 ... | [
"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 = spmatri... | [
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 paginati... | 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 va... | [
"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' ins... | [
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 [Nod... | 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 "... | [
"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'\\|(.*?)\\|/*\\[(.*... | [
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':
... | 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... | [
"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 urlencod... | [
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 ./firef... | 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-b... | [
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 p... | 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 N... | [
"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, wh... | [
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 fe... | 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 und... | [
"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... | [
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 us... | 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(b... | [
"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 i... | [
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 QTextCu... | 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... | [
"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 t... | [
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 resour... | 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 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;-).\nIf you're thinking about performing such controls inside your own Python program... | [
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... | 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 y... | [
"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" />... | 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 ... | [
"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:\nfr... | [
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:
... | 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)
taskqu... | [
"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 t... | [
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)
{
namespac... | 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;
... | [
"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... | [
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 '... | 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 HT... | [
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],
'f... | 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 reg... | [
"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 w... | [
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:
... | 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 ... | [
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.gethostbyad... | 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.get... | [
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.et... | 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 <R... | [
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 ev... | 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 appreciat... | [
"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... | [
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... | 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... | 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 s... | [
"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 ... | [
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 ... | 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 ... | [
"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 elem... | [
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 co... | 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:
... | [
"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()\... | [
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 choosin... | 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 --... | [
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.... | 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... | [
"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 ... | [
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 r... | 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 do... | [
"\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... | 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 recalcul... | [
"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 eve... | [
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 val... | 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 varian... | [
"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\nfro... | [
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
imp... | 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 Bea... | [
"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 co... | [
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; chec... | 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 rig... | [
"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 ... | [
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... | 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', ME... | [
"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', appli... | 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 WS... | [
"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... | [
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 b... | 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 gener... | [
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 (mo... | 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:... | [
"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... | [
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 ... | 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 a... | [
"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 ... | [
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).s... | 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\"): # ... | [
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
Thi... | 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
... | [
"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 file... | [
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 over... | 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 comp... | [
"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 b... | [
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 exis... | 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.isdi... | [
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... | 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\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 oth... | 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 da... | [
"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 networki... | [
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 r... | 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... | [
"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,... | [
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.date... | 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... | [
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 differen... | 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 thi... | [
"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 wi... | [
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
... | 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 imp... | [
"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 m... | 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 ... | [
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... | 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 al... | [
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 e... | 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 ... | [
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. :-... | [
-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 ... | 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... | [
"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 a... | [
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 ... | 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 ... | [
"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>\... | [
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 eve... | 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, ... | [
"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 ... | [
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 __in... | 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 tes... | [
"\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... | [
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 anywa... | 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 t... | [
"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... | [
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 ... | 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 (... | [
"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 com... | [
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] ... [sa... | 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]
... | [
"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... | [
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 ... | 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... | [
"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 b... | [
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 lik... | 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 t... | [
"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 ... | [
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 u... | 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 id... | [
"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... | 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... | [
"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 subproc... | [
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)
mymode... | 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 i... | [
"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. r... | [
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 ... | 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 mountpoin... | [
"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, ... | [
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... | 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 authenticati... | [
"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 authoriza... | [
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 th... | 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... | [
"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... | [
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 came... | 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))... | 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 i... | [
"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 isinsta... | [
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
... | 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(n... | [
"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 ... | [
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 t... | 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 th... | [
"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... | [
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 ad... | 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_LIBR... | [
"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 *.dyli... | [
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 [... | 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... | [
"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).\... | [
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)):
temp... | 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:]
... | [
"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 fin... | [
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 dra... | 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, 2... | 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)
... | [
"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.EmptyB... | [
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 r... | 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 ve... | [
"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... | [
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 t... | 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 err... | [
"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 rea... | [
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(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 ... | [
"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... | [
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], ...)
d... | 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_functio... | [
"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_compl... | [
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.CopyFi... | 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 f... | [
"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(sr... | [
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
>>>... | 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('.... | [
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 diff... | 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 ... | [
"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 ... | 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... | [
"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 cy... | [
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... | 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 c... | [
"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 ... | [
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... | 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)
... | [
"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 ... | [
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.... | 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.... | [
"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 ... | 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 ... | [
"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 s... | [
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.... | 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 begi... | [
"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("u... | 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... | [
"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('<', st... | [
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})', ... | 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 o... | [
">>> 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>>>... | [
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 p... | 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... | [
">>> 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... | [
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 ... | 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 ... | [
"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 o... | 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 ... | [
"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... | [
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... | 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/... | [
"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 helpin... | 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.21... | [
"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\... | [
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 r... | 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 ... | 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',... | [
">>> 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\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... | 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 installe... | [
"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.... | 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... | [
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 binari... | 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 com... | [
"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... | [
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 comp... | 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 ... | [
"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 s... | [
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 ... | 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 ... | [
"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_v... | [
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.