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:
Django m2m queries, distinct Users for a m2m relationship of a Model
I have a model Model with a m2m field :
user = .. fk user
...
watchers = models.ManyToManyField(User, related_name="boardShot_watchers", null=True)
How do i select all distinct Users involved in this watchers relationship for all my entrie... | Django m2m queries, distinct Users for a m2m relationship of a Model | I have a model Model with a m2m field :
user = .. fk user
...
watchers = models.ManyToManyField(User, related_name="boardShot_watchers", null=True)
How do i select all distinct Users involved in this watchers relationship for all my entries of type Model ?
I dont think there is an ORM way to access to intermedia... | [
"Not in your current model. If you want to have explicit access to the joining table, you need to make it part of the Django object model. The docs explain how to do this:\nhttp://www.djangoproject.com/documentation/models/m2m_intermediary/\nThe admin and other django.contrib* components can be configured to treat ... | [
2
] | [] | [] | [
"django",
"m2m",
"orm",
"python"
] | stackoverflow_0000807470_django_m2m_orm_python.txt |
Q:
How to query filter in django without multiple occurrences
I have 2 models:
ParentModel: 'just' sits there
ChildModel: has a foreign key to ParentModel
ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()) gives multiple occurrences of ParentModel.
How do I query all ParentModels that have at least o... | How to query filter in django without multiple occurrences | I have 2 models:
ParentModel: 'just' sits there
ChildModel: has a foreign key to ParentModel
ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()) gives multiple occurrences of ParentModel.
How do I query all ParentModels that have at least one ChildModel that's referring to it? And without multiple occur... | [
"You almost got it right...\nParentModel.objects.filter(childmodel__in=ChildModel.objects.all()).distinct()\n\n",
"You might want to avoid using childmodel__in=ChildModel.objects.all() if the number of ChildModel objects is large. This will generate SQL with all ChildModel id's enumerated in a list, possibly crea... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000796971_django_python.txt |
Q:
Python embedding with threads -- avoiding deadlocks?
Is there any way to embed python, allow callbacks from python to C++, allowing the Pythhon code to spawn threads, and avoiding deadlocks?
The problem is this:
To call into Python, I need to hold the GIL. Typically, I do this by getting the main thread state whe... | Python embedding with threads -- avoiding deadlocks? | Is there any way to embed python, allow callbacks from python to C++, allowing the Pythhon code to spawn threads, and avoiding deadlocks?
The problem is this:
To call into Python, I need to hold the GIL. Typically, I do this by getting the main thread state when I first create the interpreter, and then using PyEval_Re... | [
"\"When calling into Python, I may need to hold the same locks, because I may be iterating over some collection of objects, for example.\"\nThis often indicates that a single process with multiple threads isn't appropriate. Perhaps this is a situation where multiple processes -- each with a specific object from th... | [
2,
2
] | [
"There was recently some discussion of a similar issue on the pyopenssl list. I'm afraid if I try to explain this I'm going to get it wrong, so instead I'll refer you to the problem in question.\n"
] | [
-1
] | [
"deadlock",
"embedding",
"multithreading",
"python"
] | stackoverflow_0000803566_deadlock_embedding_multithreading_python.txt |
Q:
Printing XML into HTML with python
I have a TextEdit widget in PyQt that I use to print out a log in HTML. I use HTML so I can separate entries into color categories (red for error, yellow for debug, blue for message, etc), but this creates a problem. Most of the debug messages are XML. When I use appendHtml on th... | Printing XML into HTML with python | I have a TextEdit widget in PyQt that I use to print out a log in HTML. I use HTML so I can separate entries into color categories (red for error, yellow for debug, blue for message, etc), but this creates a problem. Most of the debug messages are XML. When I use appendHtml on the widget, it strips out all the tags.
Ho... | [
"cgi.escape can help you. It will convert the characters '&', '<' and '>' in the string to HTML-safe sequences. That is enough to prevent interpretation of xml tags.\n>>> cgi.escape('<tag>')\n'<tag>\n\n",
"A cdata section might help.\nhttp://reference.sitepoint.com/javascript/CDATASection\nhttp://en.wikiped... | [
4,
0
] | [] | [] | [
"html",
"python",
"xml"
] | stackoverflow_0000808529_html_python_xml.txt |
Q:
SQLAlchemy - Mapper configuration and declarative base
I am writing a multimedia archive database backend and I want to use joined table inheritance. I am using Python with SQLAlchemy with the declarative extension. The table holding the media record is as follows:
_Base = declarative_base()
class Record(_Base):
... | SQLAlchemy - Mapper configuration and declarative base | I am writing a multimedia archive database backend and I want to use joined table inheritance. I am using Python with SQLAlchemy with the declarative extension. The table holding the media record is as follows:
_Base = declarative_base()
class Record(_Base):
__tablename__ = 'records'
item_id = Column(String(M... | [
"I finally found the answer in the manual.\nhttp://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#joined-table-inheritance\n"
] | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0000792588_python_sqlalchemy.txt |
Q:
Parsing files with Python
What type of Python objects should I use to parse files with a specific syntax? Also what sort of loop should be followed to make it through the file. Should one pass be sufficient? Two, three?
A:
It depends on the grammar. You can use pyparsing instead of implementing your own parser. ... | Parsing files with Python | What type of Python objects should I use to parse files with a specific syntax? Also what sort of loop should be followed to make it through the file. Should one pass be sufficient? Two, three?
| [
"It depends on the grammar. You can use pyparsing instead of implementing your own parser. It is very easy to use. \n",
"You should offer more information about your aims ...\n\nWhat kind of file\nWhat structure? Tab separated? XML - like?\nWhat kind of encoding?\nWhats the target structure?\nDo you need to repar... | [
3,
2,
1,
0
] | [] | [] | [
"object",
"parsing",
"python"
] | stackoverflow_0000808621_object_parsing_python.txt |
Q:
Python - Threading and a While True Loop
I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached).
Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the... | Python - Threading and a While True Loop | I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached).
Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running..
ti... | [
"Are your threads appending to self.output here, with your main task consuming them? If so, this is a tailor-made job for Queue.Queue. Your code should become something like:\nimport Queue\n\n# Initialise queue as:\nqueue = Queue.Queue()\nFinished = object() # Unique marker the producer will put in the queue wh... | [
11,
1,
0,
0,
0
] | [] | [] | [
"loops",
"multithreading",
"python"
] | stackoverflow_0000808746_loops_multithreading_python.txt |
Q:
Make python enter password when running a csh script
I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm usin... | Make python enter password when running a csh script | I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:
import commands
commands.get... | [
"Have a look at the pexpect module. It is designed to deal with interactive programs, which seems to be your case.\nOh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D\n",
"Use subprocess. Call Popen() to create your process and use communicate() to s... | [
8,
5,
1,
1,
0,
0,
0
] | [] | [] | [
"csh",
"passwords",
"python",
"root",
"scripting"
] | stackoverflow_0000230845_csh_passwords_python_root_scripting.txt |
Q:
Python regex for finding contents of MediaWiki markup links
If I have some xml containing things like the following mediawiki markup:
" ...collected in the 12th century, of which [[Alexander the Great]] was the
hero, and in which he was represented,
somewhat like the British [[King
Arthur|Arthur]]"
what... | Python regex for finding contents of MediaWiki markup links | If I have some xml containing things like the following mediawiki markup:
" ...collected in the 12th century, of which [[Alexander the Great]] was the
hero, and in which he was represented,
somewhat like the British [[King
Arthur|Arthur]]"
what would be the appropriate arguments to something like:
re.findall... | [
"Here is an example\nimport re\n\npattern = re.compile(r\"\\[\\[([\\w \\|]+)\\]\\]\")\ntext = \"blah blah [[Alexander of Paris|poet named Alexander]] bldfkas\"\nresults = pattern.findall(text)\n\noutput = []\nfor link in results:\n output.append(link.split(\"|\")[0])\n\n# outputs ['Alexander of Paris']\n\nVersio... | [
5,
1,
1,
1
] | [] | [] | [
"mediawiki",
"python",
"regex"
] | stackoverflow_0000809837_mediawiki_python_regex.txt |
Q:
how to manually assign imagefield in Django
I have a model that has an ImageField. How can I manually assign an imagefile to it? I want it to treat it like any other uploaded file...
A:
See the django docs for django.core.files.File
Where fd is an open file object:
model_instance.image_field.save('filename.jpeg'... | how to manually assign imagefield in Django | I have a model that has an ImageField. How can I manually assign an imagefile to it? I want it to treat it like any other uploaded file...
| [
"See the django docs for django.core.files.File\nWhere fd is an open file object:\nmodel_instance.image_field.save('filename.jpeg', fd.read(), True)\n\n"
] | [
20
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000811167_django_django_models_python.txt |
Q:
reading a stream made by urllib2 never recovers when connection got interrupted
While trying to make one of my python applications a bit more robust in case of connection interruptions I discovered that calling the read function of an http-stream made by urllib2 may block the script forever.
I thought that the re... | reading a stream made by urllib2 never recovers when connection got interrupted | While trying to make one of my python applications a bit more robust in case of connection interruptions I discovered that calling the read function of an http-stream made by urllib2 may block the script forever.
I thought that the read function will timeout and eventually raise an exception but this does not seam to ... | [
"Try something like:\nimport socket\nsocket.setdefaulttimeout(5.0)\n ...\ntry:\n ...\nexcept socket.timeout:\n (it timed out, retry)\n\n",
"Good question, I would be really interested in finding an answer. The only workaround I could think of is using the signal trick explained in python docs.\nIn your case... | [
7,
2
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0000811446_python_urllib2.txt |
Q:
Is it possible to write a great PHP app which uses Unicode?
My next web application project will make extensive use of Unicode. I usually use PHP and CodeIgniter however Unicode is not one of PHP's strong points.
Is there a PHP tool out there that can help me get Unicode working well in PHP?
Or should I take the o... | Is it possible to write a great PHP app which uses Unicode? | My next web application project will make extensive use of Unicode. I usually use PHP and CodeIgniter however Unicode is not one of PHP's strong points.
Is there a PHP tool out there that can help me get Unicode working well in PHP?
Or should I take the opportunity to look into alternatives such as Python?
| [
"PHP can handle unicode fine once you make sure to encode and decode on entry and exit. If you are storing in a database, ensure that the language encodings and charset mappings match up between the html pages, web server, your editor, and the database.\nIf the whole application uses UTF-8 everywhere, decoding is n... | [
4,
1,
0
] | [] | [] | [
"php",
"python",
"unicode",
"web_applications"
] | stackoverflow_0000811306_php_python_unicode_web_applications.txt |
Q:
string encodings in python
In python, strings may be unicode ( both utf-16 and utf-8 ) and single-byte with different encodings ( cp1251, cp1252 etc ). Is it possible to check what encoding string is? For example,
time.strftime( "%b" )
will return a string with text name of a month. Under MacOS returned string wi... | string encodings in python | In python, strings may be unicode ( both utf-16 and utf-8 ) and single-byte with different encodings ( cp1251, cp1252 etc ). Is it possible to check what encoding string is? For example,
time.strftime( "%b" )
will return a string with text name of a month. Under MacOS returned string will be utf-16, under Windows with... | [
"Strings don't store any encoding information, you just have to specify one when you convert to/from unicode or print to an output device :\nimport locale\nlang, encoding = locale.getdefaultlocale()\nmystring = u\"blabla\"\nprint mystring.encode(encoding)\n\nUTF-8 is not unicode, it's an encoding of unicode into si... | [
5,
1,
1
] | [] | [] | [
"codepages",
"python",
"unicode"
] | stackoverflow_0000810794_codepages_python_unicode.txt |
Q:
Python Timeout script to kill thread active for more than X seconds
I have been looking all over the place for a good timeout script that can kill a thread if it's been active for more than X seconds, but all the examples I've seen have flaws that don't always stop the thread. Using thread.join(x) ends up defeatin... | Python Timeout script to kill thread active for more than X seconds | I have been looking all over the place for a good timeout script that can kill a thread if it's been active for more than X seconds, but all the examples I've seen have flaws that don't always stop the thread. Using thread.join(x) ends up defeating the purpose of it being a thread.
The only decent example I have found ... | [
"See my answer to python: how to send packets in multi thread and then the thread kill itself - there is a fragment with InterruptableThread class and example that kill another thread after timeout - exactly what you want.\nThere is also similar Python recipe at activestate.\n",
"I know this might not be what you... | [
2,
0
] | [] | [] | [
"multithreading",
"python",
"timeout"
] | stackoverflow_0000811692_multithreading_python_timeout.txt |
Q:
What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)?
In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so t... | What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)? | In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so they can be checked out and the environment loaded for use regardless of os/platform, kinda similar to the approach vi... | [
"I wouldn't abandon 2.6 just because of deprecation warnings; those will disappear over time. (You can use the -W ignore option to the Python interpreter to prevent them from being printed out, at least) But if modules you need to use actually don't work with Python 2.6, that would be a legitimate reason to stay wi... | [
5,
4,
2,
2,
1
] | [] | [] | [
"production",
"python",
"standards",
"supervisord"
] | stackoverflow_0000812085_production_python_standards_supervisord.txt |
Q:
python- is beautifulsoup misreporting my html?
I have two machines each, to the best of my knowledge, running python 2.5 and BeautifulSoup 3.1.0.1.
I'm trying to scrape http://utahcritseries.com/RawResults.aspx, using:
from BeautifulSoup import BeautifulSoup
import urllib2
base_url = "http://www.utahcritseries.... | python- is beautifulsoup misreporting my html? | I have two machines each, to the best of my knowledge, running python 2.5 and BeautifulSoup 3.1.0.1.
I'm trying to scrape http://utahcritseries.com/RawResults.aspx, using:
from BeautifulSoup import BeautifulSoup
import urllib2
base_url = "http://www.utahcritseries.com/RawResults.aspx"
data=urllib2.urlopen(base_url)... | [
"There are documented problems with version 3.1 of BeautifulSoup.\nYou might want to double check that is the version you in fact are using, and if so downgrade.\n",
"I suspect the problem is in the urlib2 request, not BeautifulSoup:\nIt might help if you show us the same section of the raw data as returned by th... | [
2,
1
] | [] | [] | [
"beautifulsoup",
"configuration",
"macos",
"python",
"screen_scraping"
] | stackoverflow_0000810173_beautifulsoup_configuration_macos_python_screen_scraping.txt |
Q:
Python decorating functions before call
I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?
A:
With:
decorator(original_function)()
Wit... | Python decorating functions before call | I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?
| [
"With:\ndecorator(original_function)()\n\nWithout:\noriginal_function()\n\nA decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some documentation might help clarify things.\n",
"def original_function():\n pass\n\... | [
26,
2,
1
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0000282393_decorator_python.txt |
Q:
Thread Finished Event in Python
I have a PyQt program, in this program I start a new thread for drawing a complicated image.
I want to know when the thread has finished so I can print the image on the form.
The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I... | Thread Finished Event in Python | I have a PyQt program, in this program I start a new thread for drawing a complicated image.
I want to know when the thread has finished so I can print the image on the form.
The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to... | [
"In the samples with PyQt-Py2.6-gpl-4.4.4-2.exe, there's the Mandelbrot app. In my install, the source is in C:\\Python26\\Lib\\site-packages\\PyQt4\\examples\\threads\\mandelbrot.pyw. It uses a thread to render the pixmap and a signal (search the code for QtCore.SIGNAL) to tell the GUI thread its time to draw. ... | [
3,
2,
0,
0
] | [] | [] | [
"delegates",
"multithreading",
"python"
] | stackoverflow_0000812870_delegates_multithreading_python.txt |
Q:
Ruby String Translation
I want to find the successor of each element in my encoded string. For example K->M A->C etc.
string.each_char do |ch|
dummy_string<< ch.succ.succ
end
However this method translates y->aa.
Is there a method in Ruby that is like maketrans() in Python?
A:
You seem to be looking for... | Ruby String Translation | I want to find the successor of each element in my encoded string. For example K->M A->C etc.
string.each_char do |ch|
dummy_string<< ch.succ.succ
end
However this method translates y->aa.
Is there a method in Ruby that is like maketrans() in Python?
| [
"You seem to be looking for String#tr. Use like this: some_string.tr('a-zA-Z', 'c-zabC-ZAB')\n",
"def successor(s)\n s.tr('a-zA-Z','c-zabC-ZAB')\nend\n\nsuccessor(\"Chris Doggett\") #\"Ejtku Fqiigvv\"\n\n",
"I don't know of one offhand, but I think the Ruby way would probably involve passing a block to a re... | [
8,
1,
0
] | [] | [] | [
"python",
"ruby",
"string"
] | stackoverflow_0000813147_python_ruby_string.txt |
Q:
Why does python logging package not support printing variable length args?
When I first learned Python, I got used to doing this:
print "text", lineNumber, "some dictionary", my_dict
When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this:... | Why does python logging package not support printing variable length args? | When I first learned Python, I got used to doing this:
print "text", lineNumber, "some dictionary", my_dict
When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this:
def error(*args):
print ERR_PREFIX,
for _x in args:
print _x,
pr... | [
"I would suggest that it would be better to update the existing logging messages to the style that the logging module expects as it will be easier for other people looking at your code as the logging module will not longer function as they expect. \nThat out of the way, the following code will make the logging mod... | [
7,
2,
1,
0,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0000812422_logging_python.txt |
Q:
I want to make a temporary answerphone which records MP3s
An artistic project will encourage users to ring a number and leave a voice-mail on an automated service. These voice-mails will be collected and edited into a half-hour radio show.
I want to make a temporary system (with as little as possible programming)... | I want to make a temporary answerphone which records MP3s | An artistic project will encourage users to ring a number and leave a voice-mail on an automated service. These voice-mails will be collected and edited into a half-hour radio show.
I want to make a temporary system (with as little as possible programming) which will:
Allow me to establish a public telephone number (... | [
"I use twilio, very easy, very fun.\n",
"Skype has a voicemail feature which sounds perfect for this and I suppose you would need a SkypeIn number as well\n",
"You may want to check out asterisk. I don't think it will become any easier than using an existing system.\nMaybe you can find someone in the asterisk c... | [
5,
2,
1,
1
] | [] | [] | [
"python",
"voip"
] | stackoverflow_0000813114_python_voip.txt |
Q:
Is there a way to check whether function output is assigned to a variable in Python?
In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of so... | Is there a way to check whether function output is assigned to a variable in Python? | In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just
check_status()
I would like to see something like:
Pretty printer... | [
"New Solution\nThis is a new that solution detects when the result of the function is used for assignment by examining its own bytecode. There is no bytecode writing done, and it should even be compatible with future versions of Python because it uses the opcode module for definitions.\nimport inspect, dis, opcode\... | [
5,
4,
3,
2,
2,
0,
0
] | [] | [] | [
"bytecode",
"functional_programming",
"python"
] | stackoverflow_0000813882_bytecode_functional_programming_python.txt |
Q:
How can I create a locked-down python environment?
I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-... | How can I create a locked-down python environment? | I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution.
After some frustratin... | [
"\"reasonably safe\" defined arbitrarily as \"safer than Excel and VBA\".\nYou can't win that fight. Because the fight is over the wrong thing. Anyone can use any EXE or DLL.\nYou need to define \"locked down\" differently -- in a way that you can succeed.\nYou need to define \"locked down\" as \"cannot change th... | [
9,
3,
3,
1,
0
] | [] | [] | [
"excel",
"python",
"security",
"windows"
] | stackoverflow_0000811670_excel_python_security_windows.txt |
Q:
PY2EXE: How to output "*_D.PYD" file (debug) and use MSVCR80D.DLL?
The debug configuration of my app is built against:
PYTHON25_D.DLL
MSVCR80D.DLL
We use Python .PYD files in our application. Some of these .PYD are .PY converted by PY2EXE to .PYD.
When I run PY2EXE on MYSCRIPT.PY, I get the following .PYD and... | PY2EXE: How to output "*_D.PYD" file (debug) and use MSVCR80D.DLL? | The debug configuration of my app is built against:
PYTHON25_D.DLL
MSVCR80D.DLL
We use Python .PYD files in our application. Some of these .PYD are .PY converted by PY2EXE to .PYD.
When I run PY2EXE on MYSCRIPT.PY, I get the following .PYD and dependencies:
MYSCRIPT.PYD
PYTHON25.DLL
MSVCR71.DLL
KERNEL32.DLL ... | [
"it won't work, beacuse MSVCR80D is a side by side runtime\nYou will need to either tell user to directly install MS runtime or manually also copy the manifest files.\nAlso the MSVCR71.DLL is not selected for you. It's for Python, so you may still need to keep it.\n",
"Note that the MS debug dlls are nondistribut... | [
0,
0
] | [] | [] | [
"py2exe",
"python",
"windows"
] | stackoverflow_0000814078_py2exe_python_windows.txt |
Q:
distributed/faster python unit tests
I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test exec... | distributed/faster python unit tests | I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster?
| [
"You can't frequently run all your tests, because they're too slow. This is an inevitable consequence of your project getting bigger, and won't go away. Sure, you may be able to run the tests in parallel and get a nice speedup, but the problem will just come back later, and it'll never be as it was when your projec... | [
5,
3,
2,
1,
1
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0000809564_python_unit_testing.txt |
Q:
Amazon S3 permissions
Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration... | Amazon S3 permissions | Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration date and that won't work f... | [
"There are various ways to control access to the S3 objects:\n\nUse the query string auth - but as you noted this does require an expiration date. You could make it far in the future, which has been good enough for most things I have done.\nUse the S3 ACLS - but this requires the user to have an AWS account and au... | [
14,
8,
1,
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"django",
"python"
] | stackoverflow_0000765964_amazon_s3_amazon_web_services_django_python.txt |
Q:
Python regex parsing
I have an array of strings in python which each string in the array looking something like this:
<r n="Foo Bar" t="5" s="10" l="25"/>
I have been searching around for a while and the best thing I could find is attempting to modify a HTML hyperlink regex into something that will fit my needs.... | Python regex parsing | I have an array of strings in python which each string in the array looking something like this:
<r n="Foo Bar" t="5" s="10" l="25"/>
I have been searching around for a while and the best thing I could find is attempting to modify a HTML hyperlink regex into something that will fit my needs.
But not really knowing mu... | [
"This will get you most of the way there:\n>>> print re.findall(r'(\\w+)=\"(.*?)\"', string)\n[('n', 'Foo Bar'), ('t', '5'), ('s', '10'), ('l', '25')]\n\nre.split and re.findall are complementary.\nEvery time your thought process begins with \"I want each item that looks like X\", then you should use re.findall. Wh... | [
7,
6
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000814786_python_regex.txt |
Q:
python regular exp. with a unicode char
I need a reg exp that will parse something like-
"2 * 240pin"
where the * can be either the regular star or unicode char \u00d7 or just an x. This is what I have but its not working:
multiple= r'^(\d+)\s?x|*|\\u00d7\s?(\d+)(\w{2,4})$'
multiplepat= re.compile(multiple, re.I)... | python regular exp. with a unicode char | I need a reg exp that will parse something like-
"2 * 240pin"
where the * can be either the regular star or unicode char \u00d7 or just an x. This is what I have but its not working:
multiple= r'^(\d+)\s?x|*|\\u00d7\s?(\d+)(\w{2,4})$'
multiplepat= re.compile(multiple, re.I)
print multiplepat.search(u'1 X 240pin').grou... | [
"multiple= r'^(\\d+)\\s[xX\\*\\\\u00d7]\\s?(\\d+)(\\w{2,4})$'\n\n",
"You need to escape the * as it is a quantifier in the context you use it. But you could also use a character class. So try this: \nur'^(\\d+)\\s?[x*\\u00d7]\\s?(\\d+)(\\w{2,4})$'\n\n",
"Use character sets ([]) :\n\n[]\nUsed to indicate a set o... | [
2,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000814933_python_regex.txt |
Q:
Can I encrypt email and decrypt it back using python default library set?
Of course similar questions have been asked in stackoverflow but I don't want to use any third party library like Crypto or something. So I need to generate a ciphertext from a user email and decrypt it back to plaintext. How can I do this i... | Can I encrypt email and decrypt it back using python default library set? | Of course similar questions have been asked in stackoverflow but I don't want to use any third party library like Crypto or something. So I need to generate a ciphertext from a user email and decrypt it back to plaintext. How can I do this in python?
| [
"Yes, you can. \nRead http://www.amk.ca/python/code/crypto.html\nYou'll find an answer there ;)\nYou're question is not concrete enough to say more. You may want to read http://en.wikipedia.org/wiki/Cryptography#Modern_cryptography\nCheers,\n Tuergeist\nUpdate: \nNo, you cannot. (with build in functionality due to ... | [
4,
4,
1
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0000806739_encryption_python.txt |
Q:
What is the best (idiomatic) way to check the type of a Python variable?
I need to know if a variable in Python is a string or a dict. Is there anything wrong with the following code?
if type(x) == type(str()):
do_something_with_a_string(x)
elif type(x) == type(dict()):
do_somethting_with_a_dict(x)
else:
... | What is the best (idiomatic) way to check the type of a Python variable? | I need to know if a variable in Python is a string or a dict. Is there anything wrong with the following code?
if type(x) == type(str()):
do_something_with_a_string(x)
elif type(x) == type(dict()):
do_somethting_with_a_dict(x)
else:
raise ValueError
Update: I accepted avisser's answer (though I will chang... | [
"What happens if somebody passes a unicode string to your function? Or a class derived from dict? Or a class implementing a dict-like interface? Following code covers first two cases. If you are using Python 2.6 you might want to use collections.Mapping instead of dict as per the ABC PEP.\ndef value_list(x):\n i... | [
346,
63,
46,
23,
8,
7,
3,
3,
1
] | [
"*sigh*\nNo, typechecking arguments in python is not necessary. It is never \nnecessary.\nIf your code accepts either a string or a dict object, your design is broken.\nThat comes from the fact that if you don't know already the type of an object\nin your own program, then you're doing something wrong already.\nTyp... | [
-2
] | [
"python",
"typechecking",
"types"
] | stackoverflow_0000378927_python_typechecking_types.txt |
Q:
Python imports from crossreferencing packages
Currently I'm trying to write my first Python library and I've encountered the following problem:
I have the following import in my package myapp.factories:
from myapp.models import *
And the following in my package myapp.models:
from myapp.factories import *
I need ... | Python imports from crossreferencing packages | Currently I'm trying to write my first Python library and I've encountered the following problem:
I have the following import in my package myapp.factories:
from myapp.models import *
And the following in my package myapp.models:
from myapp.factories import *
I need the models in my factories package but inside one m... | [
"\"inside one model I also need one of the factories\" - just import that factory where you need it:\nclass SomeModel:\n def some_method(self):\n from myapp.factories import SomeFactory\n SomeFactory().do_something()\n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0000815367_python.txt |
Q:
C# Web Server: Implementing a Dynamic Language
I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following:
ASP.NET
PHP
Python
I'd ... | C# Web Server: Implementing a Dynamic Language | I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following:
ASP.NET
PHP
Python
I'd prefer to implement PHP or Python because I am much ... | [
"ASP.NET will surely be the easiest as you can use all the built in classes. Essentially you don't need to build it, you just hook it up to the Web server (I don't know if we can count it as writing ASP.NET though ;) )\nYou might want to look at Cassini source code\n",
"Have you considered boo? It has a very conf... | [
1,
1,
1,
0,
0
] | [] | [] | [
"asp.net",
"php",
"python",
"webserver"
] | stackoverflow_0000815446_asp.net_php_python_webserver.txt |
Q:
How do you remove html tags using Universal Feed Parser?
The documentation lists the tags that are allowed/removed by default:
http://www.feedparser.org/docs/html-sanitization.html
But it doesn't say anything about how you can specify which additional tags you want removed.
Is there a way to do this using Universa... | How do you remove html tags using Universal Feed Parser? | The documentation lists the tags that are allowed/removed by default:
http://www.feedparser.org/docs/html-sanitization.html
But it doesn't say anything about how you can specify which additional tags you want removed.
Is there a way to do this using Universal Feed Parser or do you have to do further processing using yo... | [
"i took a quick look over the code and i don't think there is a way to overwrite them directly. But you can overwrite feedparser._HTMLSanitizer.acceptable_elements, the list of tags that wont get removed before doing feedparser.parse\n"
] | [
6
] | [] | [] | [
"django",
"feed",
"parsing",
"python"
] | stackoverflow_0000815606_django_feed_parsing_python.txt |
Q:
Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent
Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl?
UPDATE:
I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing?
Something that you can override so th... | Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent | Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl?
UPDATE:
I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing?
Something that you can override so that when you do a readline() type call its looking for something other than t... | [
"You could use the ''.join method. e.g.\n# print 'foo', 'bar', 'baz' separated by spaces\nprint 'foo', 'bar', 'baz'\n# print separated by commas\nprint ', '.join(['foo', 'bar', 'baz'])\n\nEDIT:\nOk, I misunderstood the purpose of OUTPUT_RECORD_SEPARATOR, so ''.join is not what you want.\nprint 'foo' is equivalent ... | [
1,
1,
1,
0,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0000770925_file_io_python.txt |
Q:
how to get the url of the current page in a GAE template
In Google App Engine, is there a tag or other mechanism to get the URL of the current page in a template or is it necessary to pass the url as a variable to the template from the python code?
A:
It depends how you are populating the templates. If you are ... | how to get the url of the current page in a GAE template | In Google App Engine, is there a tag or other mechanism to get the URL of the current page in a template or is it necessary to pass the url as a variable to the template from the python code?
| [
"It depends how you are populating the templates. If you are using them outside of Django, then you have to populate them with the URL yourself. If you are using them in Django with the default configuration, you would have to populate them with the URL yourself. An alternative that would avoid you having to pop... | [
3
] | [] | [] | [
"django_templates",
"google_app_engine",
"python",
"templates",
"web_applications"
] | stackoverflow_0000816683_django_templates_google_app_engine_python_templates_web_applications.txt |
Q:
How to unescape apostrophes and such in Python?
I have a string with symbols like this:
'
That's an apostrophe apparently.
I tried saxutils.unescape() without any luck and tried urllib.unquote()
How can I decode this? Thanks!
A:
Check out this question. What you're looking for is "html entity decoding". Typ... | How to unescape apostrophes and such in Python? | I have a string with symbols like this:
'
That's an apostrophe apparently.
I tried saxutils.unescape() without any luck and tried urllib.unquote()
How can I decode this? Thanks!
| [
"Check out this question. What you're looking for is \"html entity decoding\". Typically, you'll find a function named something like \"htmldecode\" that will do what you want. Both Django and Cheetah provide such functions as does BeautifulSoup.\nThe other answer will work just great if you don't want to use a lib... | [
2,
2,
1
] | [] | [] | [
"django",
"html",
"html_entities",
"python"
] | stackoverflow_0000816272_django_html_html_entities_python.txt |
Q:
Does Python have properties?
So something like:
vector3.Length
that's in fact a function call that calculates the length of the vector, not a variable.
A:
With new-style classes you can use property(): http://www.python.org/download/releases/2.2.3/descrintro/#property.
A:
Yes: http://docs.python.org/library/f... | Does Python have properties? | So something like:
vector3.Length
that's in fact a function call that calculates the length of the vector, not a variable.
| [
"With new-style classes you can use property(): http://www.python.org/download/releases/2.2.3/descrintro/#property.\n",
"Yes: http://docs.python.org/library/functions.html#property\n",
"If your variable vector3 is a 3-dimensional directed distance of a point from an origin, and you need its length, use somethin... | [
14,
6,
5,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0000813135_python.txt |
Q:
If I want to use a pylons app with Apache, should I use mod_wsgi or proxy to paste?
Or should I be using a totally different server?
A:
Nginx with mod_wsgi requires the use of a non-blocking asynchronous framework and setup and isn't likely to work out of box with Pylons.
I usually go with the proxy route to a s... | If I want to use a pylons app with Apache, should I use mod_wsgi or proxy to paste? | Or should I be using a totally different server?
| [
"Nginx with mod_wsgi requires the use of a non-blocking asynchronous framework and setup and isn't likely to work out of box with Pylons.\nI usually go with the proxy route to a stand-alone Pylons process using the PasteScript#cherrypy WSGI server (as its higher performing than the Paste#http one, though it won't r... | [
8,
0
] | [] | [] | [
"apache2",
"mod_wsgi",
"pylons",
"python"
] | stackoverflow_0000813943_apache2_mod_wsgi_pylons_python.txt |
Q:
Overriding the save method in Django ModelForm
I'm having trouble overriding a ModelForm save method. This is the error I'm receiving:
Exception Type: TypeError
Exception Value: save() got an unexpected keyword argument 'commit'
My intentions are to have a form submit many values for 3 fields, to then cr... | Overriding the save method in Django ModelForm | I'm having trouble overriding a ModelForm save method. This is the error I'm receiving:
Exception Type: TypeError
Exception Value: save() got an unexpected keyword argument 'commit'
My intentions are to have a form submit many values for 3 fields, to then create an object for each combination of those fields,... | [
"In your save you have to have the argument commit. If anything overrides your form, or wants to modify what it's saving, it will do save(commit=False), modify the output, and then save it itself.\nAlso, your ModelForm should return the model it's saving. Usually a ModelForm's save will look something like:\ndef sa... | [
167
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0000817284_django_django_admin_django_forms_python.txt |
Q:
Python/Twisted - TCP packet fragmentation?
In Twisted when implementing the dataReceived method, there doesn't seem to be any examples which refer to packets being fragmented. In every other language this is something you manually implement, so I was just wondering if this is done for you in twisted already or wha... | Python/Twisted - TCP packet fragmentation? | In Twisted when implementing the dataReceived method, there doesn't seem to be any examples which refer to packets being fragmented. In every other language this is something you manually implement, so I was just wondering if this is done for you in twisted already or what? If so, do I need to prefix my packets with a ... | [
"In the dataReceived method you get back the data as a string of indeterminate length meaning that it may be a whole message in your protocol or it may only be part of the message that some 'client' sent to you. You will have to inspect the data to see if it comprises a whole message in your protocol.\nI'm current... | [
6,
6,
2
] | [] | [] | [
"packet",
"python",
"tcp",
"twisted"
] | stackoverflow_0000460144_packet_python_tcp_twisted.txt |
Q:
Update Facebooks Status using Python
Is there an easy way to update my Facebook status ("What's on your mind?" box) using Python code ?
A:
Check out PyFacebook which has a tutorial, from... Facebook!
Blatantly ripped from the documentation on that page and untested, you'd probably do something like this:
import ... | Update Facebooks Status using Python | Is there an easy way to update my Facebook status ("What's on your mind?" box) using Python code ?
| [
"Check out PyFacebook which has a tutorial, from... Facebook!\nBlatantly ripped from the documentation on that page and untested, you'd probably do something like this:\nimport facebook\nfb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY')\nfb.auth.createToken()\nfb.login()\nfb.auth.getSession()\nfb.set_status... | [
12,
3
] | [] | [] | [
"facebook",
"python"
] | stackoverflow_0000817431_facebook_python.txt |
Q:
What's a good way to mix RSS feeds using Python?
SimplePie lets you merge feeds together:
http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date
Is there anything like this in the Python world? The Universal Feed Parser documentation doesn't say anything about merging multiple feeds together.
A:
... | What's a good way to mix RSS feeds using Python? | SimplePie lets you merge feeds together:
http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date
Is there anything like this in the Python world? The Universal Feed Parser documentation doesn't say anything about merging multiple feeds together.
| [
"This may be a good start for you. I wrote it a long time ago for one very specific combination, but I don't think I wrote it too specifically for my needs.\n",
" Planet is a feed aggregator written in Python. Its development is basically dead, but the code lives on in several forks, including Planet Venus.\n",
... | [
2,
1,
1,
0
] | [] | [] | [
"django",
"feed",
"parsing",
"python",
"rss"
] | stackoverflow_0000816118_django_feed_parsing_python_rss.txt |
Q:
Python's random: What happens if I don't use seed(someValue)?
a)In this case does the random number generator uses the system's clock (making the seed change) on each run?
b)Is the seed used to generate the pseudo-random values of expovariate(lambda)?
A:
"Use the Source, Luke!"...;-). Studying https://svn.pyt... | Python's random: What happens if I don't use seed(someValue)? | a)In this case does the random number generator uses the system's clock (making the seed change) on each run?
b)Is the seed used to generate the pseudo-random values of expovariate(lambda)?
| [
"\"Use the Source, Luke!\"...;-). Studying https://svn.python.org/projects/python/trunk/Lib/random.py will rapidly reassure you;-).\nWhat happens when seed isn't set (that's the \"i is None\" case):\nif a is None:\n try:\n a = long(_hexlify(_urandom(16)), 16)\n except NotImplementedError:\n imp... | [
18,
6,
3
] | [] | [] | [
"python",
"random",
"seed"
] | stackoverflow_0000817705_python_random_seed.txt |
Q:
Dynamically change range in Python?
So say I'm using BeautifulSoup to parse pages and my code figures out that there are at least 7 pages to a query.
The pagination looks like
1 2 3 4 5 6 7 Next
If I paginate all the way to 7, sometimes there are more than 7 pages, so that if I am on page 7, the pagination looks... | Dynamically change range in Python? | So say I'm using BeautifulSoup to parse pages and my code figures out that there are at least 7 pages to a query.
The pagination looks like
1 2 3 4 5 6 7 Next
If I paginate all the way to 7, sometimes there are more than 7 pages, so that if I am on page 7, the pagination looks like
1 2 3 7 8 9 10 Next
So now, I ... | [
"You could probably çreate a generator that has mutable state that determines when it terminates... but what about something simple like this?\npage = 1\nwhile page < num_pages + 1:\n # do stuff that possibly updates num_pages here\n page += 1\n\n",
"Here's a code free answer, but I think it's simple if you... | [
6,
3,
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0000816712_beautifulsoup_python.txt |
Q:
callable as instancemethod?
Let's say we've got a metaclass CallableWrappingMeta which walks the body of a new class, wrapping its methods with a class, InstanceMethodWrapper:
import types
class CallableWrappingMeta(type):
def __new__(mcls, name, bases, cls_dict):
for k, v in cls_dict.iteritems():
... | callable as instancemethod? | Let's say we've got a metaclass CallableWrappingMeta which walks the body of a new class, wrapping its methods with a class, InstanceMethodWrapper:
import types
class CallableWrappingMeta(type):
def __new__(mcls, name, bases, cls_dict):
for k, v in cls_dict.iteritems():
if isinstance(v, types.F... | [
"Just enrich you InstanceMethodWrapper class with a __get__ (which can perfectly well just return self) -- that is, make that class into a descriptor type, so that its instances are descriptor objects. See http://users.rcn.com/python/download/Descriptor.htm for background and details.\nBTW, if you're on Python 2.6... | [
4,
0,
0,
0
] | [] | [] | [
"metaclass",
"methods",
"python",
"python_descriptors"
] | stackoverflow_0000815947_metaclass_methods_python_python_descriptors.txt |
Q:
C55: More Info?
I saw a PyCon09 keynote presentation (slides: http://www.slideshare.net/kn0thing/ride-the-snake-reddit-keynote-pycon-09?c55) given by the reddit guys, and in it they mention a CSS compiler called C55. They said it would be open sourced soon. It looks cool - does anyone have more information about h... | C55: More Info? | I saw a PyCon09 keynote presentation (slides: http://www.slideshare.net/kn0thing/ride-the-snake-reddit-keynote-pycon-09?c55) given by the reddit guys, and in it they mention a CSS compiler called C55. They said it would be open sourced soon. It looks cool - does anyone have more information about how it works, why they... | [
"Just from the talk, the main advantage over simply generating CSS from templates is that it allows nesting, which is conceptually a lot nicer to work with.\nSo you could do something like this in C55 (obviously I'm kind of making up the syntax):\ndiv.content\n{\n color: $content_color ;\n\n .left\n {\n float... | [
3
] | [] | [] | [
"css",
"python",
"reddit"
] | stackoverflow_0000818016_css_python_reddit.txt |
Q:
In what way would you present an algorithm to detect collisions between different objects?
While working on a really only-for-fun project I encountered some problem.
There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCr... | In what way would you present an algorithm to detect collisions between different objects? | While working on a really only-for-fun project I encountered some problem.
There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCreatures. They can move inside this world. When they meet each other, a Collision happens.
The th... | [
"Use a quadtree. They're used to eliminate large regions that you know are outside a collision radius, plus they let you quickly search for the closest point.\nAs far as actual collision detection goes, since you're only using convex objects, take a look at Metanet Software's tutorial on the separating axis theore... | [
5,
1,
1,
0
] | [] | [] | [
"collision_detection",
"python"
] | stackoverflow_0000646539_collision_detection_python.txt |
Q:
Shouldn't __metaclass__ force the use of a metaclass in Python?
I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting __metaclass__ to M at the globa... | Shouldn't __metaclass__ force the use of a metaclass in Python? | I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting __metaclass__ to M at the global or class level. To test this out, I wrote the following program:
p ... | [
"In Python 3 (which you are using) metaclasses are specified by a keyword parameter in the class definition:\nclass ClassMeta(metaclass=M):\n pass\n\nSpecifying a __metaclass__ class property or global variable is old syntax from Python 2.x and not longer supported. See also \"What's new in Python 3\" and PEP 2115... | [
14,
2,
2
] | [] | [] | [
"metaclass",
"oop",
"python",
"python_3.x"
] | stackoverflow_0000818483_metaclass_oop_python_python_3.x.txt |
Q:
Web-Based Music Library (programming concept)
So, I've been tossing this idea around in my head for a while now. At its core, it's mostly a project for me to learn programming. The idea is that, I have a large set of data, my music collection. There are quite a few datasets that my music has. Format, artist, t... | Web-Based Music Library (programming concept) | So, I've been tossing this idea around in my head for a while now. At its core, it's mostly a project for me to learn programming. The idea is that, I have a large set of data, my music collection. There are quite a few datasets that my music has. Format, artist, title, album, genre, length, year of release, filena... | [
"I think this is a fine project to learn programming with. By using your own \"product\" you can really get after things that are missing and are much more motivated to learn and better your program - this is known as dogfooding. Curiously enough, the book Dive Into Python, although a little old, covers in some det... | [
3,
1,
1,
1
] | [] | [] | [
"mysql",
"php",
"python"
] | stackoverflow_0000818752_mysql_php_python.txt |
Q:
Spliting a file into lines in Python using re.split
I'm trying to split a file with a list comprehension using code similar to:
lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)]
However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this... | Spliting a file into lines in Python using re.split | I'm trying to split a file with a list comprehension using code similar to:
lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)]
However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)?
| [
"Put the regular expression hammer away :-)\n\nYou can iterate over a file directly; readlines() is almost obsolete these days.\nRead about str.strip() (and its friends, lstrip() and rstrip()).\nDon't use file as a variable name. It's bad form, because file is a built-in function.\n\nYou can write your code as:\nl... | [
9,
3,
1,
0
] | [] | [] | [
"list_comprehension",
"python",
"regex"
] | stackoverflow_0000818705_list_comprehension_python_regex.txt |
Q:
Creating dictionaries with pre-defined keys
In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?
A:
You can also have the dict subclass restrict the keys to a predefined list, by overriding __setitem__()
>>> class LimitedDict(... | Creating dictionaries with pre-defined keys | In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?
| [
"You can also have the dict subclass restrict the keys to a predefined list, by overriding __setitem__()\n>>> class LimitedDict(dict):\n _keys = \"a b c\".split()\n def __init__(self, valtype=int):\n for key in LimitedDict._keys:\n self[key] = valtype()\n def __setitem__(self, key, val):\... | [
12,
10,
3,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0000817884_dictionary_python.txt |
Q:
Is there a way to correctly sort unicode strings in SQLite using Python?
Is there a simple way to order rows with unicode data in SQLite?
A:
SQLite has a BYOS (Bring Your Own Sorter) policy. See the FAQ for more details. They chose not to include (by default) any Unicode-aware sorting algorithm, to keep the SQ... | Is there a way to correctly sort unicode strings in SQLite using Python? | Is there a simple way to order rows with unicode data in SQLite?
| [
"SQLite has a BYOS (Bring Your Own Sorter) policy. See the FAQ for more details. They chose not to include (by default) any Unicode-aware sorting algorithm, to keep the SQLite library svelte and easy to statically link in. \nHowever, you can create a collator, that sorts however you please, then tell SQLite to u... | [
5,
2
] | [] | [] | [
"python",
"sqlite",
"unicode"
] | stackoverflow_0000819211_python_sqlite_unicode.txt |
Q:
A wxPython timeline widget
I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for:
Imagine something like the widget that Audacity uses to display an audio track. It's a ... | A wxPython timeline widget | I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for:
Imagine something like the widget that Audacity uses to display an audio track. It's a horizontal timeline, with a rule... | [
"A quick web search doesn't yield anything but others hoping for the same thing. My guess is you won't find any nice wx widgets for timelines. The closest you're likely to get is a wxSlider. This is far from ideal, but it'll get you up and running. You can also look at creating a custom widget -- that'd definit... | [
1,
1
] | [] | [] | [
"controls",
"python",
"timeline",
"widget",
"wxpython"
] | stackoverflow_0000715950_controls_python_timeline_widget_wxpython.txt |
Q:
Working with a QString encoding
Is there a Python library which can detect (and perhaps decode) encoding of the string?
I found chardet but it gives me an error, using:
chardet.detect(self.ui.TextFrom.toPlainText())
got: = chardet.detect(self.ui.TextFrom.toPlainText())
File .... u.feed(aBuf) File ....
if self._hi... | Working with a QString encoding | Is there a Python library which can detect (and perhaps decode) encoding of the string?
I found chardet but it gives me an error, using:
chardet.detect(self.ui.TextFrom.toPlainText())
got: = chardet.detect(self.ui.TextFrom.toPlainText())
File .... u.feed(aBuf) File ....
if self._highBitDetector.search(aBuf):
TypeErro... | [
"You need to convert your QString to a Python string before passing it to chardet. Change this:\nchardet.detect(self.ui.TextFrom.toPlainText())\n\nto this:\nchardet.detect(str(self.ui.TextFrom.toPlainText()))\n\n",
"I guess this is another option.\nhttp://cthedot.de/encutils/\n\nA collection of helper functions ... | [
7,
2
] | [] | [] | [
"encoding",
"python"
] | stackoverflow_0000819310_encoding_python.txt |
Q:
Python, who is calling my python module
I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line).
Is there a way to establish if the module has been called from the CGI script or from the comma... | Python, who is calling my python module | I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line).
Is there a way to establish if the module has been called from the CGI script or from the command line ??
| [
"This will do it:\nimport os\nif os.environ.has_key('REQUEST_METHOD'):\n # You're being run as a CGI script.\nelse:\n # You're being run from the command line.\n\n",
"This is a really bad design idea. Your script should be designed to work independently of how it's called. The calling programs should prov... | [
9,
6
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0000819217_cgi_python.txt |
Q:
How do I handle exceptions when using threading and Queue?
If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs).
from threading import Thread
from Queue import Queu... | How do I handle exceptions when using threading and Queue? | If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs).
from threading import Thread
from Queue import Queue
from time import sleep
def do_work(item):
sleep(0.5)
... | [
"The simplest way is to start all the worker threads as daemon threads, then just have your main loop be\nwhile True:\n sleep(1)\n\nHitting Ctrl+C will throw an exception in your main thread, and all of the daemon threads will exit when the interpreter exits. This assumes you don't want to perform cleanup in al... | [
6
] | [] | [] | [
"exception",
"multithreading",
"python"
] | stackoverflow_0000820111_exception_multithreading_python.txt |
Q:
SyntaxError in finally (Django)
I'm using Django, and I have the following error:
Exception Type: SyntaxError
Exception Value: invalid syntax (views.py, line 115)
My viws.py code looks like this:
def myview(request):
try:
[...]
except MyExceptionClass, e:
[...]
finally:
render_to_response('templ... | SyntaxError in finally (Django) | I'm using Django, and I have the following error:
Exception Type: SyntaxError
Exception Value: invalid syntax (views.py, line 115)
My viws.py code looks like this:
def myview(request):
try:
[...]
except MyExceptionClass, e:
[...]
finally:
render_to_response('template.html', {}, context_instance = Req... | [
"What version of python are you using? Prior to 2.5 you can't have both an except clause and a finally clause in the same try block.\nYou can work around this by nesting try blocks.\ndef myview(request):\n try:\n try:\n [...]\n except MyExceptionClass, e:\n [...]\n finally:... | [
14,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000820778_django_python.txt |
Q:
Pylons or TurboGears vs. .NET or Java
We're embarking on a project for a client. They plan on having about 50k users by the end of the year. We're pushing to use Pylons w/ Mako and SQLAlchemy, and our contact there is excited about it, but some of his colleagues are wary because it's not .NET or J2ee (they're use... | Pylons or TurboGears vs. .NET or Java | We're embarking on a project for a client. They plan on having about 50k users by the end of the year. We're pushing to use Pylons w/ Mako and SQLAlchemy, and our contact there is excited about it, but some of his colleagues are wary because it's not .NET or J2ee (they're used to enterprisey stuff).
Their web app will... | [
"If you're looking for a success story for a customer, Virgin Charter is using Pylons with SQLAlchemy for their site. This is a high-value transaction system as people are booking very expensive flights through the site.\nFor a more high-traffic site, Reddit is now running on Pylons, along with Charlie Rose.\nSQLAl... | [
5,
3
] | [
"They are crazy if they want to use j2ee imho. Visual Studio/C# is very nice, especially if you are not trying to do anything tricky. However, if you want to customize the C# way of doing things beyond what it was explicitly designed for it can quickly turn into a mess -- you get mired in automatically generated ... | [
-1
] | [
"jakarta_ee",
"java",
"pylons",
"python",
"wsgi"
] | stackoverflow_0000783488_jakarta_ee_java_pylons_python_wsgi.txt |
Q:
SQL TOP 1 analog for lists in Python
Here is an example of my input csv file:
...
0.7,0.5,0.35,14.4,0.521838919218
0.7,0.5,0.35,14.4,0.521893472678
0.7,0.5,0.35,14.4,0.521948026139
0.7,0.5,0.35,14.4,0.522002579599
...
I need to select the top row where the last float > random number. My current implementation ... | SQL TOP 1 analog for lists in Python | Here is an example of my input csv file:
...
0.7,0.5,0.35,14.4,0.521838919218
0.7,0.5,0.35,14.4,0.521893472678
0.7,0.5,0.35,14.4,0.521948026139
0.7,0.5,0.35,14.4,0.522002579599
...
I need to select the top row where the last float > random number. My current implementation is very slow (script has a lot of iteratio... | [
"The fastest approach is to use bisect (assuming the float list is ordered). You can do it like this:\nimport bisect\n\nfloat_list = [line[-1] for line in foo]\nindex = bisect.bisect(float_list, random.random())\nif index < len(float_list)\n result = foo[index]\nelse:\n result = None # None exists\n\nThe floa... | [
3,
1
] | [] | [] | [
"python",
"tsql"
] | stackoverflow_0000821416_python_tsql.txt |
Q:
How do content discovery engines, like Zemanta and Open Calais work?
I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against?
How would a se... | How do content discovery engines, like Zemanta and Open Calais work? | I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against?
How would a service like Zemanta know what images to suggest to a piece of text for inst... | [
"Michal Finkelstein from OpenCalais here.\nFirst, thanks for your interest. I'll reply here but I also encourage you to read more on OpenCalais forums; there's a lot of information there including - but not limited to:\nhttp://opencalais.com/tagging-information\nhttp://opencalais.com/how-does-calais-learn\nAlso fee... | [
9,
7,
0
] | [] | [] | [
"python",
"ruby",
"semantics",
"zemanta"
] | stackoverflow_0000022059_python_ruby_semantics_zemanta.txt |
Q:
what python feature is illustrated in this code?
I read Storm ORM's tutorial at https://storm.canonical.com/Tutorial, and I stumbled upon the following piece of code :
store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie")
I'm not sure that the second argument of the find method will be eva... | what python feature is illustrated in this code? | I read Storm ORM's tutorial at https://storm.canonical.com/Tutorial, and I stumbled upon the following piece of code :
store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie")
I'm not sure that the second argument of the find method will be evaluated to True/False. I think it will be interpreted a... | [
"Person.name has a overloaded __eq__ method that returns not a boolean value but an object that stores both sides of the expression; that object can be examined by the find() method to obtain the attribute and value that it will use for filtering. I would describe this as a type of lazy evaluation pattern.\nIn Sto... | [
22,
9,
8,
1,
0
] | [] | [] | [
"language_features",
"python"
] | stackoverflow_0000821855_language_features_python.txt |
Q:
Implement Blackjack in Python
I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:
Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.
Calculate what the player's score is and whether it is an ace and a jack togethe... | Implement Blackjack in Python | I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:
Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.
Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.
Ok, thi... | [
"This can get you started:\nhttp://docs.python.org/library/random.html\nhttp://docs.python.org/library/strings.html\nhttp://docs.python.org/library/stdtypes.html\nhttp://docs.python.org/reference/index.html\nI see you have added some code; that's good.\nThink about the parts of your program that will need to exist.... | [
14,
4,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000551840_python.txt |
Q:
Parse a .txt file
I have a .txt file like:
Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT |00000004| |.data
__ctype_tab |00000000| r | OBJECT |00000101| |.rodata
Symbols fr... | Parse a .txt file | I have a .txt file like:
Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT |00000004| |.data
__ctype_tab |00000000| r | OBJECT |00000101| |.rodata
Symbols from _ashldi3.o:
Name ... | [
"for line in open('thefile.txt'):\n fields = line.split('|')\n if len(fields) < 4: continue\n if fields[3].trim() != 'FUNC': continue\n dowhateveryouwishwith(line, fields)\n\n",
"I think this might cost less than the use of regexes though i am not totally clear on what you are trying to accomplish\nsymbolList... | [
9,
4,
2
] | [] | [] | [
"parsing",
"python",
"text_files"
] | stackoverflow_0000818936_parsing_python_text_files.txt |
Q:
I need a regex for the href attribute for an mp3 file url in python
Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module:
import re
urls = re.finditer('http://(.*?).mp3', htmlcode)
The variable urls is an iterable object and I can use a lo... | I need a regex for the href attribute for an mp3 file url in python | Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module:
import re
urls = re.finditer('http://(.*?).mp3', htmlcode)
The variable urls is an iterable object and I can use a loop to access each mp3 file url individually if there is more than one :
f... | [
"As pointed out by the other answers, using regular expressions to parse HTML = bad, bad idea.\nWith that in mind, I will add in code of my favorite parser: BeautifulSoup:\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(htmlcode)\nlinks = soup.findAll('a', href=True)\nmp3s = [l for l in links if l... | [
3,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000822260_python_regex.txt |
Q:
How do I iterate over the HTML attributes of a Beautiful Soup element?
How do I iterate over the HTML attributes of a Beautiful Soup element?
Like, given:
<foo bar="asdf" blah="123">xyz</foo>
I want "bar" and "blah".
A:
from BeautifulSoup import BeautifulSoup
page = BeautifulSoup('<foo bar="asdf" blah="123">xyz... | How do I iterate over the HTML attributes of a Beautiful Soup element? | How do I iterate over the HTML attributes of a Beautiful Soup element?
Like, given:
<foo bar="asdf" blah="123">xyz</foo>
I want "bar" and "blah".
| [
"from BeautifulSoup import BeautifulSoup\npage = BeautifulSoup('<foo bar=\"asdf\" blah=\"123\">xyz</foo>')\nfor attr, value in page.find('foo').attrs:\n print attr, \"=\", value\n\n# Prints:\n# bar = asdf\n# blah = 123\n\n"
] | [
32
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0000822571_beautifulsoup_python.txt |
Q:
WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order
I'm learning wxPython so most of the libraries and classes are new to me.
I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is ... | WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order | I'm learning wxPython so most of the libraries and classes are new to me.
I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is intended to run both on GNOME and Windows, so I want to make sure th... | [
"The appearance of a dialog can change only if you use stock dialogs (like wx.FileDialog), if you make your own the layout will stay the same on every platform.\nwx.Dialog has a CreateStdDialogButtonSizer method that creates a wx.StdDialogButtonSizer with standard buttons where you might see differences in layout o... | [
4,
2,
0,
0
] | [] | [] | [
"cross_platform",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0000818942_cross_platform_python_user_interface_wxpython.txt |
Q:
Why is this recursive statement wrong?
This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20.
Things we... | Why is this recursive statement wrong? | This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20.
Things were working just fine till I decided to exclu... | [
"I think you want \nreturn getnormal(self)\n\ninstead of\ngetnormal(self)\n\nIf the function exits without hitting a return statement, then it returns the special value None, which is a NoneType object - that's why Python complains about a 'NoneType.' The abs() function wants a number, and it doesn't know what to d... | [
8,
1,
1
] | [] | [] | [
"python",
"recursion",
"simpy"
] | stackoverflow_0000823141_python_recursion_simpy.txt |
Q:
Yaml merge in Python
So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file.
So I was thinking it would be useful if the library provide... | Yaml merge in Python | So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file.
So I was thinking it would be useful if the library provided a default yaml tree and ... | [
"You could use PyYAML for parsing the files, and then the following function to merge two trees:\ndef merge(user, default):\n if isinstance(user,dict) and isinstance(default,dict):\n for k,v in default.iteritems():\n if k not in user:\n user[k] = v\n else:\n ... | [
22
] | [] | [] | [
"configuration",
"python",
"yaml"
] | stackoverflow_0000823196_configuration_python_yaml.txt |
Q:
How can I use Numerical Python with Python 2.6
I'm forced to upgrade to Python 2.6 and am having issues using Numerical Python (NumPy) with Python 2.6 in Windows. I'm getting the following error...
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from numpy.core.numeric import arra... | How can I use Numerical Python with Python 2.6 | I'm forced to upgrade to Python 2.6 and am having issues using Numerical Python (NumPy) with Python 2.6 in Windows. I'm getting the following error...
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from numpy.core.numeric import array,dot,all
File "C:\svn\svn_urbansim\UrbanSimDev\Bu... | [
"How did you install it? NumPy doesn't currently have a Python 2.6 binary.\nIf you have LAPACK/ATLAS/BLAS, etc. and a development environment you should be able to compile numpy from sources. Otherwise I think you're stuck with using Python 2.5 on Windows if you need NumPy.\nThe next version of NumPy should have ... | [
9,
3
] | [] | [] | [
"numpy",
"python",
"windows"
] | stackoverflow_0000417664_numpy_python_windows.txt |
Q:
Why Python informixdb package is throwing an error!
I have downloaded & installed the latest Python InformixDB package, but when I try to import it from the shell, I am getting the following error in the form of a Windows dialog box!
"A procedure entry point sqli_describe_input_stmt could not be located in the dyn... | Why Python informixdb package is throwing an error! | I have downloaded & installed the latest Python InformixDB package, but when I try to import it from the shell, I am getting the following error in the form of a Windows dialog box!
"A procedure entry point sqli_describe_input_stmt could not be located in the dynamic link isqlit09a.dll"
Any ideas what's happening?
Plat... | [
"Which version of IBM Informix Connect (I-Connect) or IBM Informix ClientSDK (CSDK) are you using? The 'describe input' function is a more recent addition, but it is likely that you have it.\nHave you been able to connect to any Informix DBMS from the command shell? If not, then the suspicion must be that you don... | [
1,
0
] | [] | [] | [
"informix",
"python"
] | stackoverflow_0000801515_informix_python.txt |
Q:
How can I make a change to a module without restarting python interpreter?
I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing.
Is there an easier way to do this?
Thanks,
Charlie
A:
The built-in func... | How can I make a change to a module without restarting python interpreter? | I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing.
Is there an easier way to do this?
Thanks,
Charlie
| [
"The built-in function reload is what you're looking for.\n",
"It sounds like you want to reload the module, for which there is a built-in function reload(module). That said, when I looked it up just now (to make sure I had my reference right, Google returned a couple of discussions (granted they are several yea... | [
10,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0000820431_python.txt |
Q:
logging in mod_python/apache
What is the standard way to make python's logging module work with apache/modpython?
I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request.
Is there an easy way to set this up?
A:
I've never done it, but it seems th... | logging in mod_python/apache | What is the standard way to make python's logging module work with apache/modpython?
I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request.
Is there an easy way to set this up?
| [
"I've never done it, but it seems that writing a subclass of logging.Handler shouldn't be that hard. Something like this should do the trick. I can't say that I have actually tried this since I don't have mod_python installed currently but you should be able to call logging.root.addHandler(ApacheLogHandler()) somew... | [
2
] | [
"We use the following. It's documented completely here.\n\nWe use logging.fileConfig with a logging.ini file.\nEach module uses logger= logging.getLogger(__name__)\nThen we can do logger.error(\"blah blah blah\") throughout our application.\n\nIt works perfectly. The logging.ini file defines where the log file go... | [
-1
] | [
"apache",
"logging",
"mod_python",
"python"
] | stackoverflow_0000822875_apache_logging_mod_python_python.txt |
Q:
App dock icon in wxPython
In wxPython on Mac OS X is it possible to display a custom icon when an application is launched. Right now when I launch the app I wrote, a blank white icon is displayed in the dock. How would I go about changing it?
A:
I have this in my setup file to add an icon:
from setuptools import... | App dock icon in wxPython | In wxPython on Mac OS X is it possible to display a custom icon when an application is launched. Right now when I launch the app I wrote, a blank white icon is displayed in the dock. How would I go about changing it?
| [
"I have this in my setup file to add an icon:\nfrom setuptools import setup\n\nAPP = ['MyApp.py']\nDATA_FILES = []\nOPTIONS = {'argv_emulation': True, \n 'iconfile': 'MyAppIcon.icns' }\n\nsetup(\n app=APP,\n data_files=DATA_FILES,\n options={'py2app': OPTIONS},\n setup_requires=['py2app'],\n)\n\nI th... | [
1
] | [] | [] | [
"macos",
"python",
"wxpython"
] | stackoverflow_0000824458_macos_python_wxpython.txt |
Q:
Best way for Parsing ANSI and UTF-16LE files using Python 2/3?
I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.
Is there a str... | Best way for Parsing ANSI and UTF-16LE files using Python 2/3? | I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.
Is there a straightforward way to open up the files using the correct file encodin... | [
"Use the chardet library to detect the encoding.\n",
"You can check for the BOM at the beginning of the file to check whether it's UTF.\nThen unicode.decode accordingly (using one of the standard encodings).\nEDIT\nOr, maybe, try s.decode('ascii') your string (given s is the variable name). If it throws UnicodeDe... | [
4,
0,
0
] | [] | [] | [
"ansi",
"encoding",
"python",
"utf_16"
] | stackoverflow_0000819396_ansi_encoding_python_utf_16.txt |
Q:
rules for slugs and unicode
After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.
url encoding is very restrictive. See http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
So, for example how do folks deal with for t... | rules for slugs and unicode | After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.
url encoding is very restrictive. See http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
So, for example how do folks deal with for title slugs for things like
"Una l... | [
"Nearly-complete transliteration table (for latin, greek and cyrillic character sets) can be found in slughifi library. It is geared towards Django, but can be easily modified to fit general needs (I use it with Werkzeug-based app on AppEngine).\n",
"I simply use utf-8 for URL paths. As long as the domain is non-... | [
8,
4,
2,
1
] | [] | [] | [
"friendly_url",
"google_app_engine",
"python",
"unicode",
"url"
] | stackoverflow_0000820496_friendly_url_google_app_engine_python_unicode_url.txt |
Q:
Initialisation of keyword args in Python
Why does the following:
class A(object):
def __init__(self, var=[]):
self._var = var
print 'var = %s %s' % (var, id(var))
a1 = A()
a1._var.append('one')
a2 = A()
result in:
var = [] 182897439952
var = ['one'] 182897439952
I don't understand why it is... | Initialisation of keyword args in Python | Why does the following:
class A(object):
def __init__(self, var=[]):
self._var = var
print 'var = %s %s' % (var, id(var))
a1 = A()
a1._var.append('one')
a2 = A()
result in:
var = [] 182897439952
var = ['one'] 182897439952
I don't understand why it is not using a new instance of a list when using... | [
"The empty list in your function definition is created once, at the time the function itself is created. It isn't created every time the function is called.\nIf you want a new one each time, do this:\nclass A(object):\n def __init__(self, var=None):\n if var is None:\n var = []\n self._... | [
6,
2,
1
] | [] | [] | [
"arguments",
"initialization",
"instantiation",
"python"
] | stackoverflow_0000824924_arguments_initialization_instantiation_python.txt |
Q:
Change/adapt date widget on admin interface
I'm configuring the admin site for my new app, and I found a little problem with my setup.
I have a 'birth date' field on my database editable via the admin site, but, the date widget isn't very handy for that, because it makes that, if I have to enter i.e. 01-04-1956 in... | Change/adapt date widget on admin interface | I'm configuring the admin site for my new app, and I found a little problem with my setup.
I have a 'birth date' field on my database editable via the admin site, but, the date widget isn't very handy for that, because it makes that, if I have to enter i.e. 01-04-1956 in the widget, i would have to page through a lot o... | [
"Use the formfield_overrides option to use a different widget. For example (untested):\nclass MyModelAdmin(admin.ModelAdmin):\n formfield_overrides = {\n models.DateField: {'widget': forms.TextInput},\n }\n\nThen you'll need to do date conversion/validation yourself.\n"
] | [
4
] | [] | [] | [
"date",
"django",
"python",
"widget"
] | stackoverflow_0000825253_date_django_python_widget.txt |
Q:
What does += mean in Python?
I see code like this for example in Python:
if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
What does the += mean?
A:
a += b is essentially the same as a = a + b, except that:
+ always returns a new... | What does += mean in Python? | I see code like this for example in Python:
if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
What does the += mean?
| [
"a += b is essentially the same as a = a + b, except that:\n\n+ always returns a newly allocated object, but += should (but doesn't have to) modify the object in-place if it's mutable (e.g. list or dict, but int and str are immutable).\n\nIn a = a + b, a is evaluated twice.\n\nPython: Simple Statements\n\nA simple ... | [
77,
24,
7,
1,
0
] | [
"it means \"append \"THIS\" to the current value\"\nexample:\na = \"hello\";\na += \" world\";\nprinting a now will output: \"hello world\"\n"
] | [
-3
] | [
"python",
"syntax"
] | stackoverflow_0000823561_python_syntax.txt |
Q:
WxPython: FoldPanelBar not really folding
I've written the following code using FoldPanelBar:
import wx
import wx.lib.agw.foldpanelbar as fpb
class frame(wx.Frame):
def __init__(self,*args,**kwargs):
wx.Frame.__init__(self,*args,**kwargs)
self.text_ctrl_1=wx.TextCtrl(self,-1,style=wx.TE_MULTIL... | WxPython: FoldPanelBar not really folding | I've written the following code using FoldPanelBar:
import wx
import wx.lib.agw.foldpanelbar as fpb
class frame(wx.Frame):
def __init__(self,*args,**kwargs):
wx.Frame.__init__(self,*args,**kwargs)
self.text_ctrl_1=wx.TextCtrl(self,-1,style=wx.TE_MULTILINE)
self.fpb=fpb.FoldPanelBar(self,-1... | [
"This does what you want I think. I haven't tested multiple panels in the foldpanelbar, you might need to limit the size of the foldpanelbar explicitly to prevent it from getting too wide.\nimport wx\nimport wx.lib.agw.foldpanelbar as fpb\n\nclass frame(wx.Frame):\n def __init__(self, *args, **kwargs):\n ... | [
1
] | [] | [] | [
"python",
"sizer",
"wxpython"
] | stackoverflow_0000815589_python_sizer_wxpython.txt |
Q:
Python: finding uid/gid for a given username/groupname (for os.chown)
What's a good way to find the uid/gid for a given username or groupname using Python? I need to set file ownership with os.chown and need the integer ids instead of the alphabetic.
[Quick note]: getpwnam works great but is not available on windo... | Python: finding uid/gid for a given username/groupname (for os.chown) | What's a good way to find the uid/gid for a given username or groupname using Python? I need to set file ownership with os.chown and need the integer ids instead of the alphabetic.
[Quick note]: getpwnam works great but is not available on windows, so here's some code that creates stubs to allow you to run the same cod... | [
"Use the pwd and grp modules:\nfrom pwd import getpwnam \n\nprint getpwnam('someuser')[2]\n# or\nprint getpwnam('someuser').pw_uid\nprint grp.getgrnam('somegroup')[2]\n\n"
] | [
111
] | [] | [] | [
"python"
] | stackoverflow_0000826082_python.txt |
Q:
How to separate content from a file that is a container for binary and other forms of content
I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the c... | How to separate content from a file that is a container for binary and other forms of content | I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file (s... | [
"What you're looking at isn't \"binary\", it's uuencoded. Python's standard library includes the module uu, to handle uuencoded data.\nThe module uu requires the use of temporary files for encoding and decoding. You can accomplish this without resorting to temporary files by using Python's codecs module like this:\... | [
3,
2,
0
] | [] | [] | [
"binary",
"encoding",
"file",
"python",
"text"
] | stackoverflow_0000822161_binary_encoding_file_python_text.txt |
Q:
List Comprehensions and Conditions?
I am trying to see if I can make this code better using list comprehensions.
Lets say that I have the following lists:
a_list = [
'HELLO',
'FOO',
'FO1BAR',
'ROOBAR',
'SHOEBAR'
]
regex_list = [lambda x: re.search(r'FOO', x, re.IG... | List Comprehensions and Conditions? | I am trying to see if I can make this code better using list comprehensions.
Lets say that I have the following lists:
a_list = [
'HELLO',
'FOO',
'FO1BAR',
'ROOBAR',
'SHOEBAR'
]
regex_list = [lambda x: re.search(r'FOO', x, re.IGNORECASE),
lambda x: re.s... | [
"Sure, I think this should do it\nnewlist = [s for s in a_list if not any(r(s) for r in regex_list)]\n\nEDIT: on closer inspection, I notice that your example code actually adds to the new list each string in a_list that doesn't match all the regexes - and what's more, it adds each string once for each regex that i... | [
18,
0
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0000826407_list_list_comprehension_python.txt |
Q:
how to get the n-th record of a datastore query
Suppose that I have the model Foo in GAE and this query:
query = Foo.all().order('-key')
I want to get the n-th record. What is the most efficient way to achieve that?
Will the solution break if the ordering property is not unique, such as the one below:
query = Foo... | how to get the n-th record of a datastore query | Suppose that I have the model Foo in GAE and this query:
query = Foo.all().order('-key')
I want to get the n-th record. What is the most efficient way to achieve that?
Will the solution break if the ordering property is not unique, such as the one below:
query = Foo.all().order('-color')
edit: n > 1000
edit 2: I want ... | [
"There is no efficient way to do this - in any DBMS. In every case, you have to at least read sequentially through the index records until you find the nth one, then look up the corresponding data record. This is more or less what fetch(count, offset) does in GAE, with the additional limitation of 1000 records.\nA ... | [
3,
2
] | [] | [] | [
"custompaging",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0000826724_custompaging_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python interpreter with Linux Screen
I was working with Python with a Linux terminal screen. When I typed:
help(somefunction)
It printed the appropriate output, but then my screen was stuck, and at the bottom of the terminal was "(end)".
How do I get unstuck? Thanks in advance.
A:
The standard on GNU (or other... | Python interpreter with Linux Screen | I was working with Python with a Linux terminal screen. When I typed:
help(somefunction)
It printed the appropriate output, but then my screen was stuck, and at the bottom of the terminal was "(end)".
How do I get unstuck? Thanks in advance.
| [
"The standard on GNU (or other Unix-like) systems is to use the environment variable PAGER for the command that should receive output for viewing one screenful (\"page\") at a time.\nMine is set to:\n$ echo $PAGER\nless\n\nYours might be set to more, or a different command, or not set at all in which case a system-... | [
10,
5
] | [] | [] | [
"linux",
"python",
"terminal"
] | stackoverflow_0000827879_linux_python_terminal.txt |
Q:
Extract domain name from a host name
Is there a programatic way to find the domain name from a given hostname?
given -> www.yahoo.co.jp
return -> yahoo.co.jp
The approach that works but is very slow is:
split on "." and remove 1 group from the left, join and query an SOA record using dnspython
when a valid SOA re... | Extract domain name from a host name | Is there a programatic way to find the domain name from a given hostname?
given -> www.yahoo.co.jp
return -> yahoo.co.jp
The approach that works but is very slow is:
split on "." and remove 1 group from the left, join and query an SOA record using dnspython
when a valid SOA record is returned, consider that a domain
I... | [
"There's no trivial definition of which \"domain name\" is the parent of any particular \"host name\".\nYour current method of traversing up the tree until you see an SOA record is actually the most correct.\nTechnically, what you're doing there is finding a \"zone cut\", and in the vast majority of cases that will... | [
15,
4,
1
] | [] | [] | [
"dns",
"hostname",
"python"
] | stackoverflow_0000825694_dns_hostname_python.txt |
Q:
Why in the world does Tkinter break using canvas.create_image?
I've got a python GUI app in the workings, which I intend to use on both Windows and Mac. The documentation on Tkinter isn't the greatest, and google-fu has failed me.
In short, I'm doing:
c = Canvas(
master=frame,
width=settings.WINDOW_SIZE[0]... | Why in the world does Tkinter break using canvas.create_image? | I've got a python GUI app in the workings, which I intend to use on both Windows and Mac. The documentation on Tkinter isn't the greatest, and google-fu has failed me.
In short, I'm doing:
c = Canvas(
master=frame,
width=settings.WINDOW_SIZE[0],
height=settings.WINDOW_SIZE[1],
background=settings.CANVAS... | [
"Tk has two types of graphics, bitmap and image. Images come in two flavours, bitmap and photo. Bitmaps and Images of type bitmap are not the same thing, which leads to confusion in docs.\nPhotoImage creates an image of type photo, and needs an image object in the canvas, so the solution is, as you already conclude... | [
4,
2,
0
] | [] | [] | [
"python",
"python_imaging_library",
"tk_toolkit",
"tkinter"
] | stackoverflow_0000824988_python_python_imaging_library_tk_toolkit_tkinter.txt |
Q:
Python - Save the context
I need to save the context of the program before exiting ... I've put all the needed stuff to an object that I've previously created a I tried many times to picke it, but no way !!
I continuously have errors like :
PicklingError: Can't pickle 'SRE_Match' object: <_sre.SRE_Match object at... | Python - Save the context | I need to save the context of the program before exiting ... I've put all the needed stuff to an object that I've previously created a I tried many times to picke it, but no way !!
I continuously have errors like :
PicklingError: Can't pickle 'SRE_Match' object: <_sre.SRE_Match object at 0x2a969cd9c0>
OSError: [Errno ... | [
"See the python doc What can be pickled and unpickled. You have objects that can not be pickled.\n"
] | [
3
] | [] | [] | [
"pickle",
"python",
"serialization"
] | stackoverflow_0000828494_pickle_python_serialization.txt |
Q:
wxPython - Redrawing Error when replacing wxFrame's Panel
I'm creating a small wxPython utility for the first time, and I'm stuck on a problem.
I would like to add components to an already created frame. To do this, I am destroying the frame's old panel, and creating a new panel with all new components.
1: Is th... | wxPython - Redrawing Error when replacing wxFrame's Panel | I'm creating a small wxPython utility for the first time, and I'm stuck on a problem.
I would like to add components to an already created frame. To do this, I am destroying the frame's old panel, and creating a new panel with all new components.
1: Is there a better way of dynamically adding content to a panel?
2: W... | [
"1) I beleive the Sizer will let you insert elements into the existing ordering of them. That would probably be a bit faster.\n2) I don't see the behavior you're describing on OSX, but at a guess, try calling self.Layout() before self.Show() in layoutElements?\n",
"I had a similar problem where the panel would be... | [
1,
0
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0000561991_python_wxpython_wxwidgets.txt |
Q:
List a dictionary
In a list appending is possible. But how I achieve appending in dictionary?
Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT|00000004| |.data
__ctype_tab |00000000| ... | List a dictionary | In a list appending is possible. But how I achieve appending in dictionary?
Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT|00000004| |.data
__ctype_tab |00000000| r | OBJECT|... | [
"Appending doesn't make sense to the concept of dictionary in the same way as for list. Instead, it's more sensible to speak in terms of inserting and removing key/values, as there's no \"end\" to append to - the dict is unordered.\nFrom your desired output, it looks like you want to have a dict of dicts of dicts,... | [
7,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0000828578_dictionary_list_python.txt |
Q:
What is the proper procedure for offering a patch to the Python documentation?
I'm about to dive into the source code for the cgi.py module again because the MiniFieldStorage class is mentioned in the documentation, but not actually documented. It occurred to me that I have done this so many times that maybe I co... | What is the proper procedure for offering a patch to the Python documentation? | I'm about to dive into the source code for the cgi.py module again because the MiniFieldStorage class is mentioned in the documentation, but not actually documented. It occurred to me that I have done this so many times that maybe I could write documentation for it. If I did, how should I submit it?
| [
"There's a page regarding Documentation Development on the official web site which looks like a good starting point. It appears as though you simply add to the issue tracker and attach a patch in the normal way.\nIn particular, it points to Documenting Python, which appears to be a rather exhaustive guide on format... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0000829341_python.txt |
Q:
Controlling VirtualBox via COM from Python?
I'm trying to control latest Sun VirtualBox via it's COM interface from Python. But, unfortunately, the following code don't work:
import win32com.client
VBOX_GUID = "{B1A7A4F2-47B9-4A1E-82B2-07CCD5323C3F}"
try :
oVbox = win32com.client.Dispatch( VBOX_GUID )
oVbox.Fi... | Controlling VirtualBox via COM from Python? | I'm trying to control latest Sun VirtualBox via it's COM interface from Python. But, unfortunately, the following code don't work:
import win32com.client
VBOX_GUID = "{B1A7A4F2-47B9-4A1E-82B2-07CCD5323C3F}"
try :
oVbox = win32com.client.Dispatch( VBOX_GUID )
oVbox.FindMachine( "kubuntu" )
except Exception as oEx:
... | [
"The problem is that the object returned by FindMachine(\"kubuntu\") does not support the IDispatch interface, and win32com does not support that.\nYou could use my comtypes package http://starship.python.net/crew/theller/comtypes/ for that, but you need to patch the version in the repository to make it work with t... | [
3
] | [] | [] | [
"com",
"python",
"virtualbox"
] | stackoverflow_0000826494_com_python_virtualbox.txt |
Q:
Cocoa client/server application
Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application?
I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a... | Cocoa client/server application | Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application?
I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expect... | [
"If you have control of both the client and server, and you can limit the client to OS X only, I second Marc's answer. Cocoa's distributed objects are an amazing technology and make RPC-style client-server apps very easy.\nIf the requirements above are too restrictive for you, you still have many options available ... | [
6,
3,
1,
0
] | [
"Look at the api's for NSConnection and NSDownload to handle the network connection. The NSString class also has methods like + stringWithContentsOfURL:encoding:error: that may be useful.\nThen there is NSXMLParser and NSXMLDocument for reading xml data.\n"
] | [
-1
] | [
"client_server",
"cocoa",
"pyobjc",
"python",
"web_services"
] | stackoverflow_0000409354_client_server_cocoa_pyobjc_python_web_services.txt |
Q:
str.format() -> how to left-justify
>>> print 'there are {0:10} students and {1:10} teachers'.format(scnt, tcnt)
there are 100 students and 20 teachers
What would be the code so that the output became:
there are 100 students and 20 teachers
Thanks.
A:
print 'there are {0:<10} stud... | str.format() -> how to left-justify | >>> print 'there are {0:10} students and {1:10} teachers'.format(scnt, tcnt)
there are 100 students and 20 teachers
What would be the code so that the output became:
there are 100 students and 20 teachers
Thanks.
| [
"print 'there are {0:<10} students and {1:<10} teachers'.format(scnt, tcnt)\n\nWhile the old % operator uses - for alignment, the new format method uses < and >\n"
] | [
22
] | [] | [] | [
"python"
] | stackoverflow_0000829667_python.txt |
Q:
Django: custom constructor for form class, trouble with accessing data from request.POST
I have written custom constructor for a form, the whole form class looks like this:
class UploadForm(forms.Form):
file = forms.FileField(label = "Plik")
def __init__(self, coto, naglowek, *args, **kwargs):
sup... | Django: custom constructor for form class, trouble with accessing data from request.POST | I have written custom constructor for a form, the whole form class looks like this:
class UploadForm(forms.Form):
file = forms.FileField(label = "Plik")
def __init__(self, coto, naglowek, *args, **kwargs):
super(UploadForm, self).__init__(*args, **kwargs)
self.coto = coto
self.naglowek ... | [
"Your question is a mess. There's code and there's an edit with another question. The edit question has nothing to do with the title.\nPlease update this question to be your real question. \nIf you have multiple submit buttons, you must give them distinct names or values (or both). Here's our code which uses di... | [
2,
0,
0
] | [] | [] | [
"django",
"post",
"python",
"webforms"
] | stackoverflow_0000829156_django_post_python_webforms.txt |
Q:
Mosso Python Module
Has anybody had success installing the Mosso (cloudfiles) python module? I'm trying to install it and getting the following error.
python-cloudfiles-1.3.1]# python setup.py install
running install
running build
running build_py
running install_lib
byte-compiling /usr/lib/python2.3/site-package... | Mosso Python Module | Has anybody had success installing the Mosso (cloudfiles) python module? I'm trying to install it and getting the following error.
python-cloudfiles-1.3.1]# python setup.py install
running install
running build
running build_py
running install_lib
byte-compiling /usr/lib/python2.3/site-packages/cloudfiles/container.py... | [
"It looks like you're running a version of Python prior to 2.4 - the syntax it's complaining about (the @ symbol, known as a \"decorator\") was introduced in Python 2.4.\n"
] | [
5
] | [] | [] | [
"cloudfiles",
"module",
"mosso",
"python"
] | stackoverflow_0000829916_cloudfiles_module_mosso_python.txt |
Q:
crontab in python
I'm writing code in python for some sort of daemon that has to execute a specific action at a certain instance in time defined by a crontab string.
Is there a module I can use?
If not, can someone paste/link an algorithm I can use to check whether the instance of time defined by the crontab has o... | crontab in python | I'm writing code in python for some sort of daemon that has to execute a specific action at a certain instance in time defined by a crontab string.
Is there a module I can use?
If not, can someone paste/link an algorithm I can use to check whether the instance of time defined by the crontab has occured in the time from... | [
"sched ftw\n",
"Kronos is another option.\nHere is a similar SO question.\n",
"You might want to take a look at pycron.\n"
] | [
3,
1,
0
] | [] | [] | [
"crontab",
"python"
] | stackoverflow_0000826882_crontab_python.txt |
Q:
Is Python2.6 stable enough for production use?
Or should I just stick with Python2.5 for a bit longer?
A:
From python.org:
The current production versions are
Python 2.6.2 and Python 3.0.1.
So, yes.
Python 3.x contains some backwards incompatible changes, so python.org also says:
start with Python 2.6 since... | Is Python2.6 stable enough for production use? | Or should I just stick with Python2.5 for a bit longer?
| [
"From python.org:\n\nThe current production versions are\n Python 2.6.2 and Python 3.0.1.\n\nSo, yes.\nPython 3.x contains some backwards incompatible changes, so python.org also says:\n\nstart with Python 2.6 since more\n existing third party software is\n compatible with Python 2 than Python 3\n right now\n\n... | [
18,
10,
6,
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0000828862_python.txt |
Q:
Python double pointer
I'm trying to get the values from a pointer to a float array, but it returns as c_void_p in python
The C code
double v;
const void *data;
pa_stream_peek(s, &data, &length);
v = ((const float*) data)[length / sizeof(float) -1];
Python so far
import ctypes
null_ptr = ctypes.c_void_p()
pa_s... | Python double pointer | I'm trying to get the values from a pointer to a float array, but it returns as c_void_p in python
The C code
double v;
const void *data;
pa_stream_peek(s, &data, &length);
v = ((const float*) data)[length / sizeof(float) -1];
Python so far
import ctypes
null_ptr = ctypes.c_void_p()
pa_stream_peek(stream, null_ptr... | [
"My ctypes is rusty, but I believe you want POINTER(c_float) instead of c_void_p. \nSo try this:\nnull_ptr = POINTER(c_float)()\npa_stream_peek(stream, null_ptr, ctypes.c_ulong(length))\nnull_ptr[0]\nnull_ptr[5] # etc\n\n",
"To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice ... | [
3,
1,
0,
0
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0000828139_ctypes_python.txt |
Q:
Python Iterator Help + lxml
I have this script-
import lxml
from lxml.cssselect import CSSSelector
from lxml.etree import fromstring
from lxml.html import parse
website = parse('http://example.com').getroot()
selector = website.cssselect('.name')
for i in range(0,18):
print selector[i].text_content()
As ... | Python Iterator Help + lxml | I have this script-
import lxml
from lxml.cssselect import CSSSelector
from lxml.etree import fromstring
from lxml.html import parse
website = parse('http://example.com').getroot()
selector = website.cssselect('.name')
for i in range(0,18):
print selector[i].text_content()
As you can see the for loop stop... | [
"The CSSSelector.cssselect() method returns an iterable, so you can just do:\nfor element in selector:\n print element.text_content()\n\n",
"What about\nfor e in selector:\n print e.text_content()\n\n?\n",
"I would expect you want a for loop like:\nselectors = website.cssselect('.name , .name, .desc')\n\n... | [
5,
2,
2
] | [] | [] | [
"for_loop",
"iterator",
"lxml",
"python"
] | stackoverflow_0000830600_for_loop_iterator_lxml_python.txt |
Q:
Using Python multiprocessing while importing a module via file path
I'm writing a program which imports a module using a file path, with the function imp.load_source(module_name,module_path). It seems to cause a problem when I try to pass objects from this module into a Process.
An example:
import multiprocessing
... | Using Python multiprocessing while importing a module via file path | I'm writing a program which imports a module using a file path, with the function imp.load_source(module_name,module_path). It seems to cause a problem when I try to pass objects from this module into a Process.
An example:
import multiprocessing
import imp
class MyProcess(multiprocessing.Process):
def __init__(se... | [
"Probably it does not work because of placing of import code into main block.\nCode below works on Windows XP, Python 2.6. Then life module will also be imported in new process.\nimport multiprocessing\nimport imp\n\nclass MyProcess(multiprocessing.Process):\n def __init__(self,thing):\n multiprocessing.Process... | [
1
] | [
"test.py on any folder:\nimport multiprocessing\nimport imp\n\nclass MyProcess(multiprocessing.Process):\n def __init__(self,thing):\n multiprocessing.Process.__init__(self)\n self.thing=thing\n def run(self):\n print 'running...', self.thing()\n\n\nif __name__==\"__main__\":\n module=... | [
-1,
-1
] | [
"import",
"module",
"multiprocessing",
"python"
] | stackoverflow_0000829123_import_module_multiprocessing_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.