content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Django Projects & Apps
i am a django newbie, and trying to get my projects and apps in a directory on my desktop.. I need to add these directories to the python path so it knows where they live and can interact with eachother.. how can I do this best? I found several ways which might have downsides???
through she... | Django Projects & Apps | i am a django newbie, and trying to get my projects and apps in a directory on my desktop.. I need to add these directories to the python path so it knows where they live and can interact with eachother.. how can I do this best? I found several ways which might have downsides???
through shell, import sys, sys.path.app... | [
"I tend to use the simple\nimport sys\npath = '/var/www/Django/'\nif path not in sys.path:\n sys.path.append(path)\n\nIn my WSGI scripts which \"power\" my application. I also have a custom management command that does exactly this before calling shell. Previously to that, I simply dumped the above in \nsettings... | [
0
] | [] | [] | [
"django",
"python",
"pythonpath"
] | stackoverflow_0004878904_django_python_pythonpath.txt |
Q:
Controlling a device that only interacts via Hyperterminal using python
I am trying to write a basic driver to control a device that only interacts with hyperterminal. All the inputs expect HT formated data and all of the returns include copious equal signs, newlines, and spaces in order to get the formatting corr... | Controlling a device that only interacts via Hyperterminal using python | I am trying to write a basic driver to control a device that only interacts with hyperterminal. All the inputs expect HT formated data and all of the returns include copious equal signs, newlines, and spaces in order to get the formatting correct for human visualization. I am pretty sure that the returns are generating... | [
"There's nothing special about HiperTerminal. The end of line character is usually '\\r\\n' or '\\n' alone.\n"
] | [
0
] | [] | [] | [
"device_driver",
"hyperterminal",
"interface",
"python",
"regex"
] | stackoverflow_0004878674_device_driver_hyperterminal_interface_python_regex.txt |
Q:
Placing Custom Images in a Plot Window--as custom data markers or to annotate those markers
I have a set of 150x150px png images, and a set of (x, y) coordinates that they correspond to. Is there a way to plot the images on a grid? For example, I'm looking for an R or Python solution to create something like the ... | Placing Custom Images in a Plot Window--as custom data markers or to annotate those markers | I have a set of 150x150px png images, and a set of (x, y) coordinates that they correspond to. Is there a way to plot the images on a grid? For example, I'm looking for an R or Python solution to create something like the following:
| [
"You create a bounding box by instantiating AnnotationBbox--once for each image\nthat you wish to display; the image and its coordinates are passed to the constructor.\nThe code is obviously repetitive for the two images, so once that block is put in a function, it's not as long as it seems here.\nimport matplotlib... | [
30,
17,
3,
3,
1
] | [] | [] | [
"matplotlib",
"plot",
"python",
"r"
] | stackoverflow_0004860417_matplotlib_plot_python_r.txt |
Q:
Import custom package in python google app engine
OK guys I can't find a solution anywhere for my problem, and I hope the solution is a simple one. Previously I had a flat file system for my gae project with no folders. I've been refactoring some code and I tried to put some in a folder. I'm a bit new and I've nev... | Import custom package in python google app engine | OK guys I can't find a solution anywhere for my problem, and I hope the solution is a simple one. Previously I had a flat file system for my gae project with no folders. I've been refactoring some code and I tried to put some in a folder. I'm a bit new and I've never done something like this before, but nothing on the ... | [
"I think the problem is that you need to explicitly import site1_ripper unless it's specified in __init__.py. Make your main import be:\nimport SiteCrawlers.site1_ripper\n\n",
"In your main file try:\nfrom SiteCrawlers.site1_ripper import siteCrawler\n\nclass Updater(webapp.RequestHandler):\n def get(self):\n ... | [
3,
0
] | [] | [] | [
"google_app_engine",
"import",
"python"
] | stackoverflow_0004878609_google_app_engine_import_python.txt |
Q:
How to script database inserts with python?
Using old example:
csr = con.cursor()
csr.execute('Truncate table test.data')
csr.executemany('INSERT INTO test.data VALUES (?,?,?,?)', Newdata)
con.commit()
How would I insert %s into
csr.executemany('INSERT INTO test.data VALUES (?,?,?,?)', Newdata)
tried:
c... | How to script database inserts with python? | Using old example:
csr = con.cursor()
csr.execute('Truncate table test.data')
csr.executemany('INSERT INTO test.data VALUES (?,?,?,?)', Newdata)
con.commit()
How would I insert %s into
csr.executemany('INSERT INTO test.data VALUES (?,?,?,?)', Newdata)
tried:
csr.executemany('INSERT INTO test.%s VALUES (?,?,?... | [
"Should be:\ncsr.executemany('INSERT INTO test.%s VALUES (?,?,?,?)' % symbol, Newdata)\n\nAlthough I would instead do something like:\nquery = 'INSERT INTO test.%s VALUES (?,?,?,?)' % symbol\ncsr.executemany(query, Newdata)\n\nNote that ? is not the default placeholder on all database wrappers. In some %s is used i... | [
4
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004879209_mysql_python.txt |
Q:
Experience with using h5py to do analytical work on big data in Python?
I do a lot of statistical work and use Python as my main language. Some of the data sets I work with though can take 20GB of memory, which makes operating on them using in-memory functions in numpy, scipy, and PyIMSL nearly impossible. The sta... | Experience with using h5py to do analytical work on big data in Python? | I do a lot of statistical work and use Python as my main language. Some of the data sets I work with though can take 20GB of memory, which makes operating on them using in-memory functions in numpy, scipy, and PyIMSL nearly impossible. The statistical analysis language SAS has a big advantage here in that it can operat... | [
"We use Python in conjunction with h5py, numpy/scipy and boost::python to do data analysis. Our typical datasets have sizes of up to a few hundred GBs.\nHDF5 advantages:\n\ndata can be inspected conveniently using the h5view application, h5py/ipython and the h5* commandline tools\nAPIs are available for different p... | [
49,
5
] | [] | [] | [
"h5py",
"hdf5",
"python",
"sas",
"scipy"
] | stackoverflow_0004871670_h5py_hdf5_python_sas_scipy.txt |
Q:
Mongodb schema structure - push and pop
I'd like to have something like the following schema for a collection:
name1:
- guid1 : [{ foo1}, {foo2}, .. {foo n}]
- guid2 : [{ foo1}, {foo2}, .. {foo n}]
(1)
Each of the foo objects are dictionaries with the same internal structure - and so ideally i would have a sing... | Mongodb schema structure - push and pop | I'd like to have something like the following schema for a collection:
name1:
- guid1 : [{ foo1}, {foo2}, .. {foo n}]
- guid2 : [{ foo1}, {foo2}, .. {foo n}]
(1)
Each of the foo objects are dictionaries with the same internal structure - and so ideally i would have a single dictionary below guid where i could append... | [
"Not to throw a wrench your way, but have you looked into using MongoEngine? It sits on top of pymongo, and makes working with mongoDB a joy. Check it out.\nSo your mongoengine declaration would look like this:\nfrom mongoengine import * \n\nclass Foo(EmbeddedDocument): \... | [
1
] | [] | [] | [
"javascript",
"json",
"mongodb",
"python"
] | stackoverflow_0004877822_javascript_json_mongodb_python.txt |
Q:
Changing a comparison function to use keys for sorting
I have the following code written in Python 2.6, with a Task class that has an optional due_date:
class Task(models.Model):
due_date = models.DateField(null = True, blank = True)
@staticmethod
def compare_by_due_date(t1, t2):
return due_da... | Changing a comparison function to use keys for sorting | I have the following code written in Python 2.6, with a Task class that has an optional due_date:
class Task(models.Model):
due_date = models.DateField(null = True, blank = True)
@staticmethod
def compare_by_due_date(t1, t2):
return due_date_cmp(t1.due_date, t2.due_date)
def due_date_cmp(t1, t2):
... | [
"You can't compare objects of all different types (such as datetime.date to None) even though 2.x does allow more comparisons between different types than 3.x, so the direct comparison of due_dates won't work.\ndef due_date_key(t):\n return (t.due_date is None, t.due_date)\n\ntasks.sort(key=due_date_key)\n\nThis w... | [
4,
2
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0004879228_python_sorting.txt |
Q:
How do I provide the ability for multiple players to connect to my MUD?
I've recently created a short and simple Multi-User Dungeon. The things I've made are the engine of the game and the actual MUD itself, so when i click on the file it you can play the MUD. The problem I have is, I don't know how to connect i... | How do I provide the ability for multiple players to connect to my MUD? | I've recently created a short and simple Multi-User Dungeon. The things I've made are the engine of the game and the actual MUD itself, so when i click on the file it you can play the MUD. The problem I have is, I don't know how to connect it so that more than one player can play. Do you connect it to a server or so... | [
"Your MUD should be the server. \nFirst, you want to make sure that your engine can handle multiple people changing the dungeon state at the same time.\nNext, take a look at how to create a server. You probably want to look at the SocketServer class, for MUDs you probably want one of the TCP subclasses.\nEach user ... | [
1,
0
] | [] | [] | [
"mud",
"python",
"sockets"
] | stackoverflow_0002651829_mud_python_sockets.txt |
Q:
A Viable Solution for Word Splitting Khmer?
I am working on a solution to split long lines of Khmer (the Cambodian language) into individual words (in UTF-8). Khmer does not use spaces between words. There are a few solutions out there, but they are far from adequate (here and here), and those projects have fall... | A Viable Solution for Word Splitting Khmer? | I am working on a solution to split long lines of Khmer (the Cambodian language) into individual words (in UTF-8). Khmer does not use spaces between words. There are a few solutions out there, but they are far from adequate (here and here), and those projects have fallen by the wayside.
Here is a sample line of Khmer... | [
"The ICU library (that has Python and Java bindings) has a DictionaryBasedBreakIterator class that can be used for this. \n",
"The python with example filesaveas appears to recurse through the entire input string (for i in xrange(1, len(text) + 1)), stuffing the best results into the cache along the way; at each ... | [
3,
1,
1
] | [] | [] | [
"nlp",
"python",
"southeast_asian_languages",
"text_segmentation",
"word_boundary"
] | stackoverflow_0004861619_nlp_python_southeast_asian_languages_text_segmentation_word_boundary.txt |
Q:
UNIX shell script to call python
I have a python script that runs on three files in the following way
align.py *.wav *.txt *.TextGrid
However, I have a directory full of files that I want to loop through. The original author suggests creating a shell script to loop through the files.
The tricky part about the loo... | UNIX shell script to call python | I have a python script that runs on three files in the following way
align.py *.wav *.txt *.TextGrid
However, I have a directory full of files that I want to loop through. The original author suggests creating a shell script to loop through the files.
The tricky part about the loop is that I need to match three files ... | [
"Assuming you're using bash, here is a one-liner:\nfor f in *.wav; do align.py $f ${f%\\.*}.txt ${f%\\.*}.TextGrid; done\n\n",
"You could use glob.glob to list only the wav files, then construct the subprocess.Popen call like so:\nimport glob\nimport os\nimport subprocess\n\nfor wav_name in glob.glob('*.wav'):\n ... | [
3,
0
] | [] | [] | [
"loops",
"python",
"unix"
] | stackoverflow_0004879884_loops_python_unix.txt |
Q:
See anything wrong with my attempt to get Flask running? (mod_wsgi + virtualenv)
I have a VPS running a fresh install of Ubuntu 10.04 LTS. I'm trying to set up a live application using the Flask microframework, but it's giving me trouble. I took notes while I tried to get it running and here's my play-by-play in a... | See anything wrong with my attempt to get Flask running? (mod_wsgi + virtualenv) | I have a VPS running a fresh install of Ubuntu 10.04 LTS. I'm trying to set up a live application using the Flask microframework, but it's giving me trouble. I took notes while I tried to get it running and here's my play-by-play in an effort to pinpoint exactly where I went wrong.
INSTALLATION
http://flask.pocoo.org/d... | [
"Obviously, it cannot find your \"myapp\" package. You should add it to the path in your myapp.wsgi file like this:\nimport sys\nsys.path.append(DIRECTORY_WHERE_YOUR_PACKAGE_IS_LOCATED)\nfrom myapp import app\n\nAlso, if myapp module is a package, you should put and empty __init__.py file into its directory.\n",
... | [
8,
0
] | [] | [] | [
"apache2",
"flask",
"mod_wsgi",
"python",
"virtualenv"
] | stackoverflow_0004420218_apache2_flask_mod_wsgi_python_virtualenv.txt |
Q:
Python: How to use a list comprehension here?
I have data of the following form:
foos = [{'bar': [{'baz': 1}, {'baz': 2}]}, {'bar': [{'baz': 3}, {'baz': 4}]}, {'bar': [{'baz': 5}, {'baz': 6}]}]
I want a list comprehension that will yield:
[1, 2, 3, 4, 5, 6]
I'm not quite sure how to go about doing this. This so... | Python: How to use a list comprehension here? | I have data of the following form:
foos = [{'bar': [{'baz': 1}, {'baz': 2}]}, {'bar': [{'baz': 3}, {'baz': 4}]}, {'bar': [{'baz': 5}, {'baz': 6}]}]
I want a list comprehension that will yield:
[1, 2, 3, 4, 5, 6]
I'm not quite sure how to go about doing this. This sorta works:
>>> [[bar['baz'] for bar in foo['bar']] ... | [
"Instead of nesting list comprehensions, you can do it with two for .. in clauses in one list comprehension:\nIn [19]: [item['baz'] for foo in foos for item in foo['bar']]\nOut[19]: [1, 2, 3, 4, 5, 6]\n\nNote that \n[... for foo in foos for item in foo['bar']]\n\ntranslates roughly into\nfor foo in foos:\n for i... | [
10,
4,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0004879641_list_comprehension_python.txt |
Q:
Including DB function calls in python MySQLdb executemany()
When I try to run statements like:
cursor.executemany("""INSERT INTO `test` (`id`,`data`,`time_added`)
VALUES (%s, %s, NOW())""", [(i.id, i.data) for i in items])
MySQLdb seems to choke on the ) in NOW(), when it expands the list o... | Including DB function calls in python MySQLdb executemany() | When I try to run statements like:
cursor.executemany("""INSERT INTO `test` (`id`,`data`,`time_added`)
VALUES (%s, %s, NOW())""", [(i.id, i.data) for i in items])
MySQLdb seems to choke on the ) in NOW(), when it expands the list of rows to be inserted because it sees that parenthesis as the end... | [
"The method below is far from ideal, but, unfortunately, it is the only way I know.\nThe idea is to manually construct the SQL, using connection.literal to escape the arguments for you:\ncursor=connection.cursor()\nargs=[(1,'foo'),(2,'bar')]\nsql=('INSERT INTO `foo` (`fooid`,`data`,`time_added`) VALUES '\n +','... | [
1
] | [] | [] | [
"executemany",
"function",
"mysql",
"python"
] | stackoverflow_0004879606_executemany_function_mysql_python.txt |
Q:
Problem building cython program under Windows
I was starting to play with cython on my windows xp machine configured with Python 2.6. I tried to run the simple example on the Cython site but the conversion of the example .pyx file is immediately failing with a confusing error.
The .pyx file is
def say_hello_to(nam... | Problem building cython program under Windows | I was starting to play with cython on my windows xp machine configured with Python 2.6. I tried to run the simple example on the Cython site but the conversion of the example .pyx file is immediately failing with a confusing error.
The .pyx file is
def say_hello_to(name):
print("Hello, %s" % name)
setup.py looks li... | [
"(Reposting as an answer because it apparently solved the problem)\nJust a guess, but could it be having trouble with line endings? E.g. if the file has Unix '\\n' line endings, but on Windows it's expecting Windows '\\r\\n' line endings?\nOK, so it was the other way round. It expects '\\n' line endings, and the ed... | [
2
] | [] | [] | [
"cython",
"python",
"windows_xp"
] | stackoverflow_0004879895_cython_python_windows_xp.txt |
Q:
PyUnit with child processes
In some Python code, I fork and do some processing in a child process while the parent waits for it to exit. It doesn't exec after the fork.
I'm having a problem testing this code in PyUnit, because when the child process exits explicitly with sys.exit, it creates a PyUnit error.
This ... | PyUnit with child processes | In some Python code, I fork and do some processing in a child process while the parent waits for it to exit. It doesn't exec after the fork.
I'm having a problem testing this code in PyUnit, because when the child process exits explicitly with sys.exit, it creates a PyUnit error.
This code below produces the problem
c... | [
"All that sys.exit does is throw a SystemExit exception, that bubbles up as normal. However os._exit(0) will exit immediately and does not give any cleanup code a chance to run. This prevents PyUnit from doing anything, including failing the test. So in your test code you can trap SystemExit and call os._exit in... | [
1
] | [] | [] | [
"child_process",
"python",
"python_unittest"
] | stackoverflow_0004879859_child_process_python_python_unittest.txt |
Q:
Django - custom filter that calls a method
I know that you can't call a method using a filter because it does it based on the DB. So I'm trying to write a custom filter.
@staticmethod
def custom_filter(obj,method_name, arg=False):
for i in obj.objects.all():
if getattr(i, method_name)(... | Django - custom filter that calls a method | I know that you can't call a method using a filter because it does it based on the DB. So I'm trying to write a custom filter.
@staticmethod
def custom_filter(obj,method_name, arg=False):
for i in obj.objects.all():
if getattr(i, method_name)() == arg:
yield i
I can get thi... | [
"Filters aren't really part of your model class. \nThey're part of a Manager associated with your Model class. The default manager instance is named objects.\nYou can, however, add managers with fancy filters.\nhttp://docs.djangoproject.com/en/1.2/topics/db/managers/\nWhen you write your own, customized manager, ... | [
5
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004880307_django_django_models_python.txt |
Q:
Download javascript loaded pages
The example I'm looking at is morningstar.com.
Most of the contents are loaded through this javascript function. When I use wget, I don't get the data that actually show up in the browser (because wget doesn't interprets javascript code).
Is there some way to evaluate the javascri... | Download javascript loaded pages | The example I'm looking at is morningstar.com.
Most of the contents are loaded through this javascript function. When I use wget, I don't get the data that actually show up in the browser (because wget doesn't interprets javascript code).
Is there some way to evaluate the javascript and download the full page (with cm... | [
"For that specific page, maybe you could just wget the URL of the \"Export\" button? Obviously this will only work if you are trying to use the actual data that the site is displaying (since that is all that is in the extract).\nHere is a link directly to the .csv file: http://financials.morningstar.com/ajax/export... | [
3,
2
] | [] | [] | [
"javascript",
"python",
"wget"
] | stackoverflow_0004880622_javascript_python_wget.txt |
Q:
Python yes/no def
I'm using the example below:
APT command line interface-like yes/no input?
I want to make it its own definition as outlined then call it upon demand, like this:
def log_manager():
question = "Do you wish to continue?"
choice = query_yes_no_quit(question, default="yes")
if ch... | Python yes/no def | I'm using the example below:
APT command line interface-like yes/no input?
I want to make it its own definition as outlined then call it upon demand, like this:
def log_manager():
question = "Do you wish to continue?"
choice = query_yes_no_quit(question, default="yes")
if choice == 'y':
... | [
"The function returns True/False. So use if choice:\nBtw, you could have easily found out the solution on your own by adding print choice ;)\n",
"Use:\nif choice:\n print(\"you entered y\")\nelse:\n print(\"not working\")\n\nthe function returns True / False, not \"y\" / \"n\".\n"
] | [
9,
1
] | [] | [] | [
"prompt",
"python"
] | stackoverflow_0004880724_prompt_python.txt |
Q:
Using StaticGenerator to generate static HTML from a Django project
I'm trying to generate static HTML for a site I've built in Django. What I've come up with so far is StaticGenerator. It looks to me like it should be similar to the example from the github page, but I have written the code below and it gives th... | Using StaticGenerator to generate static HTML from a Django project | I'm trying to generate static HTML for a site I've built in Django. What I've come up with so far is StaticGenerator. It looks to me like it should be similar to the example from the github page, but I have written the code below and it gives the error below.
Code:
sys.path.insert(0, os.path.abspath(os.path.join(os.p... | [
"OK, upon going through your trace, I'm going to guess your settings.WEB_ROOT is a tuple.\nRelevant lines:\n# web root set\nself.web_root = getattr(self.settings, 'WEB_ROOT')\n\n# web root used \nfilename = self.fs.join(self.web_root, path.lstrip('/')).encode('utf-8')\n\n# breaks on real os.path.join\nreturn os.pat... | [
1
] | [] | [] | [
"django",
"html",
"python",
"static"
] | stackoverflow_0004880739_django_html_python_static.txt |
Q:
Increasing the maximum number of connections per host of QtWebKit
Question:
How can the default limit of 6 connections per host be increased in QtWebKit?
Use case:
I've multiple QtWebKit (QWebView) panes displayed by a PySide application. (PyQt would also work the same way.) The default connection limit of 6 conne... | Increasing the maximum number of connections per host of QtWebKit | Question:
How can the default limit of 6 connections per host be increased in QtWebKit?
Use case:
I've multiple QtWebKit (QWebView) panes displayed by a PySide application. (PyQt would also work the same way.) The default connection limit of 6 connections per host quickly became an obstacle, since persistent HTTP conne... | [
"There's no API for this. It's hardcoded in qhttpnetworkconnection.cpp in the following way\n#ifdef Q_OS_SYMBIAN\nconst int QHttpNetworkConnectionPrivate::defaultChannelCount = 3;\n#else\nconst int QHttpNetworkConnectionPrivate::defaultChannelCount = 6;\n#endif\n\nYou can change it and build Qt yourself or you can ... | [
6
] | [] | [] | [
"pyqt",
"pyside",
"python",
"qt",
"webkit"
] | stackoverflow_0004879919_pyqt_pyside_python_qt_webkit.txt |
Q:
Is it possible to set blob download sizes in GAE apps now that the Content-Length header is disallowed?
After the AppEngine API update that came out a few weeks ago, the wonderful "Disallowed HTTP Response Headers" section appeared in the Python Response class documentation here, which explains that the listed hea... | Is it possible to set blob download sizes in GAE apps now that the Content-Length header is disallowed? | After the AppEngine API update that came out a few weeks ago, the wonderful "Disallowed HTTP Response Headers" section appeared in the Python Response class documentation here, which explains that the listed headers cannot be set for security purposes.
That is all well and good except that now all of my blob downloads ... | [
"Are your files transferred with \nTransfer-Encoding: Chunked\n\nThen it is possible over HTTP to send these files without the Content-Length: header. See the HTTP/1.1 RFC on Chunked Transfer Coding. I guess you should be able to define your own handler for the methods such as get etc, and create yourself the HTTP ... | [
1
] | [] | [] | [
"content_length",
"google_app_engine",
"http_headers",
"python"
] | stackoverflow_0004524107_content_length_google_app_engine_http_headers_python.txt |
Q:
Convert google email audit attachment to an email
Google has an email auditing feature that will allow a google apps admin to bcc incoming and outgoing email (lots of options) to another account. The problem is that the email is sent the other account as an attachment. The attachment is the full email, headers and... | Convert google email audit attachment to an email | Google has an email auditing feature that will allow a google apps admin to bcc incoming and outgoing email (lots of options) to another account. The problem is that the email is sent the other account as an attachment. The attachment is the full email, headers and all. I would like to convert this to an email and send... | [
"\nNot to my knowledge, but I don't know that much.\nofflineimap is written in Python and performs both IMAP downloads and uploads. Python comes with an email parser and imap client. Those might be a good places to start.\n\n"
] | [
0
] | [] | [] | [
"audit",
"email",
"google_apps",
"imap",
"python"
] | stackoverflow_0004881013_audit_email_google_apps_imap_python.txt |
Q:
Werkzeug without ORM
How do I use the Werkzeug framework without any ORM like SQLAlchemy? In my case, it's a lot of effort to rewrite all the tables and columns in SQLAlchemy from existing tables & data.
How do I query the database and make an object from the database output?
In my case now, I use Oracle with cx_O... | Werkzeug without ORM | How do I use the Werkzeug framework without any ORM like SQLAlchemy? In my case, it's a lot of effort to rewrite all the tables and columns in SQLAlchemy from existing tables & data.
How do I query the database and make an object from the database output?
In my case now, I use Oracle with cx_Oracle. If you have a solut... | [
"SQLAlchemy supports reflection so you don't have to do that. Take a look at the autoload parameter of Table, you can even make this work with the ORM.\n",
"Is it a problem to use normal DB API, issue regular SQL queries, etc? cx_Oracle even has connection pooling biolt in to help you manage connections.\n",
"m... | [
2,
0,
0
] | [] | [] | [
"orm",
"python",
"werkzeug"
] | stackoverflow_0004838528_orm_python_werkzeug.txt |
Q:
Python: Is it possible to change the Windows command line shell current directory without changing the actual current directory?
I'm using os.system() to do Windows command line shell executions. I would like to change the Windows cmd current directory. Here's one way of doing it:
os.chdir('newPath')
But chdir() ... | Python: Is it possible to change the Windows command line shell current directory without changing the actual current directory? | I'm using os.system() to do Windows command line shell executions. I would like to change the Windows cmd current directory. Here's one way of doing it:
os.chdir('newPath')
But chdir() will also change the actual Python current working directory. I don't want to change the actual Python working directory because I wan... | [
"The subprocess module is intended to replace os.system. \nAmong other things, it gives you subprocess.Popen(), which takes a cwd argument to specify the working directory for the spawned process (for exactly your situation).\nSee: http://docs.python.org/library/subprocess.html\nExample usage replacing os.system:... | [
7,
1,
1
] | [] | [] | [
"cmd",
"python",
"working_directory"
] | stackoverflow_0004881312_cmd_python_working_directory.txt |
Q:
embedding a dynamic 3d object to your website
im sorry if i keep asking the same question but i really really need to figure this one out.
the problems i currently have are:
1. a python library that will allow me to create a custom dynamic 3d model
---> i tried vpython (extremely good) but found that images I ... | embedding a dynamic 3d object to your website | im sorry if i keep asking the same question but i really really need to figure this one out.
the problems i currently have are:
1. a python library that will allow me to create a custom dynamic 3d model
---> i tried vpython (extremely good) but found that images I make there cannot exactly be embedded in a site
a ... | [
"With html5/canvas2d you can get reasonable stuff in realtime...\nfor example see this simple icosahedron (with a readable source) or this compressed 4k demo I wrote as experiments.\nthey work on Firefox, Safari, Chrome, Opera and Nexus One browsers. I didn't test other browsers.\nAn interactive version of the icos... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004881424_python.txt |
Q:
Python: Select Only Parts of an input?
Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.ran... | Python: Select Only Parts of an input? | Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chos... | [
"Try this approach:\ninput_is_valid = False\nwhile not input_is_valid:\n comma_separated_numbers = raw_input(\"Please enter a list of 5 numbers,separated by commas: \")\n numbers = [int(x.strip()) for x in comma_separated_numbers.split(\",\")]\n if len(numbers) != 5:\n print \"Please enter exactly 5... | [
2,
0,
0
] | [] | [] | [
"input",
"python",
"random",
"select"
] | stackoverflow_0004881139_input_python_random_select.txt |
Q:
Django: Normalizing user-submitted model data for display in a template
I save user-submitted data in a model. I currently have template filters to normalize the data. For example:
Mcjunkin -> McJunkin
john and beth -> John & Beth
K.j. Johnson -> K.J. Johnson
Can anyone suggest a way to do this without using temp... | Django: Normalizing user-submitted model data for display in a template | I save user-submitted data in a model. I currently have template filters to normalize the data. For example:
Mcjunkin -> McJunkin
john and beth -> John & Beth
K.j. Johnson -> K.J. Johnson
Can anyone suggest a way to do this without using template filters every time I display these model fields?
I was thinking of perha... | [
"Bravo. We do that also.\nWe have the \"normalized-for-display\" fields as properties. As well as other things like derived calculations.\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"python"
] | stackoverflow_0004881455_django_django_models_django_templates_python.txt |
Q:
Django: ModelMultipleChoiceField display description vs object
I am trying to show ModelMultipleChoiceFields as CheckboxSelectMultiple. Right now it does render the checkboxes, but with the objects. I'd like to show the object description so the user knows what they are selecting.
How do I iterate over the foodsty... | Django: ModelMultipleChoiceField display description vs object | I am trying to show ModelMultipleChoiceFields as CheckboxSelectMultiple. Right now it does render the checkboxes, but with the objects. I'd like to show the object description so the user knows what they are selecting.
How do I iterate over the foodstyles to pull that data? This is what I tried so far but that is throw... | [
"It sounds to me like you need to implement unicode(self) on your Model object, and return whatever string you want to be displayed in the form.\n"
] | [
3
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004881500_django_django_forms_python.txt |
Q:
Django - reverse lookups with ManyToManyField
I'm trying to follow the code from the django docs:
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models... | Django - reverse lookups with ManyToManyField | I'm trying to follow the code from the django docs:
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
... | [
"First, are you using a through Model? You have through in there, but you don't have it listed. If you aren't you don't need it.\nI would add a related_name, like so:\nclass Trip(models.Model):\n members = models.ManyToManyField(User,blank=True,null=True, related_name='user_trips')\n\nThen you should be able to ... | [
18
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004881783_django_django_models_python.txt |
Q:
Django static files problem
Duplicate of Django staticfiles app help
I'm using Django 1.3 beta and the static files app is confusing. In development mode it is meant to automatically serve files from the STATIC_URL path.
From http://docs.djangoproject.com/en/dev/howto/static-files/
If you're using the built-in
... | Django static files problem | Duplicate of Django staticfiles app help
I'm using Django 1.3 beta and the static files app is confusing. In development mode it is meant to automatically serve files from the STATIC_URL path.
From http://docs.djangoproject.com/en/dev/howto/static-files/
If you're using the built-in
development server (the runserv... | [
"If you want to serve up the static files while using the built in Django server you will need to add a urlpattern. This is what I do (add this after all your other patterns:\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(.*)$', 'django.views.static.serve', {'document_root': settings... | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004730716_django_python.txt |
Q:
Python project and package directories layout
I created a project in python, and I'm curious about how packages work in python.
Here is my directory layout:
top-level dir
\ tests
__init__.py
\ examples
__init__.py
example.py
module.py
How would I go about including module.py in my example.py modu... | Python project and package directories layout | I created a project in python, and I'm curious about how packages work in python.
Here is my directory layout:
top-level dir
\ tests
__init__.py
\ examples
__init__.py
example.py
module.py
How would I go about including module.py in my example.py module. I know I could set PYTHONPATH to the top-level... | [
"Python packages are very simple: a package is any directory under any entry in sys.path that has an __init__.py file. However, a module is only considered to be IN a package if it is imported via a relative import such as import package.module or from package import module. Note that this means that in general, ... | [
9,
1
] | [] | [] | [
"package",
"python"
] | stackoverflow_0004881897_package_python.txt |
Q:
Converting WXpython Bitmap to an Image, then Back Again
I have a function that I use to create a rectangular bitmap, in WXPython. I'd like to convert it to an image. Then back to a bitmap. How would one go about this?
Snippet:
def make_shape(self, w, h, r ):
maskc = wx.Color(0, 0, 0)
shownc ... | Converting WXpython Bitmap to an Image, then Back Again | I have a function that I use to create a rectangular bitmap, in WXPython. I'd like to convert it to an image. Then back to a bitmap. How would one go about this?
Snippet:
def make_shape(self, w, h, r ):
maskc = wx.Color(0, 0, 0)
shownc = wx.Color(0, 0, 1)
bitmap = wx.EmptyBitmap(w, h)
... | [
"Use wx.ImageFromBitmap(bitmap) and wx.BitmapFromImage(image)\n"
] | [
2
] | [] | [] | [
"bitmap",
"image",
"python",
"wxpython"
] | stackoverflow_0004882192_bitmap_image_python_wxpython.txt |
Q:
Python method or class to compare two video files?
I'm trying to write a program to compare files and show the duplicates in python. Anyone know any good functions or methods related to this? I am sorta lost...
A:
If you're just looking for exact duplicates, do an MD5 hash on both and see if they match:
import h... | Python method or class to compare two video files? | I'm trying to write a program to compare files and show the duplicates in python. Anyone know any good functions or methods related to this? I am sorta lost...
| [
"If you're just looking for exact duplicates, do an MD5 hash on both and see if they match:\nimport hashlib\n\nfile1 = open('file1.avi', 'r').read()\nfile2 = open('file2.avi', 'r').read()\n\nif hashlib.sha512(file1).hexdigest() == hashlib.sha512(file2).hexdigest():\n print 'They are the same'\nelse:\n print 'They... | [
3,
1,
0
] | [] | [] | [
"compare",
"file",
"python"
] | stackoverflow_0004880750_compare_file_python.txt |
Q:
Decorate \ delegate a File object to add functionality
I've been writing a small Python script that executes some shell commands using the subprocess module and a helper function:
import subprocess as sp
def run(command, description):
"""Runs a command in a formatted manner. Returns its return code."""
sta... | Decorate \ delegate a File object to add functionality | I've been writing a small Python script that executes some shell commands using the subprocess module and a helper function:
import subprocess as sp
def run(command, description):
"""Runs a command in a formatted manner. Returns its return code."""
start=datetime.datetime.now()
sys.stderr.write('%-65s' % de... | [
"1 and 2 are reasonable solutions, but overriding write() won't be enough.\nThe problem is that Popen needs file handles to attach to the process, so Python file objects doesn't work, they have to be OS level. To solve that you have to have a Python object that has a os level file handle. The only way I can think o... | [
14,
1,
0,
0,
0
] | [] | [] | [
"design_patterns",
"logging",
"python",
"subprocess"
] | stackoverflow_0004713932_design_patterns_logging_python_subprocess.txt |
Q:
JSON usage in Python
I'm looking through the json documentation and I'm trying to understand how to actually convert a Python object into JSON data, and then convert that data back into a Python object. I understand you can pass lists, dicts, and tuples of "primitives" like in the example at the top, but I tried ... | JSON usage in Python | I'm looking through the json documentation and I'm trying to understand how to actually convert a Python object into JSON data, and then convert that data back into a Python object. I understand you can pass lists, dicts, and tuples of "primitives" like in the example at the top, but I tried creating a very minimal ob... | [
"The following snipped of code illustrates several aspects of working with JSON in Python 3. Take note of the JSONEncoder class and the implementation of encoding decimal and datetime.\nimport json\nfrom decimal import Decimal\nfrom datetime import datetime, date\n\nclass JSONEncoder(json.JSONEncoder):\n def defa... | [
0,
0
] | [] | [] | [
"coding_style",
"json",
"python"
] | stackoverflow_0004882189_coding_style_json_python.txt |
Q:
Parsing strings in python
So my problem is this, I have a file that looks like this:
[SHIFT]this isrd[BACKSPACE][BACKSPACE] an example file[SHIFT]1
This would of course translate to
' This is an example file!'
I am looking for a way to parse the original content into the end content, so that a [BACKSPACE] will ... | Parsing strings in python | So my problem is this, I have a file that looks like this:
[SHIFT]this isrd[BACKSPACE][BACKSPACE] an example file[SHIFT]1
This would of course translate to
' This is an example file!'
I am looking for a way to parse the original content into the end content, so that a [BACKSPACE] will delete the last character(space... | [
"Here's one way, but it feels hackish. There's probably a better way.\ndef process_backspaces(input, token='[BACKSPACE]'):\n \"\"\"Delete character before an occurence of \"token\" in a string.\"\"\"\n output = ''\n for item in (input+' ').split(token):\n output += item\n output = output[:-1]... | [
1,
1,
1,
0,
0
] | [] | [] | [
"parsing",
"python",
"string"
] | stackoverflow_0004882249_parsing_python_string.txt |
Q:
Python, splitting strings
I have a large string text file, I would like to split the string every 117 characters and put the next 117 chars on a newline, and so on until the end of the file.
I tried this:`s = """
I have removed the string for visibility reasons
"""
space = """
"""
file = open('testoutput.txt', 'w... | Python, splitting strings | I have a large string text file, I would like to split the string every 117 characters and put the next 117 chars on a newline, and so on until the end of the file.
I tried this:`s = """
I have removed the string for visibility reasons
"""
space = """
"""
file = open('testoutput.txt', 'w')
while s:
print s[:10]
... | [
"while s:\n print s[:117]\n s = s[117:]\n\n",
"You can either split a buffer using the regular slicing syntax, or you may opt to split the file directly while reading it. This is an example of the second approach:\nwith open(r\"/path/to/some/file\") as input_file:\n line = input_file.read(117)\n while... | [
6,
3
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0004882569_python_split_string.txt |
Q:
Import Python lib in C#
There is an existing python lib which i have to instantiate in my C# code.
Which is the best possible way to do so? And how?
I am not much familiar with python, so IronPython, py2exe confused me big time.
Please Help.
A:
You'll almost certainly be better off finding a C#/.NET alternative ... | Import Python lib in C# | There is an existing python lib which i have to instantiate in my C# code.
Which is the best possible way to do so? And how?
I am not much familiar with python, so IronPython, py2exe confused me big time.
Please Help.
| [
"You'll almost certainly be better off finding a C#/.NET alternative to that library. What is it?\nIf you do really need to do this your best option will be IronPython. There are a few guides to embedding IronPython code in C#, such as this one.\n"
] | [
4
] | [] | [] | [
"c#",
"import",
"python"
] | stackoverflow_0004882674_c#_import_python.txt |
Q:
Adding glowy effect to an image
I would like to permanently add a glow effect to a bunch of images. preferably using either Ruby or Python (open to other ideas as well).
Example of what I'm looking to do (see top half):
A:
This would be as simple as using imagemagick or gd to composite a PNG with transparency on... | Adding glowy effect to an image | I would like to permanently add a glow effect to a bunch of images. preferably using either Ruby or Python (open to other ideas as well).
Example of what I'm looking to do (see top half):
| [
"This would be as simple as using imagemagick or gd to composite a PNG with transparency on top of your target image. Imagemagick's command line Composite tool will get you there quite painlessly.\nIf you're displaying these on a webpage, though, I'd recommend that you just use position: absolute to overlay a glow ... | [
4
] | [] | [] | [
"image_processing",
"imagemagick",
"python",
"ruby"
] | stackoverflow_0004882732_image_processing_imagemagick_python_ruby.txt |
Q:
Django - check if list contains something in a template
I'm trying to check if an item is in a list (set) inside of a template.
I've found this question here:
Is it possible, in a django template, to check if an object is contained in a list
however the solution isn't working for me.
I'm trying this:
{% if trip in... | Django - check if list contains something in a template | I'm trying to check if an item is in a list (set) inside of a template.
I've found this question here:
Is it possible, in a django template, to check if an object is contained in a list
however the solution isn't working for me.
I'm trying this:
{% if trip in request.user.trip_set.all %}
where trip is an instance of a... | [
"request.user.trip_set.all is not a list but a queryset. I think it is the reason of your problem. You can try to change that into a list with the dictsort template filter.\n{% if trip in request.user.trip_set.all|dictsort:\"id\" %}\n\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"django_templates",
"python"
] | stackoverflow_0004882146_django_django_models_django_templates_python.txt |
Q:
haystack search for non primary field
I would like to have any option of searching an indexed model from two different fields. For example, sometimes search by name and other times search by occupation. Does someone know the right approach to take? This is my current search_indexes.py file:
class JobIndex(indexe... | haystack search for non primary field | I would like to have any option of searching an indexed model from two different fields. For example, sometimes search by name and other times search by occupation. Does someone know the right approach to take? This is my current search_indexes.py file:
class JobIndex(indexes.SearchIndex):
text = indexes.CharFiel... | [
"The right approach is to use a SearchQuerySet with filters: http://docs.haystacksearch.org/dev/searchqueryset_api.html\nIn your case, it'd look something like:\nfrom haystack.query import SearchQuerySet\n\nsqs = SearchQuerySet()\n\n# Find people named Bob\nsqs.filter(name=\"Bob\")\n# Find people who are developers... | [
0
] | [] | [] | [
"django",
"django_haystack",
"python"
] | stackoverflow_0004882066_django_django_haystack_python.txt |
Q:
Reference objects in containing package?
I have a package, spam, that contains a contains the variable _eggs in __init__.py In the same package, in boiler.py, I have the class Boiler.
In Boiler, I want to refer to _eggs in the package’s __init__.py file. Is there a way that I can do this?
A:
The most appropriat... | Reference objects in containing package? | I have a package, spam, that contains a contains the variable _eggs in __init__.py In the same package, in boiler.py, I have the class Boiler.
In Boiler, I want to refer to _eggs in the package’s __init__.py file. Is there a way that I can do this?
| [
"The most appropriate way to retrieve that value is via an explicit relative import:\nfrom . import _eggs\n\nHowever, one thing to keep in mind is that the following command line invocation will then fail to work:\npython spam/boiler.py\n\nThe reason this won't work is the interpreter doesn't recognise any directly... | [
1
] | [] | [] | [
"namespaces",
"python",
"python_3.x"
] | stackoverflow_0004882960_namespaces_python_python_3.x.txt |
Q:
python regular expression
whats the difference between '{m}' and '{m,n}?' in http://docs.python.org/library/re.html it says '{m,n}?' matches numbers in range m to n times, but it is not a greedy search. Therefore if its not a greedy search wouldn't it only match up to m no matter what?
A:
{m,n}? will preferably ... | python regular expression | whats the difference between '{m}' and '{m,n}?' in http://docs.python.org/library/re.html it says '{m,n}?' matches numbers in range m to n times, but it is not a greedy search. Therefore if its not a greedy search wouldn't it only match up to m no matter what?
| [
"{m,n}? will preferably match only m repetitions, but it will expand as needed up to n repetitions if that's necessary for a longer match.\nCompare ^x{2}y$ and ^x{2,4}?y$:\nThe former will fail on xxxy whereas the latter will match.\nTo summarize:\nx{m}: Match x exactly m times.\nx{m,n}: Try to match x n times, but... | [
14,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004883270_python_regex.txt |
Q:
How to parse C++ source in Python?
We want to parse our huge C++ source tree to gain enough info to feed to another tool to make diagrams of class and object relations, discern the overall organization of things etc.
My best try so far is a Python script that scans all .cpp and .h files, runs regex searches to ... | How to parse C++ source in Python? | We want to parse our huge C++ source tree to gain enough info to feed to another tool to make diagrams of class and object relations, discern the overall organization of things etc.
My best try so far is a Python script that scans all .cpp and .h files, runs regex searches to try to detect class declarations, method... | [
"I'll simply recommend Clang.\nIt's a C++ library-based compiler designed with ease of reuse in mind. It notably means that you can use it solely for parsing and generating an Abstract Syntax Tree. It takes care of all the tedious operator overloading resolution, template instantiation and so on.\nClang exports a C... | [
11,
6,
3,
1,
1,
0,
0
] | [] | [] | [
"c++",
"code_analysis",
"parsing",
"python"
] | stackoverflow_0004881377_c++_code_analysis_parsing_python.txt |
Q:
What's the difference between database object and cursor object in pysqlite2?
In Python one may interact with an sqlite database using the pysqlite2 class.
from pysqlite2 import dbapi2 as sqlite
One way to send commands to the database is through the database object:
db = sqlite.connect('mydb.sqlite')
db.execute('... | What's the difference between database object and cursor object in pysqlite2? | In Python one may interact with an sqlite database using the pysqlite2 class.
from pysqlite2 import dbapi2 as sqlite
One way to send commands to the database is through the database object:
db = sqlite.connect('mydb.sqlite')
db.execute('CREATE TABLE IF NOT EXISTS t1(a, b, c)')
another way is through a cursor:
cur = db... | [
"The connection.execute method is an SQLite API extension; it's not specified by DB-API: http://www.python.org/dev/peps/pep-0249/. It's just shorthand for creating a cursor and calling execute on it, returning the cursor.\nYou shouldn't use it if you want to be sure that your code will work with other DB-API-based... | [
3
] | [] | [] | [
"cursor",
"database",
"pysqlite",
"python",
"sqlite"
] | stackoverflow_0004883450_cursor_database_pysqlite_python_sqlite.txt |
Q:
yacc fails to reduce (Python Lex-Yacc)
I'm trying to write a fairly simple grammar with PLY (python implementation of yacc), and am having trouble getting yacc to reduce strings of tokens when I want it to.
I want to interpret a series of commands that take different kinds of arguments. Each different kind of arg... | yacc fails to reduce (Python Lex-Yacc) | I'm trying to write a fairly simple grammar with PLY (python implementation of yacc), and am having trouble getting yacc to reduce strings of tokens when I want it to.
I want to interpret a series of commands that take different kinds of arguments. Each different kind of argument has a different token. The string of t... | [
"You need to include additional rules for handling multiple instructions, so yacc will know what to do with that second COMMAND token. Something like below should work.\ninstructions : instructions '\\n' instruction\n | instruction\n\ninstruction : COMMAND VARARG VARARG STRARG\n { do stuff }\... | [
1
] | [] | [] | [
"grammar",
"lex",
"ply",
"python",
"yacc"
] | stackoverflow_0004877277_grammar_lex_ply_python_yacc.txt |
Q:
Trouble reading JSON object in Python
I have a JSON object that I am trying to read using Python but I am having some issues. I have a file named "test.txt" which contains the received JSON object. The contents of "test.txt" are as follows:
{ "Sections": {"Now": "Thursday 3 February 2011 08:31", "Section": [ { "A... | Trouble reading JSON object in Python | I have a JSON object that I am trying to read using Python but I am having some issues. I have a file named "test.txt" which contains the received JSON object. The contents of "test.txt" are as follows:
{ "Sections": {"Now": "Thursday 3 February 2011 08:31", "Section": [ { "Article": [ {"audioCounter": 0, "commentsCou... | [
"In your for i in d loop, you are looping over the keys of a dictionary. The dictionary only contains one top level key, namely 'Sections', which is why you see only that output.\nI do not fully understand the structure of your JSON, but it appears you want something like this:\nfor aritcle in d['Sections']['Sectio... | [
5,
0,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0004883751_json_python.txt |
Q:
Shortcut for super(type(self), self)
I often do this when overriding a method in a sub class:
def method_x(self):
x = super(type(self), self).method_x()
[Some extra code]
return x
My question is: Is there a short cut for super(type(self), self) ?
A:
Don't do that: if super could just use type(self)... | Shortcut for super(type(self), self) | I often do this when overriding a method in a sub class:
def method_x(self):
x = super(type(self), self).method_x()
[Some extra code]
return x
My question is: Is there a short cut for super(type(self), self) ?
| [
"Don't do that: if super could just use type(self) as its first argument then it wouldn't have been written to take two arguments in the first place. You must pass the actual class here not an expression which could change if the class has been subclassed.\nThe first argument to super needs to be the class containi... | [
20
] | [] | [] | [
"python"
] | stackoverflow_0004883822_python.txt |
Q:
How can you add the feature "see other computer on this local network"?
Let's say I have a desktop software called super-dupper-app. I want it to be able to detect all computers on this local network with super-dupper-app running.
General pointers really appreciated. Bonus points for Python pointers or snippets.
... | How can you add the feature "see other computer on this local network"? | Let's say I have a desktop software called super-dupper-app. I want it to be able to detect all computers on this local network with super-dupper-app running.
General pointers really appreciated. Bonus points for Python pointers or snippets.
| [
"The short answer is you use multicast packets in python. I believe there are also python bindings for avahi, which implements \"ZeroConf\" aka mDNS/DNS-SD, which is implemented on top of multicast and would save you having to reinvent the wheel as well as being more standard.\nMulticast sits somewhere in between u... | [
3
] | [] | [] | [
"autodiscovery",
"local",
"networking",
"python"
] | stackoverflow_0004884065_autodiscovery_local_networking_python.txt |
Q:
Calling gdc/dmd shared libraries from Python using ctypes
I've been playing around with the rather excellent ctypes library in Python recently. What i was wondering is, is it possible to create shared D libraries and call them in the same way. I'm assuming i would compile the .so files using the -fPIC with dmd o... | Calling gdc/dmd shared libraries from Python using ctypes | I've been playing around with the rather excellent ctypes library in Python recently. What i was wondering is, is it possible to create shared D libraries and call them in the same way. I'm assuming i would compile the .so files using the -fPIC with dmd or gdc and call them the same way using the ctypes library.
Has ... | [
"In this case Windows dlls should work just fine. I'm not sure about the situation on Linux, there are some issues with shared libraries which will be addressed as soon as the 64 bit port of dmd is finished.\nNote that you have to export your functions as extern(C) or extern(Windows) to access them from ctypes.\n"
... | [
0
] | [] | [] | [
"ctypes",
"d",
"python"
] | stackoverflow_0000793125_ctypes_d_python.txt |
Q:
how to convert list of dictonaries into ....?
li = [[{'foo': '1',
'date': datetime.date(2011, 2, 1),
'bar': 'a'},
{'foo': '2',
'date': datetime.date(2011, 2, 1),
'bar': 'b'}],
[{'foo': '2',
'date': datetime.date(2011, 1, 30),
'bar': 'f'},
{'foo': '5',
'date': datetime.date(2011, 1, 30),
... | how to convert list of dictonaries into ....? | li = [[{'foo': '1',
'date': datetime.date(2011, 2, 1),
'bar': 'a'},
{'foo': '2',
'date': datetime.date(2011, 2, 1),
'bar': 'b'}],
[{'foo': '2',
'date': datetime.date(2011, 1, 30),
'bar': 'f'},
{'foo': '5',
'date': datetime.date(2011, 1, 30),
'bar': 'g'}]]
I want to convert this list into
... | [
"Something like this?\ndd = []\nfor l in li:\n d = {'date':l[0]['date'], 'values':[]}\n for ll in l:\n d['values'].append({'foo':ll['foo'], 'bar':ll['bar']})\n dd.append(d)\n\n\n\nprint dd\n\n[{'date': datetime.date(2011, 2, 1),\n 'values': [{'bar': 'a', 'foo': '1'}, {'bar': 'b', 'foo': '2'}]},\n {... | [
2,
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004883860_list_python.txt |
Q:
Use of python script instead of VBA in Excel
I am new to python and its workings.
I have an excel spreadsheet which was got using some VBA's.
Now I want to invoke Python to do some of the jobs...
My question then is: How can I use python script instead of VBA in an excel spreadsheet?
An example of such will be app... | Use of python script instead of VBA in Excel | I am new to python and its workings.
I have an excel spreadsheet which was got using some VBA's.
Now I want to invoke Python to do some of the jobs...
My question then is: How can I use python script instead of VBA in an excel spreadsheet?
An example of such will be appreciated.
| [
"Resolver One, or Dirigible:\nhttp://www.resolversystems.com/products/\n",
"I've always done the manipulation of Excel spreadsheets and Word documents with standalone scripts which use COM objects to manipulate the documents. I've never come across a good use case for putting Python into a spreadsheet in place of... | [
1,
0
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0004829509_excel_python.txt |
Q:
Unable to use in the same application a QWebPage twice
I'm trying to create a little web server that loads, using webkit, an URL to extract some data from the web page (eg: title, images sizes...).
I'm using PyQt4 to access from python to webkit. For each request, I'm creating a QThread that:
- creates an QWebPage... | Unable to use in the same application a QWebPage twice | I'm trying to create a little web server that loads, using webkit, an URL to extract some data from the web page (eg: title, images sizes...).
I'm using PyQt4 to access from python to webkit. For each request, I'm creating a QThread that:
- creates an QWebPage object,
- run an event loop
- when the loading of the webpa... | [
"I've managed to fix the issue: creating the QWebPage in the GUI thread (the thread of QApplication event loop) fixes the issue.\nIt seems the second time a QWebPage is used, it tries to access to the browser cache (even if it has been disabled by configuration). But if the first QWebPage was not created in the mai... | [
2
] | [] | [] | [
"pyqt4",
"python",
"qt",
"qt4",
"qtwebkit"
] | stackoverflow_0004876649_pyqt4_python_qt_qt4_qtwebkit.txt |
Q:
Errors while doing Binary Search in Python . What is wrong with the code?
import math
def BinarySearch( A , val , low , high ):
if high < low :
return -1 #not found
mid = low + (high - low ) /2
if A[mid] > val:
return BinarySearch(A,val , low , high )
if A[mid] < val :
r... | Errors while doing Binary Search in Python . What is wrong with the code? | import math
def BinarySearch( A , val , low , high ):
if high < low :
return -1 #not found
mid = low + (high - low ) /2
if A[mid] > val:
return BinarySearch(A,val , low , high )
if A[mid] < val :
return BinarySearch(A,val,low,high)
else:
return mid #found
A = ... | [
"def BinarySearch( A , val , low , high ):\n if high < low :\n return -1 #not found \n mid = low + (high - low ) /2\n if A[mid] > val:\n return BinarySearch(A, val ,... | [
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004885776_python.txt |
Q:
How to make super() work by manually filling the __class__ cell?
In Python 3 one can use super() instead of super(MyClass, self), but this only works in methods that were defined inside the class. As described in Michele Simionato's article the following example does not work:
def __init__(self):
print('callin... | How to make super() work by manually filling the __class__ cell? | In Python 3 one can use super() instead of super(MyClass, self), but this only works in methods that were defined inside the class. As described in Michele Simionato's article the following example does not work:
def __init__(self):
print('calling __init__')
super().__init__()
class C(object):
__init__ = _... | [
"Seriously: you really don't want to do this.\nBut, it's useful for advanced users of Python to understand this, so I'll explain it.\nCells and freevars are the values assigned when a closure is created. For example,\ndef f():\n a = 1\n def func():\n print(a)\n return func\n\nf returns a closure ba... | [
27,
2,
2
] | [] | [] | [
"metaprogramming",
"python",
"python_3.x",
"super"
] | stackoverflow_0004885168_metaprogramming_python_python_3.x_super.txt |
Q:
rich web client vs thin web client
I have one design decision to make.
In my web(ajax) application we need to decide where should we put user interface logic ?
Should It be completely loaded via javascript ( pure single page ) . and Only data comes and go.
or
Should server send some format (XML) which transla... | rich web client vs thin web client | I have one design decision to make.
In my web(ajax) application we need to decide where should we put user interface logic ?
Should It be completely loaded via javascript ( pure single page ) . and Only data comes and go.
or
Should server send some format (XML) which translated via javascript to dynamically create... | [
"IMO, it depends mostly on what kind of application it is. Is it used more like a desktop application? Then single page might work well. Having an Ajax-client to a large extent has the same drawbacks as using frames but that isn't a big problem in desktop-style applications. \nYour second option works better if it ... | [
2,
2,
1,
0
] | [] | [] | [
"ajax",
"pyjamas",
"python",
"user_interface",
"web_applications"
] | stackoverflow_0004842449_ajax_pyjamas_python_user_interface_web_applications.txt |
Q:
About pyjamas maturity vs GWT maturity (with short dead lines) for a web application
I love both, python and Java and I have this first 'serious' web application project that I would like to carry out.
I find it hard to choose between pyjamas + django and GWT + Hibernate.
In fact, from my beginner point of view, ... | About pyjamas maturity vs GWT maturity (with short dead lines) for a web application | I love both, python and Java and I have this first 'serious' web application project that I would like to carry out.
I find it hard to choose between pyjamas + django and GWT + Hibernate.
In fact, from my beginner point of view, it seems like the python world is more suitable for a quickly-developed and fun web applic... | [
"\nIn fact, from my beginner point of\n view, it seems like the python world\n is more suitable for a\n quickly-developed and fun web\n application. And, on the other hand,\n the java world is useful for\n performance-oriented, scalable\n solutions and for 'serious' projects\n with big money involved...\n\n... | [
7,
4
] | [] | [] | [
"gwt",
"java",
"pyjamas",
"python"
] | stackoverflow_0003472493_gwt_java_pyjamas_python.txt |
Q:
Why are there forty characters left over in Google's PEM for packing a Chrome extension
I've recently been trying to figure out how to get PyCrypto to recognize PEM's which are produced by Google Chrome's packing process. The problem is that the standard importKey method causes errors. After a rather long proces... | Why are there forty characters left over in Google's PEM for packing a Chrome extension | I've recently been trying to figure out how to get PyCrypto to recognize PEM's which are produced by Google Chrome's packing process. The problem is that the standard importKey method causes errors. After a rather long process, I finally realized that I can initially simulate the import by reverse-engineering the Der... | [
"For now, the simplest thing to do is to use the openssl rsa utiity to convert the chrome.pem file to a chrome.der file. Something like\nopenssl rsa -in chrome.pem -out chrome.der -outform DER\n\nshould do the trick. Now you can use the bytes from chrome.der directly in the RSA.importKey() method.\n"
] | [
2
] | [] | [] | [
"google_chrome_extension",
"pem",
"pycrypto",
"python",
"rsa"
] | stackoverflow_0004858307_google_chrome_extension_pem_pycrypto_python_rsa.txt |
Q:
Use psycopg2 to construct queries without connection
I have several occasions where I want to collect data when in the field. This is in situations where I do not always have access to my postgres database.
To keep things in sync, it would be excellent if I could use psycopg2 functions offline to generate queries ... | Use psycopg2 to construct queries without connection | I have several occasions where I want to collect data when in the field. This is in situations where I do not always have access to my postgres database.
To keep things in sync, it would be excellent if I could use psycopg2 functions offline to generate queries that can be held back and once I am able to connect to the... | [
"It would be a fragile approach, as the connection is used to detect some parameters used for escaping (encoding, standard-conforming string etc).\nYou can have a \"manual mogrify\" calling psycopg2.extensions.adapt(x).getquoted() on your parameters and then merging them to the query using the regular Python % oper... | [
17,
0
] | [] | [] | [
"offline_mode",
"psycopg2",
"python"
] | stackoverflow_0004879804_offline_mode_psycopg2_python.txt |
Q:
Opacity of individual widgets in WXPython
Is it possible to control the opacity of individual widgets in WXPython?
I know I can make the Frame transparent with self.SetTransparent(150), is there a way to do this for individual widgets?
A:
Since nearly everything visible inherits from wx.Window, you can use ite... | Opacity of individual widgets in WXPython | Is it possible to control the opacity of individual widgets in WXPython?
I know I can make the Frame transparent with self.SetTransparent(150), is there a way to do this for individual widgets?
| [
"Since nearly everything visible inherits from wx.Window, you can use item.SetTransparent() on most widgets.\nNot everything can go transparent though. To check:\nif button.CanSetTransparent():\n button.SetTransparent(100)\n\nBut as the wxPython documentation says:\n\nReturns True if the platform supports settin... | [
4
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004882506_python_wxpython.txt |
Q:
Object roll-back, copy-on-write, versioned proxy etc in Python
Premise: Given a Python object obj, I want to pass it along to some random function, and, when the function is done, I need the option to reset obj to it's original state. Additionally, no actual changes can be made to the obj as other code may still w... | Object roll-back, copy-on-write, versioned proxy etc in Python | Premise: Given a Python object obj, I want to pass it along to some random function, and, when the function is done, I need the option to reset obj to it's original state. Additionally, no actual changes can be made to the obj as other code may still want to access it's original state.
The optimal solution should be q... | [
"I've actually implemented two solutions to this question by now, and seeing as there are no other answers, I might as well share one.\nThe easiest solution is to use Copy On Demand. If we have a proxy P targeting object O: P will have a __getattr__ method so that when P.x is attempted, it tries to copy from O.x, s... | [
1,
0
] | [] | [] | [
"copy_on_write",
"magic_methods",
"metaprogramming",
"python",
"rollback"
] | stackoverflow_0004819111_copy_on_write_magic_methods_metaprogramming_python_rollback.txt |
Q:
python gtk window not responding
I process a new function and append the values from new function to the gtk window till the second function completes, the window gets unresponsive and can become responsive when second function completes.
can anyone tell me what should i do for the same?
A:
You can use gobject.i... | python gtk window not responding | I process a new function and append the values from new function to the gtk window till the second function completes, the window gets unresponsive and can become responsive when second function completes.
can anyone tell me what should i do for the same?
| [
"You can use gobject.idle_add to have a function be executed and still keep your windows responsive.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004886634_python.txt |
Q:
Python: namespaces in xml ElementTree (or lxml)
I want to retrieve a legacy xml file, manipulate and save it.
Here is my code:
from xml.etree import cElementTree as ET
NS = "{http://www.somedomain.com/XI/Traffic/10}"
def fix_xml(filename):
f = ET.parse(filename)
root = f.getroot()
eventlist = root.fin... | Python: namespaces in xml ElementTree (or lxml) | I want to retrieve a legacy xml file, manipulate and save it.
Here is my code:
from xml.etree import cElementTree as ET
NS = "{http://www.somedomain.com/XI/Traffic/10}"
def fix_xml(filename):
f = ET.parse(filename)
root = f.getroot()
eventlist = root.findall("%(ns)Event" % {'ns':NS })
xpath = "%(ns)sEv... | [
"Have a look at the lxml tutorial section on namespaces. Also this article about namespaces in ElementTree.\nProblem 1: Put up with it, like everybody else does. Instead of \"%(ns)Event\" % {'ns':NS } try NS+\"Event\".\nProblem 2: By default, the XML declaration is written only if it is required. You can force it (... | [
9,
1
] | [] | [] | [
"elementtree",
"namespaces",
"python",
"xml"
] | stackoverflow_0004886189_elementtree_namespaces_python_xml.txt |
Q:
python gtk problem
I have created a gtk window in init
and then I process a new function
and i append the values from new function to the gtk window
till the second function completes, the window gets unresponsive and can become responsive when second function completes.
can anyone tell me whet should i do for the... | python gtk problem | I have created a gtk window in init
and then I process a new function
and i append the values from new function to the gtk window
till the second function completes, the window gets unresponsive and can become responsive when second function completes.
can anyone tell me whet should i do for the same?
| [
"Windows become unresponsive in gtk (and in windowing systems in general) when you call a function within the Event Loop, which is the thread in charge of keeping the window responsive (this thread repaints the window, handles mouse clicks, etc.). If the function you call returns immediately, you won't notice the u... | [
2
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0004886652_gtk_python.txt |
Q:
Why no append() method on Django ValuesListQuerySet?
Any good reason there is no append method on Django ValuesListQueryset ?
If I want to add an element, is there a better way than converting first to a list ?
A:
From my comment:
django querysets are not lists.......though they still support some list opera... | Why no append() method on Django ValuesListQuerySet? | Any good reason there is no append method on Django ValuesListQueryset ?
If I want to add an element, is there a better way than converting first to a list ?
| [
"From my comment: \n\ndjango querysets are not lists.......though they still support some list operations\n\nAlso as programmersbook commented.....django querysets are lazy i.e. The queries are executed when the queryset is first accessed. Let us say you have chained a long filters for getting a queryset, even the... | [
4
] | [] | [] | [
"append",
"django",
"list",
"python"
] | stackoverflow_0004887033_append_django_list_python.txt |
Q:
Going deeper -- yield from inside yield
Is there a one-liner to take a generator and yield all elements in this generator? For example:
def Yearly(year):
yield YEARLY_HEADER
for month in range(1, 13):
# How can I rewrite the following two lines?
for line in Monthly(month):
yield line
yield YEAR... | Going deeper -- yield from inside yield | Is there a one-liner to take a generator and yield all elements in this generator? For example:
def Yearly(year):
yield YEARLY_HEADER
for month in range(1, 13):
# How can I rewrite the following two lines?
for line in Monthly(month):
yield line
yield YEARLY_FOOTER
def Monthly(month):
yield MONTHL... | [
"import itertools\n\ndef Yearly(year):\n return itertools.chain(*[(YEARLY_HEADER,)] + \n [Monthly(m) for m in range(1, 13)] + \n [(YEARLY_FOOTER,)])\n\nBasically, making the YEARLY_HEADER and YEARLY_FOOTER into iterators, they can be chained with the monthly iterator... | [
5,
3
] | [] | [] | [
"python",
"yield"
] | stackoverflow_0004887133_python_yield.txt |
Q:
Equivalent to Tkinter's place geometry manager in wxPython
Is there an equivalent to Tkinter's place geometry manager in wxPython?
For those those that don't know, place allows the positioning of widgets based on x y or relative x y coordinates.
I'm a fan of this geometry manager simply because it offers a lot of... | Equivalent to Tkinter's place geometry manager in wxPython | Is there an equivalent to Tkinter's place geometry manager in wxPython?
For those those that don't know, place allows the positioning of widgets based on x y or relative x y coordinates.
I'm a fan of this geometry manager simply because it offers a lot of control over widget positioning.
| [
"I think the best answer is \"no, there is no equivalent\". You can use absolute positioning with the \"pos\" keyword argument in the constructor, but that doesn't come close to the power of place. \n"
] | [
1
] | [
"The GridBagSizer or FlexGridSizer are kind of like Tkinter's place. Of course, wx also supports absolute positions, although I do not recommend that.\n"
] | [
-1
] | [
"geometry",
"python",
"wxpython"
] | stackoverflow_0004885296_geometry_python_wxpython.txt |
Q:
Learning Python: Find and Add value inside file
I want to find last value (ie. lo:) and just append a value to this.
ie.
i want to find the lo:3, in this case my last value and append a lo:4
File:
ifconfig lo:1
address x.x.x.x
netmask x.x.x.x
gateway x.x.x.x
ifconfig lo:2
address x.x.x.x
netmask x.x.x.x
ga... | Learning Python: Find and Add value inside file | I want to find last value (ie. lo:) and just append a value to this.
ie.
i want to find the lo:3, in this case my last value and append a lo:4
File:
ifconfig lo:1
address x.x.x.x
netmask x.x.x.x
gateway x.x.x.x
ifconfig lo:2
address x.x.x.x
netmask x.x.x.x
gateway x.x.x.x
ifconfig lo:3
address x.x.x.x
netmas... | [
"Without assuming too much on the structure of the file, you have to parse the file and take track of every \"ifconfig lo:\" line, e.g updating a running maximum. In this case:\nmax_value_observed == 3 # at the end of this step\n\nOnce you have seen it all, you will know the maximum value and will be able to compu... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004887832_python.txt |
Q:
How to start printing a StringListProperty() from index [1]?
I have a model
class Category(db.Model):
merchandise = db.StringListProperty()
content = db.StringListProperty()
topics = db.StringListProperty()
For instance, merchandise list is ["merchandise","tshirt","book","poster"]
I print the li... | How to start printing a StringListProperty() from index [1]? | I have a model
class Category(db.Model):
merchandise = db.StringListProperty()
content = db.StringListProperty()
topics = db.StringListProperty()
For instance, merchandise list is ["merchandise","tshirt","book","poster"]
I print the list like this
elif merchandise_type == "merchandise":
query = C... | [
"for merch in e.merchandise[1:]:\n self.response.out.write('<li><a href=\"/tag?tag=%s\">%s<a/></li>' % (merch, merch))\n\nQuestion, of course, is why do you have such first element in your list in the first place.\n",
"for i in range(1, len(e.merchandise)): changing the first argument of range() will start the... | [
3,
1
] | [] | [] | [
"google_app_engine",
"list",
"python"
] | stackoverflow_0004888174_google_app_engine_list_python.txt |
Q:
Addressing ranges in a Scipy sparse matrix
I have a large matrix, currently in numpy that i would like to port over to scipy sparse matrix, because saving the text representations of the numpy (2000,2000) matrix is over 100mb.
(1) There seem to a surfeit of sparse matrices available in scipy [for instance, lil_mat... | Addressing ranges in a Scipy sparse matrix | I have a large matrix, currently in numpy that i would like to port over to scipy sparse matrix, because saving the text representations of the numpy (2000,2000) matrix is over 100mb.
(1) There seem to a surfeit of sparse matrices available in scipy [for instance, lil_matrix or dok_matrix- which one would be optimal fo... | [
"I can't say which is most efficient to store. It's going to depend on your data.\nI can say, however that the += operator works, just that you can't rely on the usual array broadcasting rules:\n>>> m = sparse.lil_matrix((100,100))\n>>> m[50:56,50:56]+=scipy.ones((6,6))\n>>> m[50,50] #1.0\n\n"
] | [
6
] | [] | [] | [
"matrix",
"numpy",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0004885831_matrix_numpy_python_scipy_sparse_matrix.txt |
Q:
Print the function itself python 3
Write a program that has a function named my_func with three parameters, a, b, and c.
The first parameter is required, and the second two parameters have the default values of 'b was not entered' and 'c was not entered'.
The function must print the value of each parameter.
In you... | Print the function itself python 3 | Write a program that has a function named my_func with three parameters, a, b, and c.
The first parameter is required, and the second two parameters have the default values of 'b was not entered' and 'c was not entered'.
The function must print the value of each parameter.
In your program, call my_func three times. The... | [
"I'll try to give you some pointers to find the correct answer yourself.\nFirstly, why are you calling your function with list of string as parameter instead of just string. Passing just string would simplify your function.\nSecondly, when you specify the default value for your b and c arguments, you can use whatev... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004888268_python.txt |
Q:
ElementTree instance has no attribute 'fromstring'. So, what I did wrong?
I'm trying open and parse some html. So far, it was ok, I'm able to open the source and print it for example. But when it comes to parsing I'm stuck with "ElementTree instance has no attribute 'fromstring'"
this is my Django view.py code:
fr... | ElementTree instance has no attribute 'fromstring'. So, what I did wrong? | I'm trying open and parse some html. So far, it was ok, I'm able to open the source and print it for example. But when it comes to parsing I'm stuck with "ElementTree instance has no attribute 'fromstring'"
this is my Django view.py code:
from django.template import loader, Context
from django.http import HttpResponse
... | [
"Your import statement is wrong... fromstring is a free function in the xml.etree.ElementTree module, not a method of the class xml.etree.ElementTree.ElementTree:\nfrom xml.etree import ElementTree as etree\n...\ntree = etree.fromstring(r)\n\n"
] | [
19
] | [] | [] | [
"django",
"elementtree",
"parsing",
"python"
] | stackoverflow_0004888533_django_elementtree_parsing_python.txt |
Q:
Problem with reference in python
def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 5555, "*chrome", "http://www.address.com/")
self.selenium.start()
def test_sel__TestCase5(self):
sel = self.selenium
sel.open('/')
and this is a part of code which I'm using ... | Problem with reference in python | def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 5555, "*chrome", "http://www.address.com/")
self.selenium.start()
def test_sel__TestCase5(self):
sel = self.selenium
sel.open('/')
and this is a part of code which I'm using in all my testcases:
text='$'
... | [
"You have to pass both self and text if you want to access self.\ndef assert_text_missing(self, text):\n sel = self.selenium\n try:\n self.failIf(sel.is_text_present(text))\n except AssertionError, e:\n self.verificationErrors.append(str(e))\n\nAnd then you'd use it like this:\nself.assert_te... | [
0
] | [] | [] | [
"class_design",
"python",
"selenium"
] | stackoverflow_0004887662_class_design_python_selenium.txt |
Q:
How to inject pdb to failing Python scripts?
I'm working on a django project that has a large fixture which does not load:
$ python manage.py loaddata apps/mainsite/fixtures/test_auctions.json
/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field ... | How to inject pdb to failing Python scripts? | I'm working on a django project that has a large fixture which does not load:
$ python manage.py loaddata apps/mainsite/fixtures/test_auctions.json
/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field class whose get_db_prep_save method hasn't been up... | [
"This Python Recipe will install a debugger that starts on uncaught exceptions:\nhttp://code.activestate.com/recipes/65287-automatically-start-the-debugger-on-an-exception/\nThe gist of it is to install an exception hook in sys.excepthook that calls pdb.pm() when called (though it's slightly more complicated than t... | [
6
] | [] | [] | [
"debugging",
"django",
"pdb",
"python"
] | stackoverflow_0004888676_debugging_django_pdb_python.txt |
Q:
Working with OAuth python
I'm am using OAuth to allow my user to OAuth with Hunch, on my webpage I have a button to allow the user to go to Hunch and enter their details
<form action="/hunch" method="post" align = "right">
<div>
<input type="submit" value="Login using Hunch">
</div>... | Working with OAuth python | I'm am using OAuth to allow my user to OAuth with Hunch, on my webpage I have a button to allow the user to go to Hunch and enter their details
<form action="/hunch" method="post" align = "right">
<div>
<input type="submit" value="Login using Hunch">
</div>
</form>
How can I call a ... | [
"When GAE (using OpenId) logs in a user, it relies on the /_ah/login_required page. \nTo get a user to enter their own credentials, you should create a page containing links to log in with the different providers you wish to use. You must then override the /_ah/login_required mapping in your url mapping file to u... | [
0,
0
] | [] | [] | [
"google_app_engine",
"html",
"oauth",
"python"
] | stackoverflow_0004845538_google_app_engine_html_oauth_python.txt |
Q:
Comparing String received from Python UDP Stream to a Java String
I'm currently experimenting with UDP-Communication between a server written in Python using the SocketServer class and a client written in Java using the DatagramSocket and DatagramPacket classes.
The server accepts python method calls as an input a... | Comparing String received from Python UDP Stream to a Java String | I'm currently experimenting with UDP-Communication between a server written in Python using the SocketServer class and a client written in Java using the DatagramSocket and DatagramPacket classes.
The server accepts python method calls as an input and routes the stdout and stderr back to the client, transmitted in a 10... | [
"I now managed to resolve the issue by specifyng an offset of 0 and the length of the packet when converting my packet to a String:\nString(packet.getData(), 0, packet.getLength(), \"UTF-8\");\nThe resulting String is stripped of the trailing 0s.\n",
"It would seem to me that you can use the setLength before pack... | [
2,
0,
0
] | [] | [] | [
"character_encoding",
"java",
"python"
] | stackoverflow_0004857163_character_encoding_java_python.txt |
Q:
Is it possible to import a 3D model into pyglet?
Me and a friend are working on an openGL game written in python, using the pyglet library.
Now we finished the map drawing code, and have come to a point where we need to import some models that will be displayed on the map. Pyglet doesn't seem to support it, apart ... | Is it possible to import a 3D model into pyglet? | Me and a friend are working on an openGL game written in python, using the pyglet library.
Now we finished the map drawing code, and have come to a point where we need to import some models that will be displayed on the map. Pyglet doesn't seem to support it, apart from some old SVN code, apparently (I googled a bit ar... | [
"Open Asset Import Library (Assimp) supports ~35 different 3D file formats. \nIt has python bindings in its repository, but I don't know for sure if they're up-to-date and feature-complete. Still, assimp might be worth a try (even though I am not unbiased since i'm one of its founders).\n",
"There are 3D models a... | [
3,
2
] | [] | [] | [
"opengl",
"pyglet",
"python"
] | stackoverflow_0004445310_opengl_pyglet_python.txt |
Q:
While loop for some time
I am programming in Python. I have such a while loop
b=time.clock()
while time.clock()-b<3 :
input("input")
I want to end the while loop after exactly 3 seconds, even if the user has not yet entered anything ! How can I do that?
Edit: What would it be if I had data=s.recv(1024) where ... | While loop for some time | I am programming in Python. I have such a while loop
b=time.clock()
while time.clock()-b<3 :
input("input")
I want to end the while loop after exactly 3 seconds, even if the user has not yet entered anything ! How can I do that?
Edit: What would it be if I had data=s.recv(1024) where s is a socket, rather than inp... | [
"input blocks on user input, so you'll have to implement some asynchronous way to trigger the timeout event (or trigger on user input)\nLuckily, this SO answer seems to have just the thing!\nedit: and if you're not using Python 3, you should probably be using raw_input instead of input\n",
"You can't, using input... | [
3,
0
] | [] | [] | [
"clock",
"python",
"python_3.x",
"time",
"while_loop"
] | stackoverflow_0004889054_clock_python_python_3.x_time_while_loop.txt |
Q:
python string assignment
I have a StringIO object the is filled correctly. I than have the following code:
val = log_fp.getvalue()
lines = val.split('\n')
newval = ''
for line in lines:
if (not line.startswith('[output]')):
newval = line
print 'test1'+newval
print 'test2' +newval
in th... | python string assignment | I have a StringIO object the is filled correctly. I than have the following code:
val = log_fp.getvalue()
lines = val.split('\n')
newval = ''
for line in lines:
if (not line.startswith('[output]')):
newval = line
print 'test1'+newval
print 'test2' +newval
in the loop, I have the correct val... | [
"Splitting on '\\n' for a string such as 'foo\\n' will produce ['foo', ''].\n",
"\nWhat I need is to extract one of the\n lines in the stringIO object that is\n marked [output], \n\nUntested:\ncontent = log_fp.getvalue().split()\noutput_lines = [x for x in content if x.startswith('[output'])]\n\nThen get the fi... | [
4,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004888376_python_string.txt |
Q:
Is it possible to cancel "keyword argument repeated" exception in python 2.6?
The code runs on python 2.5 but fails with this exception on 2.6
A:
That exception is a syntax error in the source, and the only way to fix it is to correct the function call.
Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)
[GCC 4.3.2... | Is it possible to cancel "keyword argument repeated" exception in python 2.6? | The code runs on python 2.5 but fails with this exception on 2.6
| [
"That exception is a syntax error in the source, and the only way to fix it is to correct the function call.\nPython 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)\n[GCC 4.3.2] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(x): pass\n...\n>>> f(x=1, x=2)\nTraceback (... | [
3
] | [] | [] | [
"python",
"python_2.6"
] | stackoverflow_0004889000_python_python_2.6.txt |
Q:
How can I obtain the parent folder of another folder?
In my settings file I have the following lines:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, "apps"))
file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)),"..", "webapp.cfg")
Unde... | How can I obtain the parent folder of another folder? | In my settings file I have the following lines:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, "apps"))
file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)),"..", "webapp.cfg")
Under Windows if os.path.realpath(os.path.dirname(__file__)) is... | [
"Add file_path = os.path.normpath(file_path) to eliminate the up-level reference (/../).\n",
"parent = os.path.normpath(os.path.join(directory, \"..\"))\n\n"
] | [
3,
0
] | [] | [] | [
"django",
"linux",
"path",
"python",
"windows"
] | stackoverflow_0004875937_django_linux_path_python_windows.txt |
Q:
Write XML-RPC in C# and using it from Python
I have a C# XML-RPC code and I want to use it from Python, is there a capability to
implement that?
this is my code
in C#
1- dll file
public class Search:MarshalByRefObject
{
public string GetAllFiles()
{
return ("hhhhhhiiiiiiiiiii");
}
}
... | Write XML-RPC in C# and using it from Python | I have a C# XML-RPC code and I want to use it from Python, is there a capability to
implement that?
this is my code
in C#
1- dll file
public class Search:MarshalByRefObject
{
public string GetAllFiles()
{
return ("hhhhhhiiiiiiiiiii");
}
}
2- to register method
private void button1_Click(... | [
"Are you sure your C# code is indeed XML-RPC server, not remoting ? From the Python error it seems that the server's response is not a valid XML.\n"
] | [
0
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0004889021_c#_python.txt |
Q:
How to delete a checkbox when it is ticked?
I have a template that displays the list of items. It has one checkbox to each item. I want to be able to remove an item from a checkbox when a checkbox is ticked. So I would need a button that deletes an item once a checkbox is selected. Here is my template.
{% for... | How to delete a checkbox when it is ticked? | I have a template that displays the list of items. It has one checkbox to each item. I want to be able to remove an item from a checkbox when a checkbox is ticked. So I would need a button that deletes an item once a checkbox is selected. Here is my template.
{% for item in items %}
<tr>
<td><inp... | [
"You need to write a view that gets the POST data, finds out which checkboxes have been checked, and then deletes the items from the database matched by id.\nYou probably also want to wrap the view in a decorator to make sure the user has permission to delete things, or check the logged-in user is the same as the o... | [
1,
0,
0
] | [] | [] | [
"checkbox",
"django",
"html",
"javascript",
"python"
] | stackoverflow_0004886845_checkbox_django_html_javascript_python.txt |
Q:
Python Parsing: Pull data from html test file for non-standard layout
I need help with parsing an html text file that has a layout that I'm not sure how to parse through, and could really use the help.
code thus far:
import urllib,os, urllib2, webbrowser, StringIO, re
from BeautifulSoup import BeautifulSoup
from u... | Python Parsing: Pull data from html test file for non-standard layout | I need help with parsing an html text file that has a layout that I'm not sure how to parse through, and could really use the help.
code thus far:
import urllib,os, urllib2, webbrowser, StringIO, re
from BeautifulSoup import BeautifulSoup
from urllib import urlopen
urlfile = open('output.txt','r')
html = urlfile
sou... | [
"I'd recommend that you use the module called MiniDom or xml.dom.minidom. It makes it easy to parse XML and HTML files.\n"
] | [
0
] | [] | [] | [
"html_parsing",
"python",
"text",
"text_parsing"
] | stackoverflow_0004805484_html_parsing_python_text_text_parsing.txt |
Q:
Sorting list of Wikipedia links
I have a long list of Wikipedia links in a plaintext file. Each link is separated by a newline and is percent-encoded. Unfortunately a large number of these links are outdated; some are redirects and others have been removed. Is there anyway to automatically sort through the links, ... | Sorting list of Wikipedia links | I have a long list of Wikipedia links in a plaintext file. Each link is separated by a newline and is percent-encoded. Unfortunately a large number of these links are outdated; some are redirects and others have been removed. Is there anyway to automatically sort through the links, resolving redirects and removing dead... | [
"It should be easy with Perl and LWP::UserAgent:\n#!/usr/bin/perl\nuse LWP::UserAgent; \n\nopen my $fh, \"links.txt\" or die $!;\nmy @links = <$fh>;\nmy $ua = LWP::UserAgent->new;\n\nfor my $link (@links) {\n my $resp = $ua->get($link); # automatically follows redirects \n if ($resp->is_success) {\n ... | [
4,
4,
1
] | [] | [] | [
"bash",
"http",
"perl",
"python",
"wikipedia"
] | stackoverflow_0004889075_bash_http_perl_python_wikipedia.txt |
Q:
SAS or Python Extracting Map for Directions as Picture
I would like to use SAS or Python to achieve this.
I have multiple points that I would like to map out using mapquest/maps.google/maps.bing, and then download a screenshot of the map on to my C: drive.
This would not be a one time thing. I would need it to dow... | SAS or Python Extracting Map for Directions as Picture | I would like to use SAS or Python to achieve this.
I have multiple points that I would like to map out using mapquest/maps.google/maps.bing, and then download a screenshot of the map on to my C: drive.
This would not be a one time thing. I would need it to download multiple maps (Have a map for route within Chicago, th... | [
"The family of Google Maps APIs lets you call down various services from any language that will let you send a URL request. The Static API might be of special interest to you, though I'm not sure if you can overlay directions, or how.\nTo do this in Python, you could use urllib for interacting with the API; there'... | [
1,
1
] | [] | [] | [
"google_maps",
"python",
"sas"
] | stackoverflow_0004888640_google_maps_python_sas.txt |
Q:
Can't understand the reason for an output in Python
I've just started learning Python. I came across following code
if 0:
print "And now for something completely different..."
else:
print "What's all this, then?"
I understand that output should be What's all this, then? but I can't seem to find a proper exp... | Can't understand the reason for an output in Python | I've just started learning Python. I came across following code
if 0:
print "And now for something completely different..."
else:
print "What's all this, then?"
I understand that output should be What's all this, then? but I can't seem to find a proper explanation for that. Hope someone can make me understand t... | [
"0 is False in a boolean context. Same applies for empty string, lists, etc.\nFrom the python docs:\n\nIn the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and con... | [
5,
4,
1,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004890172_python.txt |
Q:
convert datetime stamp of six hexadecimal octets using python
I need to convert a date time stamp that consists of six hexadecimal octets using python and can not seem to find an easy way to do so. I am parsing a number of entries from some anti-virus logs and need to covert the date time value to something that ... | convert datetime stamp of six hexadecimal octets using python | I need to convert a date time stamp that consists of six hexadecimal octets using python and can not seem to find an easy way to do so. I am parsing a number of entries from some anti-virus logs and need to covert the date time value to something that looks like a regular date.
For example: 200A13080122 should transl... | [
"import binascii, calendar\nY,M,D,h,m,s = map(ord, binascii.a2b_hex(\"200A13080122\"))\nampm = \"AM\"\nif h >= 12:\n h = h-12\n ampm = \"PM\"\nif h == 0:\n h = 12\nprint \"%s %d, %d, %d:%d:%d %s\" % (calendar.month_name[M+1], D, 1970+Y, \n h, m, s, ampm)\n\n",
"import dat... | [
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004889912_python.txt |
Q:
Opening and closing windows by calling a function?
The idea is that I would have two or three different windows and I would like to open and close them automatically by calling a function (separate functions to open and close each window). The program itself would be running in the background but when a certain ev... | Opening and closing windows by calling a function? | The idea is that I would have two or three different windows and I would like to open and close them automatically by calling a function (separate functions to open and close each window). The program itself would be running in the background but when a certain event happens it would call the window opening function. O... | [
"In wxWindows you just call the .destroy() method on the dialog/window to delete it. You don't have to move the mouse over it. That would make wxWindows apps very annoying.\nI suspect your problem is more related to trying to do something outside the wx event framework. Most GUIs are event driven, so if you've got ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004890257_python.txt |
Q:
Pythonic way to conditionally iterate over items in a list
New to programming in general, so I'm probably going about this the wrong way. I'm writing an lxml parser where I want to omit HTML table rows that have no content from the parser output. This is what I've got:
for row in doc.cssselect('tr'):
for cell ... | Pythonic way to conditionally iterate over items in a list | New to programming in general, so I'm probably going about this the wrong way. I'm writing an lxml parser where I want to omit HTML table rows that have no content from the parser output. This is what I've got:
for row in doc.cssselect('tr'):
for cell in row.cssselect('td'):
sys.stdout.write(cell.text_conte... | [
"for row in doc.cssselect('tr'):\n cells = [ cell.text_content() for cell in row.cssselect('td') ]\n if any(cells):\n sys.stdout.write('\\t'.join(cells) + '\\n')\n\nprints the line only if there is at least one cell with text content.\n",
"ReEdit:\nYou know, I really don't like my answer at all. I v... | [
5,
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0004890363_lxml_python.txt |
Q:
Django not cascading on delete
I'm realizing more and more that I'm still a Django noob, I can't seem to figure out what's happening with my data model and why it's not cascading deletes. Here is my model.
class message(models.Model):
msg_text = models.CharField(max_length = 9900)
date_time = models.Dat... | Django not cascading on delete | I'm realizing more and more that I'm still a Django noob, I can't seem to figure out what's happening with my data model and why it's not cascading deletes. Here is my model.
class message(models.Model):
msg_text = models.CharField(max_length = 9900)
date_time = models.DateTimeField()
is_read = models.B... | [
"In Django version 1.3 there is a on_delete parameter which determinates \"ondelete\" action, for example:\ndef get_sentinel_user():\n return User.objects.get_or_create(username='deleted')[0]\n\nclass MyModel(models.Model):\n user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))\n\nSo maybe ... | [
5,
1
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0003847511_django_python_sql.txt |
Q:
Gearman + SQLAlchemy - keep losing MySQL thread
I have a python script that sets up several gearman workers. They call into some methods on SQLAlchemy models I have that are also used by a Pylons app.
Everything works fine for an hour or two, then the MySQL thread gets lost and all queries fail. I cannot figure ou... | Gearman + SQLAlchemy - keep losing MySQL thread | I have a python script that sets up several gearman workers. They call into some methods on SQLAlchemy models I have that are also used by a Pylons app.
Everything works fine for an hour or two, then the MySQL thread gets lost and all queries fail. I cannot figure out why the thread is getting lost (I get the same resu... | [
"I've seen this across the board for Ruby, PHP, and Python regardless of DB library used. I couldn't find how to fix this the \"right\" way which is to use mysql_ping, but there is a SQLAlchemy solution as explained better here http://groups.google.com/group/sqlalchemy/browse_thread/thread/9412808e695168ea/c31f5c... | [
3
] | [] | [] | [
"gearman",
"mysql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0004890927_gearman_mysql_pylons_python_sqlalchemy.txt |
Q:
Make in-memory copy of a zip by iterating over each file of the input
Python, as far as know, does not allow modification of an archived file. That is why I want to:
Unpack the zip in memory (zip_in).
Go over each file in the zip_in, and change it if needed, then copy it to zip_out. For now I'm happy with just ma... | Make in-memory copy of a zip by iterating over each file of the input | Python, as far as know, does not allow modification of an archived file. That is why I want to:
Unpack the zip in memory (zip_in).
Go over each file in the zip_in, and change it if needed, then copy it to zip_out. For now I'm happy with just making a copy of a file.
Save zip_out.
I was experimenting with zipfile and ... | [
"ZipFile.extract() expects a filename, not a file-like object to write to. Instead, use ZipFile.read(name) to get the contents of the file. It returns the byte string so will work fine with binary files. Text files may require decoding to unicode.\n"
] | [
2
] | [] | [] | [
"copy",
"memory",
"python",
"zip"
] | stackoverflow_0004890860_copy_memory_python_zip.txt |
Q:
How can I give a class as argument to a Python function
I have two functions in my (first!) Python program that only differ by the class that must be instanciated.
def f(id):
c = ClassA(id)
...
return ...
def g(id):
c = ClassB(id)
...
return ...
To avoid repeated code, I would like to... | How can I give a class as argument to a Python function | I have two functions in my (first!) Python program that only differ by the class that must be instanciated.
def f(id):
c = ClassA(id)
...
return ...
def g(id):
c = ClassB(id)
...
return ...
To avoid repeated code, I would like to be able to write a single function that would somehow accept... | [
"That works exactly as you have it (minus the ...s):\n>>> class foo:\n pass\n\n>>> def make_it(cls):\n return cls()\n\n>>> make_it(foo)\n<__main__.foo instance at 0x011D9B48>\n\nThis can be modified to take in/pass params to the class constructor as well if you like, but the idea is perfectly fine. Classes a... | [
5,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0004891489_python.txt |
Q:
How to design unit tests for a web service client?
I am creating a microblog (Twitter and Status.Net) library for Python, and wish to create unit tests for it. I'm not really sure of the best way of doing this.
Obviously the data returned from the service will be different each time - there will be new posts etc. ... | How to design unit tests for a web service client? | I am creating a microblog (Twitter and Status.Net) library for Python, and wish to create unit tests for it. I'm not really sure of the best way of doing this.
Obviously the data returned from the service will be different each time - there will be new posts etc. Also, I cannot force Twitter to fail whale to test for t... | [
"The standard way is to mock the service. http://code.google.com/p/pymox/ makes that pretty easy.\n"
] | [
5
] | [] | [] | [
"python",
"unit_testing",
"web_services"
] | stackoverflow_0004891465_python_unit_testing_web_services.txt |
Q:
Matplotlib: rotating a patch
I wanted to rotate a Rectangle in matplotlib but when I apply the transformation, the rectangle doesn't show anymore:
rect = mpl.patches.Rectangle((0.0120,0),0.1,1000)
t = mpl.transforms.Affine2D().rotate_deg(45)
rect.set_transform(t)
is this a known bug or do I make a mistake?
A:
T... | Matplotlib: rotating a patch | I wanted to rotate a Rectangle in matplotlib but when I apply the transformation, the rectangle doesn't show anymore:
rect = mpl.patches.Rectangle((0.0120,0),0.1,1000)
t = mpl.transforms.Affine2D().rotate_deg(45)
rect.set_transform(t)
is this a known bug or do I make a mistake?
| [
"The patch in the provided code makes it hard to tell what's going on, so I've made a clear demonstration that I worked out from a matplotlib example:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib as mpl\n\nfig = plt.figure()\nax = fig.add_subplot(111)... | [
26,
9
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004285103_matplotlib_python.txt |
Q:
Django: Programmatically determine path to an admin page?
If I have the admin module enabled for a certain model, is there a way to determine what the full URL will be for the page to create a new instance of that model?
What I'm looking for is something like this following:
"Please <a href='%s'>create</a> some Fo... | Django: Programmatically determine path to an admin page? | If I have the admin module enabled for a certain model, is there a way to determine what the full URL will be for the page to create a new instance of that model?
What I'm looking for is something like this following:
"Please <a href='%s'>create</a> some Foo models" % Foo.AdminCreateUrl
Update: To clarify, this needs ... | [
"First, read this. The admin site must be properly activated.\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/admin/#overview\nSecond, read this. This is how the admin URI names work.\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/admin/#admin-reverse-urls\nI think you can use the {% url %} template tag.\nPl... | [
3,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004891625_django_django_admin_python.txt |
Q:
How can I set a value in the context in a Django view decorator?
I want to write a decorator that will provide values to the template rendering context, like so:
@deco(art=Nouveau)
def my_wall(request):
# should have art == 'something' in the template
return render_from_template('plain_white.html', {art:'s... | How can I set a value in the context in a Django view decorator? | I want to write a decorator that will provide values to the template rendering context, like so:
@deco(art=Nouveau)
def my_wall(request):
# should have art == 'something' in the template
return render_from_template('plain_white.html', {art:'something'}, context_instance=RequestContext(request))
@deco(art=Nouve... | [
"The only way to do this would be if the decorator itself is responsible for rendering and returning the template. And there is quite a well-established snippet that does exactly this: the render_to decorator. The idea is that your view just returns a dictionary, and the decorator actually renders it. You should be... | [
3
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0004891142_django_django_templates_django_views_python.txt |
Q:
Which class should store the lookup table?
The world contains agents at different locations, with only a single agent at any location. Each agent knows where he's at, but I also need to quickly check if there's an agent at a given location. Hence, I also maintain a map from locations to agents. I have a problem de... | Which class should store the lookup table? | The world contains agents at different locations, with only a single agent at any location. Each agent knows where he's at, but I also need to quickly check if there's an agent at a given location. Hence, I also maintain a map from locations to agents. I have a problem deciding where this map belongs to: class World, c... | [
"Okay, I think I can provide my answer, which is perhaps more an opinion than a definitive \"do this\" (I don't have any formal training in programming).\nI think you agent_locations should be a member of each World instance.\nI try to think in terms of interface primarily. In my view, the World class should be res... | [
2,
1,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0004880691_oop_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.