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:
"Practical Django Projects" - Search function
I am reading Chapter 3 of "Practical Django Projects", on how to make a CMS. I have improved the search function and everything works fine. However I am wondering why everythings works...
On page 35, I have added an admin.py file in the cms/search/ directory. How does ... | "Practical Django Projects" - Search function | I am reading Chapter 3 of "Practical Django Projects", on how to make a CMS. I have improved the search function and everything works fine. However I am wondering why everythings works...
On page 35, I have added an admin.py file in the cms/search/ directory. How does the compiler know that he needs to take this file i... | [
"If you are calling admin.autodiscover() in your urls.py Django's admin.site will be looking for admin.py files in all packages of your INSTALLED_APPS and import all found ModelAdmin classes and add them to the admin.site.\nYou have three inputs for SearchKeyword appearing in the admin because the there are three I... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005588081_django_python.txt |
Q:
Running generated nose tests
Suppose I define a testFile.py python module with as follows.
def test_evens():
for i in range(0, 5):
yield check_even, i, i*3
def check_even(n, nn):
assert n % 2 == 0 or nn % 2 == 0
When I let the nose identify the tests in collect-only mode I get
testFile.test_evens... | Running generated nose tests | Suppose I define a testFile.py python module with as follows.
def test_evens():
for i in range(0, 5):
yield check_even, i, i*3
def check_even(n, nn):
assert n % 2 == 0 or nn % 2 == 0
When I let the nose identify the tests in collect-only mode I get
testFile.test_evens(0, 0) ... ok
testFile.test_evens(... | [
"Nose cannot do this by default, to my knowledge. Here are some options:\n1. Fake it from the command line\nProbably not what you're looking for, but I had to mention it. You could also\ncreate a wrapper script to simplify this:\npython -c 'import testFile; testFile.check_even(2, 6)'\n\n2. Create a custom nose tes... | [
7
] | [] | [] | [
"nose",
"python"
] | stackoverflow_0005585670_nose_python.txt |
Q:
Django blog app architectural problem
I am creating little blog app. I want to return post, and (my problem), previous and next posts, so I can display them together with post. My current decision is very bad, because not only I load all Post objects, but also convert QuerySet to list. Here is a snippet from views... | Django blog app architectural problem | I am creating little blog app. I want to return post, and (my problem), previous and next posts, so I can display them together with post. My current decision is very bad, because not only I load all Post objects, but also convert QuerySet to list. Here is a snippet from views.py:
def post(request, url):
try:
... | [
"You don't have to implement fetching the next and previous instances yourself, it's already builtin: http://docs.djangoproject.com/en/1.3/ref/models/instances/#django.db.models.Model.get_previous_by_FOO\nIf you want to tweak this a bit, for example to get the neighboring instances for non-date fields, see this thr... | [
2
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0005588179_django_django_views_python.txt |
Q:
Extracting XML nodes in Python
This is part of an XML document that I have:
<tr><td>Image:</td><td>
<a href="http://live.astrometry.net/status.php?job=alpha-201104-6758393&get=fullsize.png">fullsize.png</a></td></tr>
I need to extract the href attribute "of the <a> element after the <td> element with content ... | Extracting XML nodes in Python | This is part of an XML document that I have:
<tr><td>Image:</td><td>
<a href="http://live.astrometry.net/status.php?job=alpha-201104-6758393&get=fullsize.png">fullsize.png</a></td></tr>
I need to extract the href attribute "of the <a> element after the <td> element with content 'Image:'". The <a> element has no ot... | [
"OK, the final elegant (I hope ;) answer with a single XPath expression\nfrom lxml import etree\nroot = etree.fromstring(your_text)\nprint root.xpath(\"//td[contains(text(), 'Image')]/following-sibling::td/a/@href\")[0]\n\n",
"If your input file is just like your excerpt, the following code may help you:\nfrom xm... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0005587816_python_xml.txt |
Q:
mpi4py with processes and threads
Hi This is a pretty specific question, so I hope StackOverflow is meant for all programming languages and not just javascript/html
I am writing a multi program in MPICH2 (popular message passing interface). My program is written in Python so I use the MPI4Py Python bindings. MPI i... | mpi4py with processes and threads | Hi This is a pretty specific question, so I hope StackOverflow is meant for all programming languages and not just javascript/html
I am writing a multi program in MPICH2 (popular message passing interface). My program is written in Python so I use the MPI4Py Python bindings. MPI is best for situations with no shared me... | [
"If you need threads, python may not be your best option due to the Global Interpreter Lock which prevents true concurrency. See also Dave Beazly's disturbing talk.\nYou might be better off just running 20 processes to keep your 4 cores and 5 nodes busy, and just use MPI for all communication.\nPython incurs a lot... | [
5
] | [] | [] | [
"mpi",
"multithreading",
"python"
] | stackoverflow_0005588505_mpi_multithreading_python.txt |
Q:
django south broke my db (can't drop constraint)
I wanted to add a table and a foreign key to that table. Initially I had:
class VirtualMachine(models.Model):
...
I then changed that to:
class OperatingSystem(models.Model):
name = models.CharField(max_length=40)
def __unicode__(self):
return ... | django south broke my db (can't drop constraint) | I wanted to add a table and a foreign key to that table. Initially I had:
class VirtualMachine(models.Model):
...
I then changed that to:
class OperatingSystem(models.Model):
name = models.CharField(max_length=40)
def __unicode__(self):
return self.name
class VirtualMachine(models.Model):
ope... | [
"Ah I think the table got locked or something. I restarted postgres and then could do stuff manually to the table and rescue it.\n"
] | [
2
] | [] | [] | [
"database",
"django",
"django_south",
"postgresql",
"python"
] | stackoverflow_0005588895_database_django_django_south_postgresql_python.txt |
Q:
Control Selection Border in PyQT
this is my first post here , I am trying to achive something in pyqt , I have a control placed in a widget and when user is selecting that control , i need a selection border something similer pyqt designer has , I am attching a image for refrenct .
Anybody has any idea how I can a... | Control Selection Border in PyQT | this is my first post here , I am trying to achive something in pyqt , I have a control placed in a widget and when user is selecting that control , i need a selection border something similer pyqt designer has , I am attching a image for refrenct .
Anybody has any idea how I can aachive this with pyqt ?
Thanks
| [
"I'm pretty sure the general method would be as follows:\n\nCreate a QFrame that will serve as a wrapper; pass it the widget you wish to 'select'\nPlace the wrapped widget in a layout; this will be the QFrame widget's layout.\nOverload the functions for a mouse double-click event and a paint event, so that on selec... | [
1
] | [] | [] | [
"pyqt4",
"python",
"widget"
] | stackoverflow_0005373922_pyqt4_python_widget.txt |
Q:
python & android and googlemaps
I'm making a game depending on android and python (client and server ) and i neeed the client to choose a place too play in it from google maps and send the x & y cordinnates to the python then python add points to the areaa the client will play in .. soo how can i do this in python... | python & android and googlemaps | I'm making a game depending on android and python (client and server ) and i neeed the client to choose a place too play in it from google maps and send the x & y cordinnates to the python then python add points to the areaa the client will play in .. soo how can i do this in python and thank in advance
| [
"The easiest option is probably to have the python server side of things send the coordinates back to the Android app in its response and then the android app can manipulate the map as needed.\n"
] | [
1
] | [] | [] | [
"android",
"google_maps",
"python"
] | stackoverflow_0005588728_android_google_maps_python.txt |
Q:
Distinguishing between GET and POST data in CherryPy?
I've been deciding between Python web frameworks for a project of mine and I've really liked how lightweight, flexible, and concise CherryPy is compared to others. The only problem I'm having is I can't find any documentation on how to distinguish between data ... | Distinguishing between GET and POST data in CherryPy? | I've been deciding between Python web frameworks for a project of mine and I've really liked how lightweight, flexible, and concise CherryPy is compared to others. The only problem I'm having is I can't find any documentation on how to distinguish between data sent via GET and via POST.
For example, I don't want users ... | [
"See the docs.\n\nA string containing the HTTP method, such as \"GET\" or \"POST\". Set\n in the \"run\" phase.\n\nlooks like checking cherrypy.request.method is what you want to do.\n"
] | [
9
] | [] | [] | [
"cherrypy",
"python",
"web_frameworks"
] | stackoverflow_0005588887_cherrypy_python_web_frameworks.txt |
Q:
How do I use wild cards in python as specified in a text file
Hello I'm new to python and I'd like to know how to process a .txt file line by line to copy files specifid as wild cards
basically the .txt file looks like this.
bin/
bin/*.txt
bin/*.exe
obj/*.obj
document
binaries
so now with that information I'd li... | How do I use wild cards in python as specified in a text file | Hello I'm new to python and I'd like to know how to process a .txt file line by line to copy files specifid as wild cards
basically the .txt file looks like this.
bin/
bin/*.txt
bin/*.exe
obj/*.obj
document
binaries
so now with that information I'd like to be able to read my .txt file match the directory copy all the... | [
"Here's something to start with...\nimport glob # For specifying pathnames with wildcards\nimport shutil # For doing common \"shell-like\" operations.\nimport os # For dealing with pathnames\n\n# Grab all the pathnames of all the files matching those specified in `text_file.txt`\nmatching_pathnames = []\nfor line i... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005589031_python.txt |
Q:
Does web2py have these?
I am finishing up a project in PHP with Yii and phing. Even though Yii is the best web framework I've used to date, I prefer writing Python over PHP. So, I've been looking at web2py and have some questions:
Does web2py provide Javascript form validation? Yii has http://www.yiiframework.... | Does web2py have these? | I am finishing up a project in PHP with Yii and phing. Even though Yii is the best web framework I've used to date, I prefer writing Python over PHP. So, I've been looking at web2py and have some questions:
Does web2py provide Javascript form validation? Yii has http://www.yiiframework.com/extension/jformvalidate/
... | [
"\nDoes web2py provide Javascript form validation? \n\nOut of the box web2py does server-side validation, client side js pre-validation of int, double and calendar popup for date/time/datetime. There are jQuery plugins to add more client-side validation. web2py is mostly serverside, not clientside.\n\nDoes web2py h... | [
13
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0005589230_python_web2py.txt |
Q:
Editing all text in childNodes of XML file with Python
I'm trying to edit the text inside of all of the tags named "Volume" in an XML file by multiplying that text by a number entered by the user. The text inside of the "Volume" tag will always be a number. My code works so far, but only on the first instance of t... | Editing all text in childNodes of XML file with Python | I'm trying to edit the text inside of all of the tags named "Volume" in an XML file by multiplying that text by a number entered by the user. The text inside of the "Volume" tag will always be a number. My code works so far, but only on the first instance of the "Volume" text.
Here's an example of the XML:
<bl... | [
"You'll be much happier if you use a more modern XML API, like ElementTree (in the standard library) or lxml (more advanced).\nIn ElementTree or lxml you get access to XPath (or something close), which allows for a much more flexible syntax in finding elements and attributes in XML documents.\nIn ElementTree:\nvolu... | [
2
] | [] | [] | [
"edit",
"python",
"text",
"xml"
] | stackoverflow_0005587644_edit_python_text_xml.txt |
Q:
Python list + list vs. list.append()
Today I spent about 20 minutes trying to figure out why
this worked as expected:
users_stories_dict[a] = s + [b]
but this would have a None value:
users_stories_dict[a] = s.append(b)
Anyone know why the append function does not return the new list? I'm looking for some sor... | Python list + list vs. list.append() | Today I spent about 20 minutes trying to figure out why
this worked as expected:
users_stories_dict[a] = s + [b]
but this would have a None value:
users_stories_dict[a] = s.append(b)
Anyone know why the append function does not return the new list? I'm looking for some sort of sensible reason this decision was mad... | [
"append works by actually modifying a list, and so all the magic is in side-effects. Accordingly, the result returned by append is None. In other words, what one wants is: \ns.append(b)\nand then: \nusers_stories_dict[a] = s\nBut, you've already figured that much out. As to why it was done this way, while I don't r... | [
12,
9
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005589549_list_python.txt |
Q:
Python: Parse wordpress HTML
I am trying to build a blog-mapping site, which would spot the current trends in a given set of blogs. For convenience, I'm going to focus on a given list of Wordpress blogs.
Is there a Python package for parsing Wordpress HTML?
I'm looking for:
Identification (Is the given HTML a Wor... | Python: Parse wordpress HTML | I am trying to build a blog-mapping site, which would spot the current trends in a given set of blogs. For convenience, I'm going to focus on a given list of Wordpress blogs.
Is there a Python package for parsing Wordpress HTML?
I'm looking for:
Identification (Is the given HTML a Wordpress blog)
Blog properties (name... | [
"As I know, there are not any parsing libraries that parse WordPress HTML specially, but general-purpose HTML parsing libraries such as html5lib, BeautifulSoup.\nI recommend you html5lib+lxml.html.\n"
] | [
3
] | [] | [] | [
"python",
"wordpress"
] | stackoverflow_0005587700_python_wordpress.txt |
Q:
How to calculate lines of code, comments and docstrings for a Python module?
Is there a tool or snippet that produces the following output in some form:
lines_of_code = 98
lines_of_comments = 24
lines_of_documentation = 11
NOTE 1: I will then try to feed this data to Jenkins to graph.
NOTE 2: I am aware that CLOC... | How to calculate lines of code, comments and docstrings for a Python module? | Is there a tool or snippet that produces the following output in some form:
lines_of_code = 98
lines_of_comments = 24
lines_of_documentation = 11
NOTE 1: I will then try to feed this data to Jenkins to graph.
NOTE 2: I am aware that CLOC counts comments but I would like to separately count comments and docstrings.
| [
"Look at PyLint: http://www.logilab.org/857\n"
] | [
3
] | [] | [] | [
"lines_of_code",
"python",
"static_analysis"
] | stackoverflow_0005590286_lines_of_code_python_static_analysis.txt |
Q:
Why is the first line longer?
i'm using python to read a txt document with:
f = open(path,"r")
for line in f:
line = line.decode('utf8').strip()
length = len(line)
firstLetter = line[:1]
it seems to work, but the first line's length is always longer by... 1
for example:
the first line is "XXXX" where ... | Why is the first line longer? | i'm using python to read a txt document with:
f = open(path,"r")
for line in f:
line = line.decode('utf8').strip()
length = len(line)
firstLetter = line[:1]
it seems to work, but the first line's length is always longer by... 1
for example:
the first line is "XXXX" where X denotes a chinese character
then ... | [
"You are probably getting the Byte Order Mark (BOM) as the first character on the first line.\nInformation about dealing with it is here\n",
"You have a UTF-8 BOM at the start of your file. Don't faff about inspecting the first character. Instead of the utf8 encoding, use the utf_8_sig encoding with either codecs... | [
5,
5
] | [] | [] | [
"python",
"text_files"
] | stackoverflow_0005590103_python_text_files.txt |
Q:
Emulating the list.insert() method as a subclass of Python's list
I'm trying to build a class that inherits methods from Python's list, but also does some additional things on top... it's probably easier just to show code at this point...
class Host(object):
"""Emulate a virtual host attached to a physical int... | Emulating the list.insert() method as a subclass of Python's list | I'm trying to build a class that inherits methods from Python's list, but also does some additional things on top... it's probably easier just to show code at this point...
class Host(object):
"""Emulate a virtual host attached to a physical interface"""
def __init__(self):
# Insert class properties here...... | [
"If you can possibly avoid it, don't inherit from builtin classes. (You can, but that doesn't mean you should without a really compelling reason)\nThose classes are optimised for speed, and that makes inheriting from them correctly quite tedious, since you end up having to override almost everything.\nInheriting fr... | [
7,
6,
3,
0
] | [] | [] | [
"list",
"python",
"subclassing"
] | stackoverflow_0005586533_list_python_subclassing.txt |
Q:
Issue with wxPython mulltiline text box being too large for wx.Frame - can I auto "shrink" to the correct size of the text box?
Not sure if I am asking this correctly (e.g. using widget/object in the correct context). This code is meant just as an experiment (learning about classes and wxPython right now) - so it... | Issue with wxPython mulltiline text box being too large for wx.Frame - can I auto "shrink" to the correct size of the text box? | Not sure if I am asking this correctly (e.g. using widget/object in the correct context). This code is meant just as an experiment (learning about classes and wxPython right now) - so it might not make sense as functional code.
Problem: I have a window/frame that I am allowing the user to specify width/height, and th... | [
"Jake pointed you in a right direction, but there is one more thing. You should be aware that first object which goes into the frame is wrapped into the basic sizer. The problem is that as far as I know you have no control of this sizer. So you have to add your own sizer, which you can use for frame fitting. You ne... | [
2,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005590176_python_wxpython.txt |
Q:
Django custom field with multiple inheritance
I have two custom Django fields, a JSONField and a CompressedField, both of which work well. I would like to also have a CompressedJSONField, and I was rather hoping I could do this:
class CompressedJSONField(JSONField, CompressedField):
pass
but on import I get:... | Django custom field with multiple inheritance | I have two custom Django fields, a JSONField and a CompressedField, both of which work well. I would like to also have a CompressedJSONField, and I was rather hoping I could do this:
class CompressedJSONField(JSONField, CompressedField):
pass
but on import I get:
RuntimeError: maximum recursion depth exceeded whi... | [
"after doing a few quick tests i found that if you remove the metaclass from the JSON and compressed fields and put it in the compressedJSON field it compiles. if you then need the JSON or Compressed fields then subclass them and jusst add the __metaclass__ = models.SubfieldBase\ni have to admit that i didn't do an... | [
3
] | [
"It is hard to understand when exactly you are getting that error. But looking at DJango code, there is simlar implementation (multiple inheritance) \nrefer: class ImageFieldFile(ImageFile, FieldFile) \nin django/db/models/fields\n"
] | [
-2
] | [
"custom_fields",
"django",
"multiple_inheritance",
"python"
] | stackoverflow_0005524241_custom_fields_django_multiple_inheritance_python.txt |
Q:
PHP Webserver in Python
How can I make a PHP 5.3 webserver using Python?
I know how to make a simple HTTP server, but how can I include PHP?
Thanks.
A:
Do you perhaps mean writing your own implementation of a PHP module for your own webserver? eg, writing something like mod_php but in python for your own home r... | PHP Webserver in Python | How can I make a PHP 5.3 webserver using Python?
I know how to make a simple HTTP server, but how can I include PHP?
Thanks.
| [
"Do you perhaps mean writing your own implementation of a PHP module for your own webserver? eg, writing something like mod_php but in python for your own home rolled web server? You would have to have a mighty good reason for pursuing that...check out LAMP maybe that will do what you need\n"
] | [
0
] | [
"After some clarifications at last it came clear that your question was\n\"how to connect PHP to HTTP server\"\nSo, actually you were interested in three letters: CGI.\nHowever I still doubt you will get any good from it. \n"
] | [
-3
] | [
"php",
"python"
] | stackoverflow_0005591230_php_python.txt |
Q:
Switching scenes with pyglet
Can anybody recommend how to switch between scenes in pyglet.
I.e.
menu > game
game > menu
menu > help
ect
The only way that i can think to do it off the top of my head is by using different windows, which i am quite sure would be the complete wrong way to do it. Or by overloading ... | Switching scenes with pyglet | Can anybody recommend how to switch between scenes in pyglet.
I.e.
menu > game
game > menu
menu > help
ect
The only way that i can think to do it off the top of my head is by using different windows, which i am quite sure would be the complete wrong way to do it. Or by overloading all of the window's event function... | [
"Here is a rough schematic of a class structure that might work for you:\nclass Game(object):\n \"This class contains the Scene which is the current scene the user is look ing at.\"\n def __init__(self):\n self.current_level = 0\n self.current_screen = MainMenu(self)\n\n def load(self):\n ... | [
2,
2,
1,
0
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0005581447_pyglet_python.txt |
Q:
Scheme-less database solution to work on one machine only?
I am looking for a scheme-less database to store roughly 10[TB] of data on disk, ideally, using a python client. The suggested solution should be free for commercial use, and have good performance for reads and writes.
The main goal here is to store time-s... | Scheme-less database solution to work on one machine only? | I am looking for a scheme-less database to store roughly 10[TB] of data on disk, ideally, using a python client. The suggested solution should be free for commercial use, and have good performance for reads and writes.
The main goal here is to store time-series data, including more than billion records, accessed by tim... | [
"MongoDB is likely a good choice related to performance, flexibility and usability (easy approachable). However large databases require careful planning - especially when it comes to aspects of backup and high-availability. Without further insight about project requirements there is little to say if one machine is ... | [
4,
3,
2,
1
] | [] | [] | [
"database",
"linux",
"mongodb",
"nosql",
"python"
] | stackoverflow_0005590148_database_linux_mongodb_nosql_python.txt |
Q:
Calling python code(.py files) from C#
I have some python code that does a certain task. I need to call this code from C# without converting the python file as an .exe, since the whole application is built on C#.
How can I do this?
A:
If your python code can be executed via IronPython then this is definitely th... | Calling python code(.py files) from C# | I have some python code that does a certain task. I need to call this code from C# without converting the python file as an .exe, since the whole application is built on C#.
How can I do this?
| [
"If your python code can be executed via IronPython then this is definitely the way to go - it offers the best interop and means that you will be able to use .Net objects in your scripts. \nThere are many ways to invoke IronPython scripts from C# ranging from compiling the script up as an executable to executing a ... | [
6,
5,
1
] | [] | [] | [
".net",
"c#",
"python",
"python.net"
] | stackoverflow_0005591557_.net_c#_python_python.net.txt |
Q:
Try/catch or validation for speed?
I'm working with Python and whenever I've had to validate function input, I assumed that the input worked, and then caught errors.
In my case, I had a universal Vector() class which I used for a few different things, one of which is addition. It functioned both as a Color() class... | Try/catch or validation for speed? | I'm working with Python and whenever I've had to validate function input, I assumed that the input worked, and then caught errors.
In my case, I had a universal Vector() class which I used for a few different things, one of which is addition. It functioned both as a Color() class and as a Vector(), so when I add a scal... | [
"I upvoted Matt Joiner's answer, but wanted to include some additional observations to make it clear that, along with a couple of other factors, there are 4 times that matter when choosing between pre-checking conditions (known as LBYL or \"Look Before You Leap\") and just handling exceptions (known as EAFP or \"Ea... | [
83,
6
] | [] | [] | [
"exception_handling",
"performance",
"python",
"typechecking"
] | stackoverflow_0005589532_exception_handling_performance_python_typechecking.txt |
Q:
python invalid literal error
so I have this code
data = input()
m = data.split(',')
for i in range(0, len(m)):
print(int(m[i]) )
but then when i run it and type in "1,2,3", i get this error:
print(int(m[i]))
ValueError: invalid literal for int() with base 10: '"1'
what did i do wrong?
using python 3
... | python invalid literal error | so I have this code
data = input()
m = data.split(',')
for i in range(0, len(m)):
print(int(m[i]) )
but then when i run it and type in "1,2,3", i get this error:
print(int(m[i]))
ValueError: invalid literal for int() with base 10: '"1'
what did i do wrong?
using python 3
| [
"As you have your code, the input you type in should be numbers separated by commas. You do not have to include the quotes, just type 1,2,3 and nothing else. You only need the quotes only if you are writing actual code writing string literals. In this case, you are just taking input and it will already be string... | [
4,
0,
0,
0
] | [] | [] | [
"input",
"python"
] | stackoverflow_0005320939_input_python.txt |
Q:
Best practice for maintaining the order of a subset of records
I am trying to implement a playlist, and right now I come up with these tables:
playlist
id
title
creator
playlist_item
id
item_id
playlist_id
position
item
id
title
When I try to write Playlist.... | Best practice for maintaining the order of a subset of records | I am trying to implement a playlist, and right now I come up with these tables:
playlist
id
title
creator
playlist_item
id
item_id
playlist_id
position
item
id
title
When I try to write Playlist.add_song, I found it hard to maintain the order of items with positi... | [
"I remember doing the same thing for an mp3 player i wrote some years ago. The problem is not just setting a new position, but also updating positions if a playlist item is deleted (one that was in the middle, for instance, then all below must be updated).\nSince a good implementation commands that your positions a... | [
0
] | [] | [] | [
"database",
"mysql",
"python"
] | stackoverflow_0005591998_database_mysql_python.txt |
Q:
How can i parse/scrape/crawl sites for specific information?
Ive recently been charged with a task that blows my mind. My club wants to go through sites and find people who are doing what we are.
The method in use currently is go to wikipedia, get the list of every city (eg: List of cities in alabama ), go each of... | How can i parse/scrape/crawl sites for specific information? | Ive recently been charged with a task that blows my mind. My club wants to go through sites and find people who are doing what we are.
The method in use currently is go to wikipedia, get the list of every city (eg: List of cities in alabama ), go each of the sites (eg: meetup, facebook, craigslist, etc.), then execute ... | [
"I wouldn't create a real web crawler for something as simple as this. I think what would suffice is to:\n\nGet list of cities in a file, say cities.txt (doable manually or figure something out)\nFigure out what URL patterns are used to search from the sites you want.\nWrite a shell script that makes all the search... | [
1
] | [] | [] | [
"parsing",
"python",
"web_crawler",
"wget"
] | stackoverflow_0005590360_parsing_python_web_crawler_wget.txt |
Q:
Joining a list of python objects with __str__ method
I've already looked at this question on representing strings in Python but my question is slightly different.
Here's the code:
>>> class WeirdThing(object):
... def __init__(self):
... self.me = time.time()
... def __str__(self):
... retu... | Joining a list of python objects with __str__ method | I've already looked at this question on representing strings in Python but my question is slightly different.
Here's the code:
>>> class WeirdThing(object):
... def __init__(self):
... self.me = time.time()
... def __str__(self):
... return "%s" % self.me
... def __repr__(self):
... ... | [
"You have to stringify your objects before you can join them. This is because str.join expects a series of strings, and you must give it a series of strings.\nFor the sake of less typing at the cost of readability, you can do \"\\n\".join(map(str, list_of_things).\n",
"There are probably no amazing way.\ndef strj... | [
13,
3,
3,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0005588685_python_string.txt |
Q:
Help choosing between reload or subprocess
Hello i want to know the best way to re import or re execute a module, because i have a web server with just one Apache session for all my domains and applications, and i if i need to make some changes on one application restart the server will affect the others, so looki... | Help choosing between reload or subprocess | Hello i want to know the best way to re import or re execute a module, because i have a web server with just one Apache session for all my domains and applications, and i if i need to make some changes on one application restart the server will affect the others, so looking for the best way to recall a module. If i cho... | [
"Reloading a module is rarely a good idea in a production environment; it's a mechanism intended for debugging. When you reload a module, the module's contents (classes, function, data) get replaced, but existing references to these items from other modules are not affected. This is particularly important for class... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0005590396_python_python_3.x.txt |
Q:
numpy array subclass unexpedly shares attributes across instances
I am having a weird subclass numpy.ndarray issue that feels like
Values of instance variables of superclass persist across instances of subclass
But I have not been able to understand fully or make it work for for my example.
Reading through
Slig... | numpy array subclass unexpedly shares attributes across instances | I am having a weird subclass numpy.ndarray issue that feels like
Values of instance variables of superclass persist across instances of subclass
But I have not been able to understand fully or make it work for for my example.
Reading through
Slightly more realistic example - attribute added to existing array I am tr... | [
"The problem is here:\ndef __new__(cls, input_array, attrs={})\n\nNever do this attrs={} in a function header. The expected result is (probably) not what you think it is. This is a common Python Pitfall. See here Default Parameter Values in Python\nThe right way how to do this:\ndef __new__(cls, input_array, attrs=... | [
17
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0005587582_numpy_python.txt |
Q:
How to bring back library functions which have been deleted?
Suppose I do this
import cmath
del cmath
cmath.sqrt(-1)
I get this
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cmath' is not defined
But when I import cmath again, I am able to use sqrt again
import cmath
c... | How to bring back library functions which have been deleted? | Suppose I do this
import cmath
del cmath
cmath.sqrt(-1)
I get this
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cmath' is not defined
But when I import cmath again, I am able to use sqrt again
import cmath
cmath.sqrt(-1)
1j
But when I do the following
import cmath
del cma... | [
"You'd need reload\nreload(cmath)\n\n... will reload definitions from the module.\nimport cmath\ndel cmath.sqrt\nreload(cmath)\ncmath.sqrt(-1)\n\n... will correctly print ..\n1j\n\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0005592384_python.txt |
Q:
How to set value of hidden form in Mechanize/Python?
I'm scraping a site that uses a hidden form as a means of a countermeasure against exactly what I'm trying to do. This form:
<input style="width: 2px; height: 25px" type="hidden" size="1" name="TestJavaScript" />
is the culprit. The form expects that this inpu... | How to set value of hidden form in Mechanize/Python? | I'm scraping a site that uses a hidden form as a means of a countermeasure against exactly what I'm trying to do. This form:
<input style="width: 2px; height: 25px" type="hidden" size="1" name="TestJavaScript" />
is the culprit. The form expects that this input's value will be set to "OK" by some JavaScript that exec... | [
"As posted elsewhere (namely on the mechanize library's FAQ page):\nform.find_control(\"foo\").readonly = False # allow changing .value of control foo \nform.set_all_readonly(False) # allow changing the .value of all controls\n\n"
] | [
28
] | [] | [] | [
"mechanize",
"python",
"screen_scraping"
] | stackoverflow_0005592088_mechanize_python_screen_scraping.txt |
Q:
why do closeEvent and destroyed slot not get called on accepting PyQt4 QDialog?
All in the question title, and my simplified code below.
According to the docs:
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdialog.html#done
on clicking Ok, it should close and indeed if I close it using the window clo... | why do closeEvent and destroyed slot not get called on accepting PyQt4 QDialog? | All in the question title, and my simplified code below.
According to the docs:
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdialog.html#done
on clicking Ok, it should close and indeed if I close it using the window close button, it fires the event:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
... | [
"The answer came from http://www.riverbankcomputing.com/pipermail/pyqt/2011-April/029589.html\nwith many thanks to Hans-Peter Jansen\n\nDon't hook handler for destroyed signal onto the object being destroyed.(seems obvious in retrospect)\nQDialog.accept() does not fire closeEvent, even though it does get destroyed ... | [
3,
1
] | [] | [] | [
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0005570402_pyqt4_python_qt_qt4.txt |
Q:
How to run php in an HTML file running python?
I get an "unhandled exception" every time I try to run this standard include in an html file running python:
<?php
//add header with tabs
include('includes/templates/common/tpl_header.php');
?>
I'm trying to run it right under the body tag that looks like this:
<body... | How to run php in an HTML file running python? | I get an "unhandled exception" every time I try to run this standard include in an html file running python:
<?php
//add header with tabs
include('includes/templates/common/tpl_header.php');
?>
I'm trying to run it right under the body tag that looks like this:
<body py:match="body" py:attrs="h.append_class_attr(attrs... | [
"HTML is HTML, Python is Python and PHP is PHP.\nIt's THREE different technologies, which cannot be mixed.\nYou can't \"run standard PHP include\" in HTML file.\nYou can't \"run standard PHP include\" in Python file.\nYou can run PHP code in PHP file only. \nYou can't run Python code in HTML file. You can run Pyt... | [
0,
0
] | [] | [] | [
"include",
"php",
"python"
] | stackoverflow_0005590717_include_php_python.txt |
Q:
Return type of numpy.minimum()?
When I use the numpy functions minimum() and maximum() on boolean arrays, the type of the result prints as numpy.int32. However, a comparison with the numpy.int32 type fails (even after a cast). Is this a bug?
g = np.ones((5, 5), dtype = np.bool)
h = np.maximum(g, 4)
i = np.int32(h)... | Return type of numpy.minimum()? | When I use the numpy functions minimum() and maximum() on boolean arrays, the type of the result prints as numpy.int32. However, a comparison with the numpy.int32 type fails (even after a cast). Is this a bug?
g = np.ones((5, 5), dtype = np.bool)
h = np.maximum(g, 4)
i = np.int32(h)
print 'type of g ', g.dtype.type ... | [
"Seems normal enough to me. Using np.maximum returns the maximum of g and 4, which is 4 (True == 1). You get a matrix full of fours, which is integer type.\nIf you use this syntax for your type comparisons, they work: h.dtype.type == np.dtype(np.int32) or more simply h.dtype == np.int32.\n",
"The return type is a... | [
3,
2,
1,
1,
0
] | [] | [] | [
"int32",
"numpy",
"python",
"types"
] | stackoverflow_0005582760_int32_numpy_python_types.txt |
Q:
Extract incoming mail attachment
I would like to extract incoming mail's attachment using bash or python or any script.
Anyone has experience on such ?
Thank you.
A:
I think that Python's email module can parse and extract attachments from messages as you want.
A:
You are very vague about how the mails are inc... | Extract incoming mail attachment | I would like to extract incoming mail's attachment using bash or python or any script.
Anyone has experience on such ?
Thank you.
| [
"I think that Python's email module can parse and extract attachments from messages as you want.\n",
"You are very vague about how the mails are incoming, if it's even relevant that they are incoming, what format they are in, how you want to identify the attachments to extract, when you want to extract them (ie. ... | [
3,
1
] | [] | [] | [
"bash",
"email",
"python"
] | stackoverflow_0005590271_bash_email_python.txt |
Q:
oauth google using python
i am fairly new to programming for web. and i want to start from scratch here.
i tried to search the net but ended up completely confused.
now what i want to learn is how to authenticate a google account through a python script.
can anyone please provide me with a code fragment or any ex... | oauth google using python | i am fairly new to programming for web. and i want to start from scratch here.
i tried to search the net but ended up completely confused.
now what i want to learn is how to authenticate a google account through a python script.
can anyone please provide me with a code fragment or any example.
thanks a lot in advance.... | [
"I spent a whole day on coding this, after several failed attempts over the past few weeks. This only gets you as far as the first step, but it does so without any external libraries. And yes, I know it's close to two years after the OP, but from what I could see it still needed to be done.\n\n#!/usr/bin/python\n'd... | [
19,
3,
1,
0,
0
] | [] | [] | [
"oauth",
"python"
] | stackoverflow_0001215033_oauth_python.txt |
Q:
Python Subprocess can not get the output of oracle command "imp"
For example:
import subprocess
p=subprocess.Popen("imp -help",stdout=subprocess.PIPE,stdin=subprocess.PIPE)
out,err=p.communicate
the out is null
but other oracle command like "sqlplus -help","rman -help" works fine
A:
There could be two problems... | Python Subprocess can not get the output of oracle command "imp" | For example:
import subprocess
p=subprocess.Popen("imp -help",stdout=subprocess.PIPE,stdin=subprocess.PIPE)
out,err=p.communicate
the out is null
but other oracle command like "sqlplus -help","rman -help" works fine
| [
"There could be two problems why you are not getting any output in stdout:\n\nThe process is dumping all it's output to stderr.\nThe system does not know how to execute \"imp -help\".\n\nThe solution for the first problem is easy: capture stderr using the argument stderr = subprocess.PIPE.\nThe solution to the seco... | [
1
] | [] | [] | [
"oracle",
"python"
] | stackoverflow_0005593002_oracle_python.txt |
Q:
How do you implement __delitem__ when subclassing collections.MutableSequence?
Using Alex Martelli's guidance to use collections.MutableSequence instead of subclassing list() (using Python 2.6.6)
Alex suggested using
class HostList(collections.MutableSequence):
"""A container for manipulating lists of hosts"""... | How do you implement __delitem__ when subclassing collections.MutableSequence? | Using Alex Martelli's guidance to use collections.MutableSequence instead of subclassing list() (using Python 2.6.6)
Alex suggested using
class HostList(collections.MutableSequence):
"""A container for manipulating lists of hosts"""
def __init__(self):
"""Initialize the class"""
self.list = list... | [
"del ii, del(ii) : you are deleting the name ii from the scope of the function __delitem__, not the list (see: del)\nIf ii is an item in the list, you can use: self.list.remove(ii);\nIf ii is an index of an item in the list, you can use: self.list.remove(self.list[ii])\nUpdate\nOr as @Thomas Wouters said, its bette... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0005593475_python.txt |
Q:
Use Django User-Model or create a own Model?
I'm currently designing a Django based site. For simplicity lets assume that it is a simple community site where users can log in and write messages to other users.
My current choice is wether to use the buildin User-Model or to build something my own. I don't need much... | Use Django User-Model or create a own Model? | I'm currently designing a Django based site. For simplicity lets assume that it is a simple community site where users can log in and write messages to other users.
My current choice is wether to use the buildin User-Model or to build something my own. I don't need much from the buildin User: there will be no username ... | [
"\nIs there anything wrong with my reflections?\n\nYes.\n\nMy current choice is wether to use the buildin User-Model or to build something my own.\n\nThere is a third choice.\nhttp://docs.djangoproject.com/en/1.2/topics/auth/#storing-additional-information-about-users\n\neverything else would be placed in a UserPro... | [
9,
2,
1,
0
] | [] | [] | [
"design_decisions",
"django",
"django_users",
"python"
] | stackoverflow_0005337351_design_decisions_django_django_users_python.txt |
Q:
mysqldump from remote server to same remote serveritself from a local machine using python script!
If someone could not understand what exactly i'm trying to do, here it goes....
I use amazon cloud server, so i want to backup my database with a python script, hopefully i've got it working from command line.....
Wh... | mysqldump from remote server to same remote serveritself from a local machine using python script! | If someone could not understand what exactly i'm trying to do, here it goes....
I use amazon cloud server, so i want to backup my database with a python script, hopefully i've got it working from command line.....
When i do a backup, it should run mysqldump on amazon server and save it into amazon server itself!! /home... | [
"Maybe you should take a look at fabric\nIt may be overkill for a single command, but as soon as your deployment/backup tasks become complex, it will surely pay off.\n\nFabric is a Python (2.5 or higher) library and command-line tool for streamlining the use of SSH for application deployment or systems administrati... | [
4,
0
] | [] | [] | [
"mysql",
"mysqldump",
"python"
] | stackoverflow_0005593636_mysql_mysqldump_python.txt |
Q:
What is the optimized way to insert large number of records (more than 40,000) in sqlite3
I am trying to insert more than 40,000 records into sqlite3 in one stretch.
What would be the best approach to insert them in least amount of time.
I have used prepared statements in Java and am aware that precompiled sql st... | What is the optimized way to insert large number of records (more than 40,000) in sqlite3 | I am trying to insert more than 40,000 records into sqlite3 in one stretch.
What would be the best approach to insert them in least amount of time.
I have used prepared statements in Java and am aware that precompiled sql statements are faster as compared to raw sql queries. I was not able to find a code snippet for i... | [
"You should use executemany with an appropriate iterator\n"
] | [
8
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0005593881_python_sqlite.txt |
Q:
Can i control on my human model using blender
Possible Duplicate:
how can i have the full control on my 3D human model?
I want to have full control on my 3D human model like scaling it,changing width and height etc. using blender scripts to integrate with it in my own project
If yes how to start
If no is there a... | Can i control on my human model using blender |
Possible Duplicate:
how can i have the full control on my 3D human model?
I want to have full control on my 3D human model like scaling it,changing width and height etc. using blender scripts to integrate with it in my own project
If yes how to start
If no is there any other tool can do this ?
| [
"You start by learning blenders scripting language.\nYes it can also be done in 3dsmax, by either parameter wiring,\nrigging, or by using maxscript.\nYou are very diffuse with your question.\nwhat do you mean with \"integrate it in my own project\", what project?\nanimation project? blender project? realtime 3d pro... | [
1
] | [] | [] | [
"3dsmax",
"blender",
"maxscript",
"python"
] | stackoverflow_0005571503_3dsmax_blender_maxscript_python.txt |
Q:
python script to split date and time in a log file
I have the date and time in a log file like this [01/Jan/2011:11:12:38 -0500]. I want to split like 01/Jan/2011 and 11:12:38 -0500. Please help me as how to split this using python code.
A:
>>> "01/Jan/2011:11:12:38 -0500".split(":",1)
['01/Jan/2011', '11:12:38 ... | python script to split date and time in a log file | I have the date and time in a log file like this [01/Jan/2011:11:12:38 -0500]. I want to split like 01/Jan/2011 and 11:12:38 -0500. Please help me as how to split this using python code.
| [
">>> \"01/Jan/2011:11:12:38 -0500\".split(\":\",1)\n['01/Jan/2011', '11:12:38 -0500']\n>>>\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005594248_python.txt |
Q:
SQLAlchemy - difference between mapped orm.relation with backref or two orm.relation from both sides
In some project I implement user-requested mapping (at runtime) of two tables which are connected by a 1-to-n relation (one table has a ForeignKey field).
From what I get from the documentation, the usual way is to... | SQLAlchemy - difference between mapped orm.relation with backref or two orm.relation from both sides | In some project I implement user-requested mapping (at runtime) of two tables which are connected by a 1-to-n relation (one table has a ForeignKey field).
From what I get from the documentation, the usual way is to add a orm.relation to the mapped properties with a mapped_collection as collection_class on the non-forei... | [
"I found the answer myself by now:\nIf you use an orm.relation from each side and no backrefs, you have to use back_populates or if you mess around at one side, it won't be properly updated in the mapping on the other side.\nTherefore, an orm.relation from each side instead of an automated backref IS possible but y... | [
1
] | [] | [] | [
"database",
"python",
"relation",
"sqlalchemy"
] | stackoverflow_0004782344_database_python_relation_sqlalchemy.txt |
Q:
Need to avoid subprocess deadlock without communicate
I need a execute a command that produces a lot of output and takes a lot of time to execute (> 30 minutes). I was thinking of using subprocess.Popen to do it. I need to capture the output of the command, so I pass PIPE to stdout and stderr.
A deadlock problem w... | Need to avoid subprocess deadlock without communicate | I need a execute a command that produces a lot of output and takes a lot of time to execute (> 30 minutes). I was thinking of using subprocess.Popen to do it. I need to capture the output of the command, so I pass PIPE to stdout and stderr.
A deadlock problem when using Popen.wait() is well documented on a lot of forum... | [
"\nto workaround python bug #1124861 on Python2.4 you could attach stdin to a NUL device\n\n\nimport os\nfrom subprocess import PIPE, STDOUT, Popen\n\nlines = []\np = Popen(cmd, bufsize=1, stdin=open(os.devnull), stdout=PIPE, stderr=STDOUT)\nfor line in iter(p.stdout.readline, ''):\n print line, # pri... | [
13,
6,
3,
1,
0
] | [] | [] | [
"deadlock",
"pipe",
"python",
"stdout",
"subprocess"
] | stackoverflow_0005582933_deadlock_pipe_python_stdout_subprocess.txt |
Q:
How to store exponential values using python
I am looking for a way to perform a digit divided by larger value(2/5000000) and then store that value in table, but the problem is when i save that value, only 0 is stored , instead of correct value.I tried with float, double precision, but still only 0 is stored, is t... | How to store exponential values using python | I am looking for a way to perform a digit divided by larger value(2/5000000) and then store that value in table, but the problem is when i save that value, only 0 is stored , instead of correct value.I tried with float, double precision, but still only 0 is stored, is there any other way .
Thank you
| [
"Remember to operate on floating numbers, and not convert it after the operation. E.g. 2/5000000.\nAlso, use the Decimal library, if you are looking for more accurate decimals.\n",
"You need to use floating point division. To be explicit, you can cast ints to float:\n>>> a = 2\n>>> b = 5000000\n>>> c = a/float(b)... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005594758_python.txt |
Q:
Add with statement in non verbose mode in fabric (Python)
I have the following code now
if (verbose):
with hide('running', 'stdout', 'stderr'):
line 1
line 2
else:
line 1
line 2
Is there any way to avoid the repetition of line1 and line 2?
A:
def dothisstuff():
line 1
line 2
if... | Add with statement in non verbose mode in fabric (Python) | I have the following code now
if (verbose):
with hide('running', 'stdout', 'stderr'):
line 1
line 2
else:
line 1
line 2
Is there any way to avoid the repetition of line1 and line 2?
| [
"def dothisstuff():\n line 1\n line 2\n\nif (verbose):\n with hide('running', 'stdout', 'stderr'):\n dothisstuff()\nelse:\n dothisstuff()\n\nThough this might be overkill for only 2 repetitions of 2 lines. But I assume it are more then 2 lines :)\n"
] | [
1
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0005594836_fabric_python.txt |
Q:
Fabric's cd context manager does not work
I have set up my development environment on a new PC and seems I am having strange error with Fabric. Its 'cd' context manager seems does not change the current directory, and thus a lot of my commands don't work. I have written the test and it showed me results I have not... | Fabric's cd context manager does not work | I have set up my development environment on a new PC and seems I am having strange error with Fabric. Its 'cd' context manager seems does not change the current directory, and thus a lot of my commands don't work. I have written the test and it showed me results I have not expected to get:
from __future__ import with_s... | [
"You're looking for lcd (l for local) rather than cd (which is remote).\n"
] | [
63
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0005594933_fabric_python.txt |
Q:
what is the most frequent error in python for a beginner?
What do you think is the most frequent errors or pitfalls a beginner may encounter when he use python?
A:
Forgetting the self keyword in classes.
Either in method declaration and/or when referencing class members (specially for someone coming from .NET/Ja... | what is the most frequent error in python for a beginner? | What do you think is the most frequent errors or pitfalls a beginner may encounter when he use python?
| [
"Forgetting the self keyword in classes.\nEither in method declaration and/or when referencing class members (specially for someone coming from .NET/Java/.. world where \"equivalent\" this keyword can be omitted).\n",
"My guess would be:\nSyntaxError: invalid syntax\n",
"That could be IndentationError resulting... | [
2,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005595051_python.txt |
Q:
Merge 2 images using google app engine and python?
I want to merge 2 images and that too at specific location of 1st image.
Example:
1st image: x.png (400 X 400px)
2nd image: y.png (at 100,100 co-ordinates)
How can i do this using python in google appengine.?
If you can provide some codes for this ... or any refe... | Merge 2 images using google app engine and python? | I want to merge 2 images and that too at specific location of 1st image.
Example:
1st image: x.png (400 X 400px)
2nd image: y.png (at 100,100 co-ordinates)
How can i do this using python in google appengine.?
If you can provide some codes for this ... or any reference to this code... will be appreciated.
Thank you,
Pl... | [
"This can be done using the very cut down imaging library which emulates some of the functions of PIL. The function you need is composite\nfrom google.appengine.api import images\n\nxpng = #Load data from x.png here, or read from BlobProperty\nypng = #Load data from y.png here, or read from BlobProperty\n\ncomposi... | [
13,
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"python_imaging_library"
] | stackoverflow_0005594708_google_app_engine_python_python_imaging_library.txt |
Q:
Python ide with omitting lines while debugging
I have 3 lines and I want something like in visual studio where I can execute first line, and then by mouse move execution step to 3rd line and execute it without executing second line.
So in this case
print('a')
print('b')
print('c')
I want to have in an input:
a
c... | Python ide with omitting lines while debugging | I have 3 lines and I want something like in visual studio where I can execute first line, and then by mouse move execution step to 3rd line and execute it without executing second line.
So in this case
print('a')
print('b')
print('c')
I want to have in an input:
a
c
Now I'm using wing ide 4 trial and it hasn't this ... | [
"Wing IDE has a contributed add-on script that supports this:\nhttp://wiki.wingware.com/DebugMoveProgramCounter\nDrop it into the 'scripts' directory in your user settings directory (which varies in location but is listed 5th in Wing's About box) then select Reload All Scripts from the Edit menu.\nProbably easiest ... | [
2,
1
] | [] | [] | [
"debugging",
"ide",
"python"
] | stackoverflow_0005577951_debugging_ide_python.txt |
Q:
How to create web page to test and use web service?
I need to create a simple web service, and am leaning towards the Python package soaplib.
I would also like to create a simple web page that can consume the web service. This will serve two purposes:
Allow for easier testing by multiple people including non-pro... | How to create web page to test and use web service? | I need to create a simple web service, and am leaning towards the Python package soaplib.
I would also like to create a simple web page that can consume the web service. This will serve two purposes:
Allow for easier testing by multiple people including non-programmers.
Allow knowledgeable / power users to call the s... | [
"Have you considered using REST (here or here)? I was creating small app using GAE and I wanted to have programmable interface for that too. So using exactly the same URLs I've created a web service (REST) which based on client accepted mime type answered either using json (for software) or html (for users). You ha... | [
0
] | [] | [] | [
"python",
"soaplib",
"web_services",
"webforms"
] | stackoverflow_0005588337_python_soaplib_web_services_webforms.txt |
Q:
How can I catch "Uncaught exception"?
I'm developing some fb app, using python-sdk.
Sometimes I get an "Uncaught exception", that looks like:
Uncaught exception GET…
…
…
GraphAPIError: Error validating access token.
I know the reasons for this exception, and how to solve it (renew oauth token).
But how can I catc... | How can I catch "Uncaught exception"? | I'm developing some fb app, using python-sdk.
Sometimes I get an "Uncaught exception", that looks like:
Uncaught exception GET…
…
…
GraphAPIError: Error validating access token.
I know the reasons for this exception, and how to solve it (renew oauth token).
But how can I catch it?
Traditional try: .. except: doesn't d... | [
"Probably the exception is thrown in another thread spawn by the API, check its source code.\n"
] | [
0
] | [] | [] | [
"facebook_graph_api",
"python"
] | stackoverflow_0005593189_facebook_graph_api_python.txt |
Q:
python video capture loop
I've written a simple script to continuously capture snapshots from my webcam. My only issue is the videocapture module doesn't always grab an image which in turn crashes the program. I think I could solve this by using an infinite loop but I'm not real certain how to go about it. Here's ... | python video capture loop | I've written a simple script to continuously capture snapshots from my webcam. My only issue is the videocapture module doesn't always grab an image which in turn crashes the program. I think I could solve this by using an infinite loop but I'm not real certain how to go about it. Here's the script:
from VideoCapture i... | [
"Try to use cam.getImage instead of cam.saveSnapshot. cam.getImage returns PIL image, thus you are able to determine whether any frame has been actually grabbed or not.\nThe folloing code hasnt been tested: \nfrom VideoCapture import Device\nimport datetime\ndef capt():\n a = datetime.datetime.now().strftime(\"%Y... | [
4
] | [] | [] | [
"image_capture",
"python"
] | stackoverflow_0005595658_image_capture_python.txt |
Q:
Counting (and writing) word frequencies for each line within text file
first time posting in stack - always found previous questions capable enough of solving my prob! Main problem I have is the logic... even a pseudo code answer would be great.
I'm using python to read in data from each line of a text file, in th... | Counting (and writing) word frequencies for each line within text file | first time posting in stack - always found previous questions capable enough of solving my prob! Main problem I have is the logic... even a pseudo code answer would be great.
I'm using python to read in data from each line of a text file, in the format:
This is a tweet captured from the twitter api #hashtag http://url.... | [
"from collections import Counter\n\nhotwords = ('tweet', 'twitter')\n\nlines = \"a b c tweet d e f\\ng h i j k twitter\\n\\na\"\n\nc = Counter(lines.split())\n\nfor hotword in hotwords:\n print hotword, c[hotword]\n\nThis script works for python 2.7+\n",
"defaultdict is your friend for this sort of thing.\nf... | [
4,
1,
0
] | [] | [] | [
"filewriter",
"loops",
"nltk",
"python"
] | stackoverflow_0005595574_filewriter_loops_nltk_python.txt |
Q:
Twisted PerspectiveBroker/ServerFactory Questions
I'm trying to play with twisted. I've already try to create a server and a client using the appropriate Factory. It's a fantastic framework but only strings can be sent :(
I'd like to send some list or array objects as a start, and maybe later use objects from the ... | Twisted PerspectiveBroker/ServerFactory Questions | I'm trying to play with twisted. I've already try to create a server and a client using the appropriate Factory. It's a fantastic framework but only strings can be sent :(
I'd like to send some list or array objects as a start, and maybe later use objects from the server inside clients. But currently I'm stuck with som... | [
"PBClientFactory is a ClientFactory, so you still get clientConnectionFailed and clientConnectionLost calls on it. Subclass and override, if you want. You can also use the notifyOnDisconnect method which is implemented by both the Broker (the protocol class used with PB) and by RemoteReference which you'll often ... | [
2
] | [] | [] | [
"broker",
"factory",
"perspective",
"python",
"twisted"
] | stackoverflow_0005552620_broker_factory_perspective_python_twisted.txt |
Q:
How to use python on an object in a "for" function in a django template?
I want to be able to extract some data in python based on an object in a "for" function in a template.
In the example below I would like to do something with example outside the template system, so I wont be limited by the template language, ... | How to use python on an object in a "for" function in a django template? | I want to be able to extract some data in python based on an object in a "for" function in a template.
In the example below I would like to do something with example outside the template system, so I wont be limited by the template language, but can instead use python:
#django_template.html
{% for example in queryset... | [
"That's not the way Django works. If you want to do something \"outside\" the template language, you do it in your view function.\nThe template language is intentionally limited to presentation only.\nNo processing.\n(You can fudge the rules a bit with properties and descriptors, but don't. It ruins performance a... | [
2,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0005596900_django_django_templates_python.txt |
Q:
can't start IronPython interpreter from DOS prompt
here is the output of my path variable:
I run:
U:\>echo %path%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Dell\DW WLAN Card;C:\Program Files\Intel\DMIX;C:\Program Files\NTRU Cryptosystems\... | can't start IronPython interpreter from DOS prompt | here is the output of my path variable:
I run:
U:\>echo %path%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Dell\DW WLAN Card;C:\Program Files\Intel\DMIX;C:\Program Files\NTRU Cryptosystems\NTRU TCG Software Stack\bin\;C:\Program Files\Wave Syste... | [
"there is no magic in command line call (or nearly no)\nit takes the different files in your path variable here the useful is C:\\Program Files\\IronPython 2.6 for .NET 4.0 and call any .exe or .bat.\nBy looking into C:\\Program Files\\IronPython 2.6 for .NET 4.0 you should be able to find which program is enable f... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005596932_python.txt |
Q:
Django: When to customize save vs using post-save signal
I have a series of tests and cases in a database. Whenever a test is obsoleted, it gets end dated, and any sub-cases of that test should also be end dated. I see two ways to accomplish this:
1) Modify the save function to end date sub-cases.
2) Create a re... | Django: When to customize save vs using post-save signal | I have a series of tests and cases in a database. Whenever a test is obsoleted, it gets end dated, and any sub-cases of that test should also be end dated. I see two ways to accomplish this:
1) Modify the save function to end date sub-cases.
2) Create a receiver which listens for Test models being saved, and then end... | [
"I generally use this rule of thumb:\n\nIf you have to modify data so that the save won't fail, then override save() (you don't really have another option). For example, in an app I'm working on, I have a model with a text field that has a list of choices. This interfaces with old code, and replaces an older model ... | [
29,
16
] | [] | [] | [
"django",
"python",
"receiver",
"save"
] | stackoverflow_0005597378_django_python_receiver_save.txt |
Q:
{% extends "view/base.html" %}
{% extends "base.html" %} works fine, but I want to point to a
static_dir.
Here is app.yaml:
- url: /view
static_dir: static/view
Here is main.py:
template_values = {
'url': url,
'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file_... | {% extends "view/base.html" %} | {% extends "base.html" %} works fine, but I want to point to a
static_dir.
Here is app.yaml:
- url: /view
static_dir: static/view
Here is main.py:
template_values = {
'url': url,
'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.respon... | [
"Files served as static assets are just that, and not templates. If you want to extend a template, it has to be in a template directory.\n"
] | [
2
] | [] | [] | [
"djangoappengine",
"python",
"templates"
] | stackoverflow_0005597545_djangoappengine_python_templates.txt |
Q:
How to detect gestures in OpenKinect (with python wrappers)
I've started looking into OpenKinect development, and to start, I'm trying to figure out how to look for certain gestures done by the person.
Are there any tutorials out there on how to do this? Or what would be a good place to start?
I'm just trying to d... | How to detect gestures in OpenKinect (with python wrappers) | I've started looking into OpenKinect development, and to start, I'm trying to figure out how to look for certain gestures done by the person.
Are there any tutorials out there on how to do this? Or what would be a good place to start?
I'm just trying to do things like know when a person turns their hand in one directio... | [
"I'm not sure that it will be exactly what you want, but my brother has used the OpenNI/NITE library to recognize some gestures on the Kinect using Ruby. I saw a demo that my brother did where the computer recognized him giving the computer a wave. \nThere are Python bindings for that library with the onipy project... | [
3
] | [] | [] | [
"kinect",
"opencv",
"openni",
"python"
] | stackoverflow_0005588593_kinect_opencv_openni_python.txt |
Q:
Efficient way to run select query for millions of data
I want to run various select query 100 million times and I have aprox. 1 million rows in a table. Therefore, I am looking for the fastest method to run all these select queries.
So far I have tried three different methods, and the results were similar.
The fo... | Efficient way to run select query for millions of data | I want to run various select query 100 million times and I have aprox. 1 million rows in a table. Therefore, I am looking for the fastest method to run all these select queries.
So far I have tried three different methods, and the results were similar.
The following three methods are, of course, not doing anything use... | [
"This sort of benchmark is unlikely to produce any useful data, but the second method should be fastest, as once the statement is prepared it is stored in memory by the database server. Further calls to repeat the query do not require the text of the query to be transmitted, so saving a small about of time.\nThis i... | [
1,
0,
0
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0005595071_postgresql_psycopg2_python.txt |
Q:
Trying to include pypoker, poker-eval package in Python
Ok, so I finally got poker-eval and pypoker to install correctly. If I go to the pypoker folder in cygwin, and type python test.py, it runs the program fine. However, if I copy the test.py file over to a netbeans project main file, I get the error ImportError... | Trying to include pypoker, poker-eval package in Python | Ok, so I finally got poker-eval and pypoker to install correctly. If I go to the pypoker folder in cygwin, and type python test.py, it runs the program fine. However, if I copy the test.py file over to a netbeans project main file, I get the error ImportError: No module named _pokereval_2_7. The problem is, I am using ... | [
"A quick look at the source code makes it seem that Python 2.7 is not supported by that library. Try using Python 2.6 instead.\n",
"An example of a ready made Texas Hold'em 7- and 5-card evaluator can be found here with documentation and further explained here. It goes by the name of \"SpecialKEval\". All feedbac... | [
0,
0,
0
] | [] | [] | [
"package",
"poker",
"python",
"pythonpath",
"wxpython"
] | stackoverflow_0005366672_package_poker_python_pythonpath_wxpython.txt |
Q:
converting IPv6 string to bytes + python
Just as we use socket.inet_aton() for converting Ipv4 string is there any way to convert the IPv6 address string in Windows.
The function socket.inet_pton() is only available for Unix.
So is there any other way for me to do that on windows and python 2.6 ???
A:
IPy can do... | converting IPv6 string to bytes + python | Just as we use socket.inet_aton() for converting Ipv4 string is there any way to convert the IPv6 address string in Windows.
The function socket.inet_pton() is only available for Unix.
So is there any other way for me to do that on windows and python 2.6 ???
| [
"IPy can do all sorts of IP address manipulations.\nAlso, inet_pton() is available as of Windows Vista, but Python targets older releases as well.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005598332_python.txt |
Q:
Finding starts, ends, and loops with pydot
Is there a way to achieve this in pydot?
Take the following example:
[Outputted Dot File]
strict graph g{
"A" -> "B";
"B" -> "C";
"C" -> "D";
"D" -> "E";
}
[Python]
print(num.start)
>>> A
print(num.steps)
>>> ["a,b","b,c","c,d","d,e"]
print(num.end)
>>> E
or with the fo... | Finding starts, ends, and loops with pydot | Is there a way to achieve this in pydot?
Take the following example:
[Outputted Dot File]
strict graph g{
"A" -> "B";
"B" -> "C";
"C" -> "D";
"D" -> "E";
}
[Python]
print(num.start)
>>> A
print(num.steps)
>>> ["a,b","b,c","c,d","d,e"]
print(num.end)
>>> E
or with the following case:
[Outputted Dot File]
strict graph ... | [
"Well you have the whole graph structure, via graph.get_edge_list() you can implement standard depth first search to find shortest path between nodes. Finding loops is likewise done with standard graph algorithms. See this article on Graph implementations in Python for sourcecode on how to do shortest path betwee... | [
1,
1
] | [] | [] | [
"graphviz",
"pydot",
"python"
] | stackoverflow_0005596453_graphviz_pydot_python.txt |
Q:
Choosing items from a list on a percentual basis
I have a list with around 40 strings and want to assign every item a weight / percentage. During runtime I now want a randomizer to pick an item from the list according to its percentage. Meaning that over a large enough sample size the number of times this item get... | Choosing items from a list on a percentual basis | I have a list with around 40 strings and want to assign every item a weight / percentage. During runtime I now want a randomizer to pick an item from the list according to its percentage. Meaning that over a large enough sample size the number of times this item gets picked would correspond to the assigned percentage. ... | [
"Check out this page: Weighted random generation in Python\nEdit: See this also (on SO): A weighted version of random.choice\n",
"One way to do it is to use a range as a dictionary key (perhaps as a 2-tuple) and the string as the value. Then you can use random.randint() to generate an integer in the range describ... | [
3,
1
] | [] | [] | [
"list",
"python",
"random"
] | stackoverflow_0005598570_list_python_random.txt |
Q:
How to match the following strings using Python Regex?
Using Python Regex, I was wondering
how to match the patterns
("Exercises...) and
("Chapter...)
how to replace ("Exercises...)
with ("Exercises...)), and
("Chapter...) and ("Chapter....
For example:
("Exercises, 31" "#42") is converted to ("Exercises, 31" ... | How to match the following strings using Python Regex? | Using Python Regex, I was wondering
how to match the patterns
("Exercises...) and
("Chapter...)
how to replace ("Exercises...)
with ("Exercises...)), and
("Chapter...) and ("Chapter....
For example:
("Exercises, 31" "#42") is converted to ("Exercises, 31" "#42"))
("Chapter 2 I Positive Borel Measures, 33" "#44") to... | [
">>> import re\n>>> re.sub(r'(\\(\"Exercises.*?\\))', r'\\1)', '(\"Exercises, 31\" \"#42\")')\n'(\"Exercises, 31\" \"#42\"))'\n>>> re.sub(r'(\\(\"Chapter.*?)\\)', r'\\1', '(\"Chapter 2 I Positive Borel Measures, 33\" \"#44\")')\n'(\"Chapter 2 I Positive Borel Measures, 33\" \"#44\"'\n\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005599296_python_regex.txt |
Q:
Regular Expression help
So I have a string like this:
A!
B!
C!
<tag>
D!
E!
</tag>
F!
<tag>
G!
</tag>
Is it possible to parse this with a regex so I get this output (a list):
[A, B, C, [D, E], F, [G]]
Basically I'm looking for a way to split the string by ! and by the tag...and the tag part can happen anywhere...... | Regular Expression help | So I have a string like this:
A!
B!
C!
<tag>
D!
E!
</tag>
F!
<tag>
G!
</tag>
Is it possible to parse this with a regex so I get this output (a list):
[A, B, C, [D, E], F, [G]]
Basically I'm looking for a way to split the string by ! and by the tag...and the tag part can happen anywhere...and multiple times (but not r... | [
"I don't know Python, but you can do this with three simple regex-replaces (possibly doable as a single regex, but the following should work fine).\nJavascript version:\nstr = '[' + str.replace(/!\\n/, ', ').replace(/<[^\\/>]*>/, '[').replace(/<\\/[^>]*>/, ']') + ']';\n\nHopefully that will be understandable enough... | [
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005581956_python_regex.txt |
Q:
C++\IronPython integration example code?
I'm looking for a simple example code for C++\IronPython integration, i.e. embedding python code inside a C++, or better yet, Visual C++ program.
The example code should include: how to share objects between the languages, how to call functions\methods back and forth etc...... | C++\IronPython integration example code? | I'm looking for a simple example code for C++\IronPython integration, i.e. embedding python code inside a C++, or better yet, Visual C++ program.
The example code should include: how to share objects between the languages, how to call functions\methods back and forth etc...
Also, an explicit setup procedure would help ... | [
"UPDATE - I've written a more generic example (plus a link to a zip file containing the entire VS2008 project) as entry on my blog here.\nSorry, I am so late to the game, but here is how I have integrated IronPython into a C++/cli app in Visual Studio 2008 - .net 3.5. (actually mixed mode app with C/C++)\nI write a... | [
2,
1
] | [] | [] | [
"c++",
"ironpython",
"python",
"visual_c++",
"visual_studio"
] | stackoverflow_0003953910_c++_ironpython_python_visual_c++_visual_studio.txt |
Q:
Is there a dictionary-like datastructure that would allow searches for 'key' and for 'value'
I need a structure for my little Python program to save a list of max 500 names with one number each. The names would be unique, but the numbers would repeat (often). I first thought of a dictionary, but I also need to be ... | Is there a dictionary-like datastructure that would allow searches for 'key' and for 'value' | I need a structure for my little Python program to save a list of max 500 names with one number each. The names would be unique, but the numbers would repeat (often). I first thought of a dictionary, but I also need to be able to search for the numbers, for instance I would need to change all 2 to 3. What would you rec... | [
"You can use a dict, and search by value like so:\nnames = {\"Spiderman\":1, \"Dr. House\":2, \"Jon Skeet\":1}\n\nresulting_keys = [k for k, v in names.iteritems() if v == 1]\n# returns ['Spiderman', 'Jon Skeet']\n\nThen you can do something like:\n names.update(dict((k,names[k] + 1) for k in resulting_keys))\n\nWh... | [
3,
2
] | [] | [] | [
"data_structures",
"map",
"python"
] | stackoverflow_0005599481_data_structures_map_python.txt |
Q:
distutils does not recompile C extension modules
I'm trying to use distutils with a Python module that contains extensions written in C. The program code is housed on a Linux server, but I sometimes upload changes from a Windows machine using the file transfer program WinSCP (editing is done in Notepad++). I've no... | distutils does not recompile C extension modules | I'm trying to use distutils with a Python module that contains extensions written in C. The program code is housed on a Linux server, but I sometimes upload changes from a Windows machine using the file transfer program WinSCP (editing is done in Notepad++). I've noticed that distutils often does not notice these chang... | [
"Looking into the source for distutils and seeing how it enforces rebuilds it looks like it checks timestamps of files to determine whether a file is out of date or not.\nCan you make sure the timestamp is changing when winscp is uploading the file? Otherwise it looks like the build command has a \"force\" option t... | [
1
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0005599414_distutils_python.txt |
Q:
Chat popup using Django + Jquery
I am developing a chat system. I want a new popup window to appear whenever a client try to contact another client. so how can I create a popup window to be opened on a certain event like when client receive a message.
I am using Django, Jquery.
thanks.
A:
Check out the accepted... | Chat popup using Django + Jquery | I am developing a chat system. I want a new popup window to appear whenever a client try to contact another client. so how can I create a popup window to be opened on a certain event like when client receive a message.
I am using Django, Jquery.
thanks.
| [
"Check out the accepted answer on this post:\nHow does Facebook chat avoid continuous polling of the server?\nI think the Comet technique mentioned here would be best for your situation and could help you to avoid constant AJAX polling.\nYou could set up a Django view that worked as a client to a chat server, const... | [
2,
0
] | [] | [] | [
"ajax",
"chat",
"django",
"jquery",
"python"
] | stackoverflow_0005599502_ajax_chat_django_jquery_python.txt |
Q:
Does someone know any user reputation engines?
I develop website and would like to add reputation value to each user. So I'm looking for user reputation engine with features like:
good reputation model
users gain reputation when it do something what is liked by other users
users with bigger reputation has bigger ... | Does someone know any user reputation engines? | I develop website and would like to add reputation value to each user. So I'm looking for user reputation engine with features like:
good reputation model
users gain reputation when it do something what is liked by other users
users with bigger reputation has bigger influence to other reputations
exclude cyclic reputa... | [
"I'm not familiar with a particular open-source product that works out of the box, but Randy Farmer has recently written an O'Reilly book on Building Online Communities that is quite helpful.\nThis SO topic may also help with building your own: Karma/reputation system\n"
] | [
2
] | [] | [] | [
"django",
"python",
"web"
] | stackoverflow_0005593549_django_python_web.txt |
Q:
Why are my lambdas disappearing?
I have some Python code that's dependent upon passing around some lambdas, and they get copied to a few different places, but I'm finding that when I pop them out of a list, they just magically disappear from all the other lists. I don't know if this is a bug or not. I'll note th... | Why are my lambdas disappearing? | I have some Python code that's dependent upon passing around some lambdas, and they get copied to a few different places, but I'm finding that when I pop them out of a list, they just magically disappear from all the other lists. I don't know if this is a bug or not. I'll note that I'm running this on CPython.
Here's... | [
"list.pop modifies the list in-place. So everyone with a reference to the list sees the same change. You're not storing copies in the second, you're just storing several references to one single list, which is then emptied in the first while loop.\nYou can copy lists through a[:] (which is a slice from the beginnin... | [
4,
2,
1
] | [] | [] | [
"arraylist",
"arrays",
"lambda",
"python"
] | stackoverflow_0005599878_arraylist_arrays_lambda_python.txt |
Q:
How to use loop to create a group of list containers in python
Is it possible to create a group of list/array from another list.
Have
L = ['a','b','c','d','e',]
would like
a=[]
b=[]
c=[]
d=[]
e=[]
A:
You could, with some hackery, create variables from strings. However, this is almost never a good idea. Just ... | How to use loop to create a group of list containers in python | Is it possible to create a group of list/array from another list.
Have
L = ['a','b','c','d','e',]
would like
a=[]
b=[]
c=[]
d=[]
e=[]
| [
"You could, with some hackery, create variables from strings. However, this is almost never a good idea. Just use a dict, which is exactly that without all the headaches that come from confusing your code's namespace with a collection for (possibly user-provided) data.\nd = {}\nfor name in L:\n d[name] = []\n\n(... | [
12,
5
] | [] | [] | [
"arrays",
"list",
"loops",
"python"
] | stackoverflow_0005599992_arrays_list_loops_python.txt |
Q:
Regex Group Matching
I am trying to match a pattern like so:
Pattern: (abc)(def)(ghi)h
Match:
Group 0 = [a,b,c]
Group 1 = [d,e,f]
Group 2 = [g,h,i]
Group 3 = h
Is it possible via regex to extrapolate the data into a list like that described?
The code being used is Python for reference.
A:
AFAIK, ... | Regex Group Matching | I am trying to match a pattern like so:
Pattern: (abc)(def)(ghi)h
Match:
Group 0 = [a,b,c]
Group 1 = [d,e,f]
Group 2 = [g,h,i]
Group 3 = h
Is it possible via regex to extrapolate the data into a list like that described?
The code being used is Python for reference.
| [
"AFAIK, that's not possible in one regex. You could do something like this:\nimport re\n\nmatches = re.findall('[^()]+', '(abc)(def)(ghi)h')\nmap = []\nfor m in matches: \n map.append(list(m))\nfor e in map:\n print e\n\nwhich will print:\n['a', 'b', 'c']\n['d', 'e', 'f']\n['g', 'h', 'i']\n['h']\n\nEDIT\nThe patt... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005599753_python_regex.txt |
Q:
Displaying real time output to wx.TextCtrl
I'm currently in the process of building a wi-fi packet capture utility in Ubuntu using the modules wxPython, Pcapy and impacket. I have created the GUI in wxPython and the capture code referencing the other modules, however combining the two is proving difficult. As idio... | Displaying real time output to wx.TextCtrl | I'm currently in the process of building a wi-fi packet capture utility in Ubuntu using the modules wxPython, Pcapy and impacket. I have created the GUI in wxPython and the capture code referencing the other modules, however combining the two is proving difficult. As idiotic as this sounds, i'm finding it difficult to ... | [
"If you want to redirect everything sent to stdout (emitted by print statements, for example) to your text control, then you can just replace sys.stdout with your own object simulating a file object.\nYou can just use the StringIO class, then send its accumulated value to your text control periodically (using a tim... | [
1
] | [] | [] | [
"python",
"wxpython",
"wxtextctrl"
] | stackoverflow_0005599528_python_wxpython_wxtextctrl.txt |
Q:
Consuming XML restful service, outputting in JSON - for loop issue
I have a RESTful service on another server on the internet. I am sending that a request, which returns a single XML item with a few attributes.
I also have another python function that consumes a locally stored XML, and when I provide a parameter t... | Consuming XML restful service, outputting in JSON - for loop issue | I have a RESTful service on another server on the internet. I am sending that a request, which returns a single XML item with a few attributes.
I also have another python function that consumes a locally stored XML, and when I provide a parameter to it, it'll iterate through all the elements, and return only the XML it... | [
"You need to pass a generator to Django as a response:\nresponse_generator = (\n json.dumps(\n {\n 'name': row.getAttribute(\"name\"),\n 'address': row.getAttribute(\"address\"),\n 'phone': row.getAttribute(\"phone\")},\n sort_keys=True,\n indent=4)\n for ... | [
1
] | [] | [] | [
"json",
"python",
"rest",
"xml"
] | stackoverflow_0005599344_json_python_rest_xml.txt |
Q:
python matplotlib add and remove text to figure using button events
I'm trying to add text to a graph at the location of the mouse pointer when button_press_event is called and remove it when button_release_event is called. I have successfully added the text but I can not get it to erase. Here is part of the co... | python matplotlib add and remove text to figure using button events | I'm trying to add text to a graph at the location of the mouse pointer when button_press_event is called and remove it when button_release_event is called. I have successfully added the text but I can not get it to erase. Here is part of the code I used:
def onclick(event):
print 'you pressed', event.button, eve... | [
"Assuming you should use it in a class and refer to the following txt as self.txt I use global here for sake of ease:\ntxt = None\n\ndef onclick(event):\n global txt\n txt = plt.text(event.xdata, event.ydata, 'TESTTEST', fontsize=8)\n fig.canvas.draw()\n\ndef offclick(event):\n txt.remove()\n fig.can... | [
10
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0005600370_matplotlib_python.txt |
Q:
python variables, classes
Dear All, Trying to learn python, classes, and how to pass variables between. Going through a learning guide here, and am having trouble with the following Error:
TypeError: unbound method scan() must be called with lexicon instance as first argument (got str instance instead)
Can someo... | python variables, classes | Dear All, Trying to learn python, classes, and how to pass variables between. Going through a learning guide here, and am having trouble with the following Error:
TypeError: unbound method scan() must be called with lexicon instance as first argument (got str instance instead)
Can someone please help me understand th... | [
"You have to instantiate an object of type lexicon before you can invoke one of its methods. i.e.\nlex = lexicon(data)\nlex.scan()\n\n",
"In addition to what Jim said, self is automatically passed in for you. (And it's not required to be called self but calling it something else will just confuse yourself and ot... | [
7,
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0005601080_class_python.txt |
Q:
Sorting a dict by values inside an inner dict in Python
My apologies if I am using the incorrect terminology, as I'm a bit of a Python n00b when it comes to the proper descriptions for data structures.
I have a data structure that looks like this:
{
u'COU': {'hl': 39, 'hw': 42, 'winPct': Decimal('0.54716981132... | Sorting a dict by values inside an inner dict in Python | My apologies if I am using the incorrect terminology, as I'm a bit of a Python n00b when it comes to the proper descriptions for data structures.
I have a data structure that looks like this:
{
u'COU': {'hl': 39, 'hw': 42, 'winPct': Decimal('0.5471698113207547169811320755'), 'al': 36, 'l': 72, 'w': 87, 'aw': 45},
... | [
"You can't sort a dictionary, but you could convert the dictionary into a list of tuples with the form (key, value).\nsorted_d = sorted(d.iteritems(), key=lambda v: v[1]['winPct'])\n\nTo Reverse the sorting as per your comment use:\nsorted_d = sorted(d.iteritems(), key=lambda v: v[1]['winPct'], reverse=True)\n\n",
... | [
2,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0005601909_python_sorting.txt |
Q:
How to check that new instantiation of class is proper data type (python)
I want to create a class that accepts data only in a specific format, and otherwise returns an error. For example,
class Sentence:
def __init__(self, input):
self.initial_input = input
## Check and assign input
if isinstance(input, ... | How to check that new instantiation of class is proper data type (python) | I want to create a class that accepts data only in a specific format, and otherwise returns an error. For example,
class Sentence:
def __init__(self, input):
self.initial_input = input
## Check and assign input
if isinstance(input, (list, tuple)):
self.tagged = input
else: raise TypeError, ('Input must be a ... | [
"Use of duck typing is common in Python, so checking the type is usually discouraged unless absolutely necessary. Generally, if an argument must be of some specific type, it is best to assume that the user has provided the correct type. This allows the user to provide something that isn't quite right but still work... | [
4
] | [] | [] | [
"class",
"oop",
"python"
] | stackoverflow_0005602066_class_oop_python.txt |
Q:
Converting a list of dict to a list of a specific value
I'd like to know the most elegant (and performant?) pattern to replace what I often code as:
names = []
for person in persons:
names.append(person.GetName())
I write this because it's how I'd write it in JavaScript, and I don't know any better. But I ima... | Converting a list of dict to a list of a specific value | I'd like to know the most elegant (and performant?) pattern to replace what I often code as:
names = []
for person in persons:
names.append(person.GetName())
I write this because it's how I'd write it in JavaScript, and I don't know any better. But I imagine there's something I can do with list comprehensions?
| [
"names = [person.GetName() for person in persons]\n\n",
"names = [person.GetName() for person in persons] \n"
] | [
2,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0005602265_list_comprehension_python.txt |
Q:
Single Instance Application - Passing commands
I'm using wxPython, and I'm trying to make a single instance application. As far as this goes, there is no problem. My problem is passing commands to the already existing instance.
So lets say that when I double click a file that is associated with my application, it ... | Single Instance Application - Passing commands | I'm using wxPython, and I'm trying to make a single instance application. As far as this goes, there is no problem. My problem is passing commands to the already existing instance.
So lets say that when I double click a file that is associated with my application, it reads the file and displays, here is an example:
imp... | [
"A \"Single Instance\" application has two parts.\nA \"client\", which is double-clicked and starts running. If the server is not running, it starts the server. It passes commands to the server. And stops. Leaving the server running.\nA \"server\", which is started by each client. It does the \"listening to ... | [
2,
2
] | [] | [] | [
"python",
"single_instance",
"wxpython"
] | stackoverflow_0005520639_python_single_instance_wxpython.txt |
Q:
IRC BOT (python)
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('PRIVMSG ' + 'NICKSERV' + 'ghost' + 'supaBOT' + 'htown')
sck.send('NICK supaBOT\r\n')
sck.send('PRIVMSG ' + 'NICKSERV' + 'IDENTIFY' + 'password')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
s... | IRC BOT (python) | sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('PRIVMSG ' + 'NICKSERV' + 'ghost' + 'supaBOT' + 'htown')
sck.send('NICK supaBOT\r\n')
sck.send('PRIVMSG ' + 'NICKSERV' + 'IDENTIFY' + 'password')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN ' + " " ... | [
"Like Mike said, you're not sending the data you should be sending. You need to add the spaces there and you need : before final command arguments if they have spaces. Some of the lines are also missing '\\r\\n'.\nThat is, the format for a PRIVMSG is: 'PRIVMSG nick :message with spaces\\r\\n'\nPRIVMSG only has two ... | [
5,
0
] | [] | [] | [
"irc",
"python",
"sockets"
] | stackoverflow_0005602128_irc_python_sockets.txt |
Q:
Reasons behind naming in easy-to-confuse Python's classes such as OS and SYS?
I have noticed that considerably amount of questions in SO, relating to Python, are about people messing up Sys -class, OS class and no class. For example, an easy confusing is the case: os.open("something"), open("something") and sys.op... | Reasons behind naming in easy-to-confuse Python's classes such as OS and SYS? | I have noticed that considerably amount of questions in SO, relating to Python, are about people messing up Sys -class, OS class and no class. For example, an easy confusing is the case: os.open("something"), open("something") and sys.open("something"). I haven't understood yet the reasons behind the naming of classes,... | [
"\nEasy confusing is lies in the case: os.open(\"something\"), open(\"something\") and sys.open(\"something\").\n\nA \"mnemonic\" is the documentation, available on-line or downloaded to your workstation.\n\nBuilt-in open: http://docs.python.org/library/functions.html#open \"Open a file\"\nos.open: http://docs.pyt... | [
3,
2
] | [] | [] | [
"language_history",
"naming",
"operating_system",
"python",
"security"
] | stackoverflow_0005602439_language_history_naming_operating_system_python_security.txt |
Q:
Where is the python path set when I don't have a .bash_profile?
I am running ubuntu, and I don't have a .bash_profile.
So my question is, where exactly is my python path set then?
How can I see what the current python path is, doing:
$PYTHON_PATH
doesn't return anything?
A:
It's set by the site module, and the ... | Where is the python path set when I don't have a .bash_profile? | I am running ubuntu, and I don't have a .bash_profile.
So my question is, where exactly is my python path set then?
How can I see what the current python path is, doing:
$PYTHON_PATH
doesn't return anything?
| [
"It's set by the site module, and the interpreter executable itself. sys.path contains the current value.\n",
"You can see your python path in python like so:\n>> import sys\n>> print sys.path\n\n",
"you can create a .bash_profile with your favorite editor, and put into it:\nexport PYTHONPATH=$HOME/lib/python\n... | [
5,
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005602559_python.txt |
Q:
How can I access members of the HTTPServer from a BaseHTTPRequestHandler?
I'm putting together a little application that involved both a GUI, HTTP and TCP servers. The GUI controls the responses returned from the HTTP and TCP servers to the clients. I'm using the HTTPServer and SocketServer.TCPServer classes as ... | How can I access members of the HTTPServer from a BaseHTTPRequestHandler? | I'm putting together a little application that involved both a GUI, HTTP and TCP servers. The GUI controls the responses returned from the HTTP and TCP servers to the clients. I'm using the HTTPServer and SocketServer.TCPServer classes as the servers, with subclasses for both BaseHTTPRequestHandler and StreamRequestH... | [
"BaseHTTPRequestHandler has a built in attribute server. Not sure why you are setting another self._server in the inherited class. Would be useful if you can also copy the code in get_interface() method. Also what is this 'server' argument ? instance of inherited HttpServer?\n"
] | [
6
] | [] | [] | [
"basehttpserver",
"httpserver",
"python"
] | stackoverflow_0005602412_basehttpserver_httpserver_python.txt |
Q:
Catching a dying process in pexpect
I'm writing some pexpect stuff that's basically sending commands over telnet.
But, it's possible that my telnet session could die (due to networking problems, a cable getting pulled, whatnot).
How do I initialize a telnet session such that, if it dies, I can catch it and tell it... | Catching a dying process in pexpect | I'm writing some pexpect stuff that's basically sending commands over telnet.
But, it's possible that my telnet session could die (due to networking problems, a cable getting pulled, whatnot).
How do I initialize a telnet session such that, if it dies, I can catch it and tell it to reconnect and then continue execution... | [
"IMHO, you're normally better-off with a currently-maintained library like exscript or telnetlib, but the efficient incantation in pexpect is:\nimport pexpect as px\n\ncmds = ['cmd1', 'cmd2', 'cmd3']\nretcode = -1\nwhile (retcode<10):\n if (retcode<2):\n child = px.spawn('telnet %s %s' % (ip_addr,port))\... | [
4,
0
] | [] | [] | [
"expect",
"pexpect",
"python"
] | stackoverflow_0005602080_expect_pexpect_python.txt |
Q:
Python Console Website
I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?
A:
This is one I know of:
http://shell.appspot.com/
There's also Lord of the REPL's:
http://lotrepls.appspot.com/
Python on repl.it:
http://repl.it/languages/Python
A:
Whil... | Python Console Website | I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?
| [
"This is one I know of:\n\nhttp://shell.appspot.com/\n\nThere's also Lord of the REPL's:\n\nhttp://lotrepls.appspot.com/\n\nPython on repl.it:\n\nhttp://repl.it/languages/Python\n\n",
"While not really a \"console\", skulpt.org runs python code client-side with no plugins or anything, which makes it a lot faster ... | [
12,
11,
4,
4,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0001598733_python.txt |
Q:
Design Patterns for Dynamic Inheritance
Here's what I'm trying to do, I'm not sure what to look for or what the proper way to design this is:
I'm working on an exception hierarchy for an application. As part of this, there are some exceptions which will sometimes be fatal and other times be recoverable -- whether ... | Design Patterns for Dynamic Inheritance | Here's what I'm trying to do, I'm not sure what to look for or what the proper way to design this is:
I'm working on an exception hierarchy for an application. As part of this, there are some exceptions which will sometimes be fatal and other times be recoverable -- whether a particular instance is fatal or recoverable... | [
"My recommendation is to decouple the exception's content from its meaning. The same exception can have different meanings in different places!\nYour question suggests to turn an exception into a \"sentient\" object with advanced capabilities like examining logs. But this is not the intention for exceptions. Except... | [
6,
1
] | [] | [] | [
"design_patterns",
"exception",
"metaprogramming",
"oop",
"python"
] | stackoverflow_0005602804_design_patterns_exception_metaprogramming_oop_python.txt |
Q:
Python Programming for the absolute beginner Chapter 7 Challenge 2
I've been trying to learn python using this book, however, I seem to be stuck on this challenge.
"2. Improve the Trivia Challenge game so that it maintains a high-scores list in a file. The program should record the player's name and score if the p... | Python Programming for the absolute beginner Chapter 7 Challenge 2 | I've been trying to learn python using this book, however, I seem to be stuck on this challenge.
"2. Improve the Trivia Challenge game so that it maintains a high-scores list in a file. The program should record the player's name and score if the player makes the list. Store the high scores using a pickled object."
I d... | [
"I don't want to do it all for you, but here are some hints:\nNo need for dictionary, dictionaries are unordered. Use a sorted list of 2-tuples: high_scores = [(score1, name1), (score2, name2), ...]. Sort the list in reverse order: high_scores.sort(reverse=True). Use the list append and pop methods to add new entri... | [
0
] | [] | [] | [
"pickle",
"python",
"python_3.x"
] | stackoverflow_0005407934_pickle_python_python_3.x.txt |
Q:
Python and BeautifulSoup for parsing HTML
I've gotten to the point where I have the HTML, but I'd like to extract just one string out of it
There is a line in each HTML file that looks like this
<h4 class="ws-ds-name detail-title">DATA_I_WANT</h4>
And I'm not sure how to use the .find() method to get exactly tha... | Python and BeautifulSoup for parsing HTML | I've gotten to the point where I have the HTML, but I'd like to extract just one string out of it
There is a line in each HTML file that looks like this
<h4 class="ws-ds-name detail-title">DATA_I_WANT</h4>
And I'm not sure how to use the .find() method to get exactly that tag and then extract out the DATA_I_WANT
Any ... | [
"from BeautifulSoup import BeautifulSoup as bs\nmarkup = ''' some HTML here '''\nsoup = bs(markup)\nsoup.find('h4', {'class':'ws-ds-name detail-title'}).contents[0]\n# result: \n# u'DATA_I_WANT'\n\nOr you could use lxml:\nfrom lxml.html import fromstring\ndoc = fromstring(markup)\ndoc.xpath('//h4[@class=\"ws-ds-nam... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0005603217_beautifulsoup_python.txt |
Q:
know filename:line_no where an import to my_module was made
I have a module my_module that it is sourced (imported) by lots of files using:
from my_module import *
Being inside the module, can I know which file imported this module ?
I would like to know the filename:line_no which made this import.
so code I requi... | know filename:line_no where an import to my_module was made | I have a module my_module that it is sourced (imported) by lots of files using:
from my_module import *
Being inside the module, can I know which file imported this module ?
I would like to know the filename:line_no which made this import.
so code I require is:
my_module.py
print "This module is currently imported from... | [
"Place this in your top-level module code:\nimport traceback\nlast_frame = traceback.extract_stack()[-2]\nprint 'Module imported from file:line_no = %s:%i' % last_frame[:2]\n\nYou can also use inspect instead of traceback:\nimport inspect\nlast_frame = inspect.stack()[1]\nprint 'Module imported from file:line_no = ... | [
5
] | [] | [] | [
"file",
"import",
"module",
"python"
] | stackoverflow_0005603321_file_import_module_python.txt |
Q:
Is there a limitation on the number of tables a PostgreSQL database can have?
I have created a database in PostgreSQL, let's call it testdb.
I have a generic set of tables inside this database, xxx_table_one, xxx_table_two and xxx_table_three.
Now, I have Python code where I want to dynamically create and remove "... | Is there a limitation on the number of tables a PostgreSQL database can have? | I have created a database in PostgreSQL, let's call it testdb.
I have a generic set of tables inside this database, xxx_table_one, xxx_table_two and xxx_table_three.
Now, I have Python code where I want to dynamically create and remove "sets" of these 3 tables to my database with a unique identifier in the table name d... | [
"PostgreSQL doesn't have many limits, your hardware is much more limited, that's where you encounter most problems. http://www.postgresql.org/about/\nYou can have 2^32 tables in a single database, just over 4 billion.\n",
"\nPostgreSQL doesn't impose a direct limit on this, your OS does (it depends on maximum dir... | [
14,
3,
0
] | [] | [] | [
"database",
"database_design",
"mysql",
"postgresql",
"python"
] | stackoverflow_0003715456_database_database_design_mysql_postgresql_python.txt |
Q:
In subprocess.Popen, which file does bufsize apply to?
I'm in need of setting the stderr stream in a Popen call to line-buffered. I discovered the bufsize argument, but it doesn't say which of the 3 (stdin, stdout, stderr) files it's actually applied to.
Which file does the bufsize argument
modify?
How do I modif... | In subprocess.Popen, which file does bufsize apply to? | I'm in need of setting the stderr stream in a Popen call to line-buffered. I discovered the bufsize argument, but it doesn't say which of the 3 (stdin, stdout, stderr) files it's actually applied to.
Which file does the bufsize argument
modify?
How do I modify the other
file buffering modes?
| [
"Use the source, Luke :-) /usr/lib/python2.7/subprocess.py:\nif p2cwrite is not None:\n self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)\nif c2pread is not None:\n if universal_newlines:\n self.stdout = os.fdopen(c2pread, 'rU', bufsize)\n else:\n self.stdout = os.fdopen(c2pread, 'rb', bufsize)... | [
3
] | [] | [] | [
"buffering",
"popen",
"python",
"stream",
"subprocess"
] | stackoverflow_0005604204_buffering_popen_python_stream_subprocess.txt |
Q:
track def excute in django
I want by default see all def run without any customizing code
example
[date] settings.py
[date] url.py
[date] /apps/views/views.py run index def
[date] ...
is there any middle were or something do this job?
A:
This is a tough one. First of all, logging every function (proper term fo... | track def excute in django | I want by default see all def run without any customizing code
example
[date] settings.py
[date] url.py
[date] /apps/views/views.py run index def
[date] ...
is there any middle were or something do this job?
| [
"This is a tough one. First of all, logging every function (proper term for “def”) would probably a bad idea and unnecessary. You might want to look at the python trace module.\nIf you are just trying to debug what's happening in a Django app and want to do so with a middleware, look no further than the awesome dja... | [
2
] | [] | [] | [
"django",
"logging",
"python",
"tracking"
] | stackoverflow_0005603298_django_logging_python_tracking.txt |
Q:
XPath match every node containing text
How do I match all child nodes containing text recursively.
If I have a tree like
table
tr
td
"hello"
td
b
"hi"
tr
td
"salud"
td
em
"bonjour"
How do I match every single string within the table node with xpath?
Something like "//table/*/text()"?... | XPath match every node containing text | How do I match all child nodes containing text recursively.
If I have a tree like
table
tr
td
"hello"
td
b
"hi"
tr
td
"salud"
td
em
"bonjour"
How do I match every single string within the table node with xpath?
Something like "//table/*/text()"?
| [
"The XPath expression you gave was almost correct already:\n//table//text()\nwill get you all text nodes within all tables in the document.\n",
"How about the following?\nfrom lxml import etree\nfrom StringIO import StringIO\n\ninput = '''\n<table>\n <tr>\n <td>hello</td>\n <td><b>hi</b></td>\n </tr>\n <tr>\n ... | [
3,
0
] | [] | [] | [
"lxml",
"python",
"scrape",
"xpath"
] | stackoverflow_0005603368_lxml_python_scrape_xpath.txt |
Q:
How do I use Xfce widgets with Pygi?
I've been playing around with pygi recently, trying to put together a mixer plugin for xfce, but when I try to load the GtkBuilder file from python it doesn't recognize the XfceTitledDialog (which I'm trying to use for the configuration dialog).
Is there something special I nee... | How do I use Xfce widgets with Pygi? | I've been playing around with pygi recently, trying to put together a mixer plugin for xfce, but when I try to load the GtkBuilder file from python it doesn't recognize the XfceTitledDialog (which I'm trying to use for the configuration dialog).
Is there something special I need to do to use xfce widgets?
Here's what I... | [
"Try setting some shell environment variables that glade needs.\nGLADE_PIXMAP_PATH=/usr/share/glade3/pixmaps\nGLADE_CATALOG_PATH=:/usr/share/glade3/catalogs\nGLADE_MODULE_PATH=:/usr/lib64/glade3/modules\nLIBGLADE_MODULE_PATH=/usr/lib64/libglade/2.0\n\nMake sure those are the right paths on your system and the the x... | [
0
] | [] | [] | [
"gtk",
"gtkbuilder",
"python"
] | stackoverflow_0005603124_gtk_gtkbuilder_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.