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:
What are some of the Artificial Intelligence (AI) related techniques one would use for parsing a webpage?
I would like to scrape several different discussions forums, most of which have different HTML formats. Rather than dissecting the HTML for each page, it would be more efficient (and fun) to implement some sor... | What are some of the Artificial Intelligence (AI) related techniques one would use for parsing a webpage? | I would like to scrape several different discussions forums, most of which have different HTML formats. Rather than dissecting the HTML for each page, it would be more efficient (and fun) to implement some sort of Learning Algorithm that could identify the different messages (i.e. structures) on each page, and individu... | [
"build a solution that:\n\ntakes some sample webpages with the same structure (eg forum threads)\nanalyzes the DOM tree of each to find which parts are the same / different\nwhere they are different is the dynamic content you are after (posts, user names, etc)\n\nThis technique is known as wrapper induction.\n",
... | [
2,
1,
0
] | [] | [] | [
"artificial_intelligence",
"machine_learning",
"parsing",
"python",
"screen_scraping"
] | stackoverflow_0007714422_artificial_intelligence_machine_learning_parsing_python_screen_scraping.txt |
Q:
Python: Memory allocation error
I am reading rows from a sqlite db, looping over them and then using the variables from each row as arguments for a function which generates plots,
something like the following pseudo code
conn=sqlite3.connect(db)
c=conn.cursor()
myrows=c.execute("select * from values WHERE var=1")... | Python: Memory allocation error | I am reading rows from a sqlite db, looping over them and then using the variables from each row as arguments for a function which generates plots,
something like the following pseudo code
conn=sqlite3.connect(db)
c=conn.cursor()
myrows=c.execute("select * from values WHERE var=1")
for burst in myrows:
met=burst[1... | [
"can't you say something like below, if all you care is this second field?\nmyrows=c.execute(\"select values.bust from values WHERE var=1\")\nalso, i am wondering you really want to create plot for each line... dont you want to plot all the data in one plot?\n",
"Try and see if by changing your for statement to:... | [
1,
0
] | [] | [] | [
"allocation",
"memory",
"python",
"segmentation_fault"
] | stackoverflow_0007996621_allocation_memory_python_segmentation_fault.txt |
Q:
What is the best way to sort list with custom sorting parameters in Python?
I have a series of lists that looks like this:
li1 = ['a.1', 'b.9', 'c.8', 'd.1', 'e.2']
li2 = ['a.4', 'b.1', 'c.2', 'd.2', 'e.4']
How can I rearrange the items in each list so that the first item is 'b.something'? For the example above:
... | What is the best way to sort list with custom sorting parameters in Python? | I have a series of lists that looks like this:
li1 = ['a.1', 'b.9', 'c.8', 'd.1', 'e.2']
li2 = ['a.4', 'b.1', 'c.2', 'd.2', 'e.4']
How can I rearrange the items in each list so that the first item is 'b.something'? For the example above:
li1 = ['b.9', 'a.1', 'c.8', 'd.1', 'e.2']
li2 = ['b.1', 'a.4', 'c.2', 'd.2', 'e.4... | [
"Python's sorting is stable, so you will maintain the order after the first item regardless.\nli1.sort(key=lambda x: not x.startswith('b.'))\n\n",
"\nrearrange the items in each list so that the first item is 'b.something'\nMaintaining the order after the first item isn't important.\n\nThat isn't sorting, then. C... | [
5,
4,
3
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0007996940_list_python_sorting.txt |
Q:
Iterate through checkboxes in Flask
I have a Jinja2 template that looks like this:
<form action="" method=post>
<table>
<tr>
<th></th>
<th>ID</th>
<th>Title</th>
</tr>
{% for page in pages %}
<tr>
<td><input type=checkbox n... | Iterate through checkboxes in Flask | I have a Jinja2 template that looks like this:
<form action="" method=post>
<table>
<tr>
<th></th>
<th>ID</th>
<th>Title</th>
</tr>
{% for page in pages %}
<tr>
<td><input type=checkbox name=do_delete value="{{ page['id'] }}"></... | [
"Flask's request object (well, actually the class that is returned by the LocalProxy instance that is request) is a subclass of werkzeug's MultiDict data structure - which includes a getlist method.\npage_ids = request.form.getlist(\"do_delete\")\n\n"
] | [
36
] | [] | [] | [
"flask",
"jinja2",
"python"
] | stackoverflow_0007996075_flask_jinja2_python.txt |
Q:
xml.etree.ElementTree and unicode findtext
I am trying to parse Medline xml documents using iterparse in the xml.etree.ElementTree module. All is working well except that some of the text includes non-ascii characters. I do not see a way of handling unicode using findtext. Any suggestions?
A:
Have you tried o... | xml.etree.ElementTree and unicode findtext | I am trying to parse Medline xml documents using iterparse in the xml.etree.ElementTree module. All is working well except that some of the text includes non-ascii characters. I do not see a way of handling unicode using findtext. Any suggestions?
| [
"Have you tried opening the file with utf8 encoding flah:\nfd = open('some.xml', mode='r', encoding='utf-8')\nxml.etree.ElementTree.iterparse(fd)\n\nOr use decode:\nfd = open('some.xml', mode='r')\nsio = StringIO(fd.read().decode(\"utf-8\"))\nxml.etree.ElementTree.iterparse(sio)\n\n",
"This was a very useful post... | [
2,
0
] | [] | [] | [
"elementtree",
"python",
"unicode",
"xml"
] | stackoverflow_0007995900_elementtree_python_unicode_xml.txt |
Q:
How do I embed a Python script into a c# program?
I am writing a python script to configure a storage array. I am making a frontend for it in Visual Studio 2010 using C#. I'd like to have the python script run within a textbox in the c# GUI rather than in a seperate DOS window. I'd also like the responses from the... | How do I embed a Python script into a c# program? | I am writing a python script to configure a storage array. I am making a frontend for it in Visual Studio 2010 using C#. I'd like to have the python script run within a textbox in the c# GUI rather than in a seperate DOS window. I'd also like the responses from the python script to be visible within the textbox in real... | [
"I think this post will get you started.\n\n",
"You could run it in a hidden console window and capture the output it generates\nCapturing console output from a .NET application (C#)\n"
] | [
2,
0
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0007968149_c#_python.txt |
Q:
interacting with an external django project from within another django project
I'm looking for a way to interact with the models of a django project from within a separate django project. I don't mean different apps, I mean 2 separate projects with 2 separate settings files.
I'm in the process of migrating an old ... | interacting with an external django project from within another django project | I'm looking for a way to interact with the models of a django project from within a separate django project. I don't mean different apps, I mean 2 separate projects with 2 separate settings files.
I'm in the process of migrating an old web store (really old, it's all static html) to our django based backend. To do this... | [
"I've done this before...\nSo,\nProject A, Project B\nProject B wants to call models in Project A...\n1) Project B connects to the same database with the same user/login as Project A.\nIf so then you can just import models from Project A into Project B and interact with them like normal.\n2) Project B connects to a... | [
5
] | [
"Why not replicate the models from the crawler into your new project (so they are created in the same project space), then simply use django's manage.py to dump the data from the old crawler project into json files and migrate them over to your new project?\nProvided your crawler project is settings/db type indepen... | [
-1
] | [
"django",
"django_models",
"python"
] | stackoverflow_0007987845_django_django_models_python.txt |
Q:
Check if an item equals to one out of many elements in Python
I want to check if an item from a list equals to any one element out of a given set of n elements, if yes, do some thing.
For example, the most intuitive but of course cumbersome and ugly way is:
for item in List:
if (item == element1) or (item == e... | Check if an item equals to one out of many elements in Python | I want to check if an item from a list equals to any one element out of a given set of n elements, if yes, do some thing.
For example, the most intuitive but of course cumbersome and ugly way is:
for item in List:
if (item == element1) or (item == element2) or ... or (item == elementn):
do something
What a... | [
"You use the in operator:\nelements = set((element1, element2, ..., elementn))\n...\nif item in elements:\n do something\n\nUse either a set or a tuple for the elements: a set is faster for lookups but requires the elements be hashable. A tuple is lighter weight for a few elements but gets slower if there are mor... | [
9,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0007997749_python.txt |
Q:
How to run a Python program on a Windows server without having Python installed?
So I wrote a Python script which does some simple stuff. It was originally going to run on a Unix server but due to crappy network security settings which TPTB refuse to change, we need to run it on a Windows server instead. However... | How to run a Python program on a Windows server without having Python installed? | So I wrote a Python script which does some simple stuff. It was originally going to run on a Unix server but due to crappy network security settings which TPTB refuse to change, we need to run it on a Windows server instead. However, the administrators of said Windows server refuse to do anything helpful like install... | [
"Will they let you copy executables onto the server at all? If so then you should be able to do a non-admin installation of Python or use Portable Python which can just be copied into a folder without any installation at all.\nNothing wrong with Py2exe, but it does mean you then have to build the script into a fres... | [
4
] | [] | [] | [
"ironpython",
"py2exe",
"python"
] | stackoverflow_0007997794_ironpython_py2exe_python.txt |
Q:
Distributing Python apps
Quick question... Once I build a .py app, with wx gui, etc... I can compile it with pyinstaller or cx_freeze, and send the binaries to my servers, correct?
Is this a good way to distribute a script? I am fairly new to app development cycle... I have a few python script which I would like... | Distributing Python apps | Quick question... Once I build a .py app, with wx gui, etc... I can compile it with pyinstaller or cx_freeze, and send the binaries to my servers, correct?
Is this a good way to distribute a script? I am fairly new to app development cycle... I have a few python script which I would like to make public, because they ... | [
"The best solution depends on who you're releasing it to, and what license you're releasing it under.\nIf you're not concerned about revealing the code of the apps you're distributing, then a service like github or bitbucket is the way to go. The best way to contribute your code to a community (if you're releasing ... | [
4,
0
] | [] | [] | [
"cx_freeze",
"pyinstaller",
"python"
] | stackoverflow_0007730046_cx_freeze_pyinstaller_python.txt |
Q:
scipy -- how to convert a function result to array
Hello i have the function Walk1d which then i want to calculate the cumsum.
I use Walk1d=lambda n: sc.cumsum(steps(n)) .The result is an array but when i am trying Walk1d.cumsum() it doesn't work because type(Walk1d) is a function.
If i try sc.array(Walk1d).cumsu... | scipy -- how to convert a function result to array | Hello i have the function Walk1d which then i want to calculate the cumsum.
I use Walk1d=lambda n: sc.cumsum(steps(n)) .The result is an array but when i am trying Walk1d.cumsum() it doesn't work because type(Walk1d) is a function.
If i try sc.array(Walk1d).cumsum() it gives me : at 0x3798488>
How can i handle this?
i... | [
"Walk1d is a function taking an argument. You have to call the function and pass in an argument to get a result, for example\nprint(Walk1d(10).cumsum())\n\n",
"The function Walk1d needs to be called with a parameter n:\nprint(sc.array(Walk1d(10)).cumsum())\n\n"
] | [
1,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0007997862_python_scipy.txt |
Q:
invoke celery task from tornado
How can someone invoke a celery task from tornado, and get the result via a callback?
This post claims that someone must simply put a message via RabbitMQ and then the task shall be executed. This makes sense, but can someone give an example in python (even better in tornado, with... | invoke celery task from tornado | How can someone invoke a celery task from tornado, and get the result via a callback?
This post claims that someone must simply put a message via RabbitMQ and then the task shall be executed. This makes sense, but can someone give an example in python (even better in tornado, with a callback)? Personally, I use mongo... | [
"The callback object should be a celery Task too or your code doesn't work.\nYou can use signals inside the task body if your callback function don't have to be a celery task.\nhttp://docs.python.org/library/signal.html\n"
] | [
0
] | [
"If you have the module with your tasks in the pythonpath of your tornado process a simple:\nmy_task.delay()\n\nshould work as long as celery is configured properly in your tornado instance. To do that when starting your server pass:\nCELERY_CONFIG_MODULE=app.foo.celeryconfig\n\nin the environment so when you do im... | [
-1,
-1
] | [
"celery",
"python",
"tornado"
] | stackoverflow_0007934675_celery_python_tornado.txt |
Q:
openerp-server database issue
postgresql
python
I need some help fixing some issues with a postgresql database I use for openerp-server. I looked everywhere to find an answer but I couldn't get any reposes from OpenERP community. Hope some of you postgresql professionals could show me some indications on fixing my... | openerp-server database issue | postgresql
python
I need some help fixing some issues with a postgresql database I use for openerp-server. I looked everywhere to find an answer but I couldn't get any reposes from OpenERP community. Hope some of you postgresql professionals could show me some indications on fixing my broken db.
Here are the errors I e... | [
"Openerp is trying to update the 'Administrator' address_id and it doesn't seems to exists.\nYou can add it with dummy values with a command like this:\nINSERT INTO res_partner_address VALUES (1, 1, '2011-11-02 14:50:55.607533', '2011-11-03 12:48:03.231399', 1, 5, '', NULL, '', '', true, 1, '', '', '', NULL, NUL... | [
0
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0007998005_postgresql_python.txt |
Q:
Automating responses to command line program in batchfile
I am trying to run a Windows (XP) command line program which prompts for 'Enter' or 'y' to continue. Currently, I can respond to the 'y's by running the program as:
echo y | name_of_binary
in a batch file.
I can't figure out how to tell the shell to respond... | Automating responses to command line program in batchfile | I am trying to run a Windows (XP) command line program which prompts for 'Enter' or 'y' to continue. Currently, I can respond to the 'y's by running the program as:
echo y | name_of_binary
in a batch file.
I can't figure out how to tell the shell to respond with 'Enter' or 'y' when this is required. If it gets to a 'Pr... | [
"The standard way to output an Enter in Batch is echo/ in a line with no additional spaces. To output an Enter followed by 'Y' you may try this: (echo/&echo Y) | name_of_binary (don't insert spaces in echo/&).\nIf that not works would be because the LineFeed characters that are inserted both after the first Enter a... | [
2,
0
] | [] | [] | [
"batch_file",
"cmd",
"python",
"windows"
] | stackoverflow_0007990041_batch_file_cmd_python_windows.txt |
Q:
Python OrderedSet with .index() method
Does anyone know about a fast OrderedSet implementation for python that:
remembers insertion order
has an index() method (like the one lists offer)
All implementations I found are missing the .index() method.
A:
You can always add it in a subclass. Here is a basic impleme... | Python OrderedSet with .index() method | Does anyone know about a fast OrderedSet implementation for python that:
remembers insertion order
has an index() method (like the one lists offer)
All implementations I found are missing the .index() method.
| [
"You can always add it in a subclass. Here is a basic implementation for the OrderedSet you linked in a comment:\nclass IndexOrderedSet(OrderedSet):\n def index(self, elem):\n if key in self.map:\n return next(i for i, e in enumerate(self) if e == elem)\n else:\n raise KeyErro... | [
6
] | [] | [] | [
"html_lists",
"python",
"set"
] | stackoverflow_0007998692_html_lists_python_set.txt |
Q:
float has no attribute int , in python 3.2
I have this one error that says ,"float has no attribute int" error.
The question is to write a function that takes a parameter as image and draws two vertical lines to img, one red line from (50,0) to (50,300) and one made up of randomly colored pixels from (150,50) to (... | float has no attribute int , in python 3.2 | I have this one error that says ,"float has no attribute int" error.
The question is to write a function that takes a parameter as image and draws two vertical lines to img, one red line from (50,0) to (50,300) and one made up of randomly colored pixels from (150,50) to (150,250). For some reason the random part, where... | [
"random.random() returns a random floating point in the range [0.0,1.0). If you wanted an integer of it, you'd have to do:\nint(RandomColor) # would be 0 because random() is < 1.0\nint(RandomColor * 256) # to get 0-255 \n\nYou want a random number between 0-255, so couldn't you just do:\nrandom.randint(0,255)\n\n",... | [
6,
1
] | [] | [] | [
"python",
"random"
] | stackoverflow_0007998436_python_random.txt |
Q:
Catch exception with python under windows and UNIX
I got some code that i did 3 years ago under python 2.5 or so. It was working properly back then It was something like this :
try:
if os.path.exists(os.path.join(TRACES.log_file_path, TRACES.log_file_name)):
os.remove(os.path.join(TRACES.log_file_path, ... | Catch exception with python under windows and UNIX | I got some code that i did 3 years ago under python 2.5 or so. It was working properly back then It was something like this :
try:
if os.path.exists(os.path.join(TRACES.log_file_path, TRACES.log_file_name)):
os.remove(os.path.join(TRACES.log_file_path, TRACES.log_file_name))
except IOError , e:
print (str... | [
"The operating system shouldn't make a difference to Python syntax. Most likely, your cygwin installation includes a Python 2.5. (Confirm this by just typing 'python' in your cygwin prompt and checking the banner.) \nNote that 'a cygwin prompt' is not Unix. \nIf you must, install Python 3 under Cygwin.\n"
] | [
2
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0007999018_exception_python.txt |
Q:
Using built in Django authentication/User model with Mongodb
Switching over from sqlite to MongoDB and I followed all of the setup/configuration settings for Django MongoDB Engine. Now when I go to add a user by returning an HTTP response from to the adduser method in views.py:
def adduser(request):
username... | Using built in Django authentication/User model with Mongodb | Switching over from sqlite to MongoDB and I followed all of the setup/configuration settings for Django MongoDB Engine. Now when I go to add a user by returning an HTTP response from to the adduser method in views.py:
def adduser(request):
username = request.POST['username']
password = request.POST['password... | [
"MongoEngine provides authentication for Django apps with MongoDB.\n"
] | [
1
] | [] | [] | [
"authentication",
"django",
"mongodb",
"mongoengine",
"python"
] | stackoverflow_0007999032_authentication_django_mongodb_mongoengine_python.txt |
Q:
QWidget not deleted with parent window
Using the below code, the __del__ method of my Preview widget never gets called. If I uncomment the "del window" line, it does. Why?
#!/usr/bin/env python
from PyQt4 import QtGui
class Preview(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, ... | QWidget not deleted with parent window | Using the below code, the __del__ method of my Preview widget never gets called. If I uncomment the "del window" line, it does. Why?
#!/usr/bin/env python
from PyQt4 import QtGui
class Preview(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
def __del__(self):
print("Del... | [
"If a QObject subclass has a parent, then Qt will delete it when the parent is deleted. On the other hand, if a QObject subclass has no parent, it will (eventually) be deleted by python.\nHopefully this example will make things somewhat clearer:\nfrom PyQt4 import QtGui\n\nclass Widget(QtGui.QWidget):\n def __in... | [
2
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0007988578_pyqt_python_qt.txt |
Q:
Multiplication table in Python
I have this problem---
Write code that will print a multiplication table for 10 positive integers across the columns and 10 positive integers down the rows. Prompt the user for the starting values for both the columns and the rows.
My attempt after some explanation from another quest... | Multiplication table in Python | I have this problem---
Write code that will print a multiplication table for 10 positive integers across the columns and 10 positive integers down the rows. Prompt the user for the starting values for both the columns and the rows.
My attempt after some explanation from another question, which doesn't print like Id exp... | [
"(1) Your col variable is not getting reset for each new row.\nIt is just always incrementing.\nMaybe use another pair of variables, like r and c for the iteration itself.\nOr store the original row and col in differently-named variables.\n(2) Your indentation of the last two lines seems wrong - shouldn't it be ins... | [
3,
0
] | [] | [] | [
"algorithm",
"math",
"python"
] | stackoverflow_0007999121_algorithm_math_python.txt |
Q:
Do PyImport_ImportModule and import statement load into different namespace?
Here is canonical example of a program extending embedded Python 3.x in C/C++:
#include <Python.h>
//// Definition of 'emb' Python module ////////////////////
static PyObject* emb_foo(PyObject *self, PyObject *args)
{
char const* n = ... | Do PyImport_ImportModule and import statement load into different namespace? | Here is canonical example of a program extending embedded Python 3.x in C/C++:
#include <Python.h>
//// Definition of 'emb' Python module ////////////////////
static PyObject* emb_foo(PyObject *self, PyObject *args)
{
char const* n = "I am foo";
return Py_BuildValue("s", n);
}
static PyMethodDef EmbMethods[] = ... | [
"__import__ doesn't put the module in any namespace at all, but returns it instead. \nimport calls __import__, plus it stores the result in a variable.\nThe docs say that import spam does something similar to:\nspam = __import__('spam', globals(), locals(), [], 0)\n\n\nTo get the same effect in the C API, you need ... | [
10
] | [] | [] | [
"c++",
"import",
"python",
"python_c_api",
"python_embedding"
] | stackoverflow_0007998816_c++_import_python_python_c_api_python_embedding.txt |
Q:
Can OpenERP display a grid view based on the selection in a dropdown list?
In .NET, when the user selects a value from a dropdown list, you can make it reload different data in a grid view according to which value was selected in the dropdown list.
Can I do the same thing in OpenERP? When the user selects a value ... | Can OpenERP display a grid view based on the selection in a dropdown list? | In .NET, when the user selects a value from a dropdown list, you can make it reload different data in a grid view according to which value was selected in the dropdown list.
Can I do the same thing in OpenERP? When the user selects a value from a many2one field, can I automatically display a grid of data?
| [
"I haven't seen any screens like that, but you might be able to do something like it. The on_change event of fields can trigger changes in other fields on the screen. You can definitely use that to change simple fields, but I don't know if you could use it to populate a grid of data. The documentation says you can ... | [
0
] | [] | [] | [
"openerp",
"python"
] | stackoverflow_0007976373_openerp_python.txt |
Q:
python: local variable referenced before assignment error
I am completing a text based game for an intro to python class. It is not complete but I was working on the main_menu function and the functions called within the main_menu function when I ran into this error message. I have encountered this error several t... | python: local variable referenced before assignment error | I am completing a text based game for an intro to python class. It is not complete but I was working on the main_menu function and the functions called within the main_menu function when I ran into this error message. I have encountered this error several times in my learning experience and it was usually attributed to... | [
"The first line\ntravel = travel(location)\n\nimplicitly marks the name travel as local for the whole function. All look-ups for this name look for a local name, including the one on the right-hand side of the cited line. At that time, there is no value assigned to the local name, though, hence the error. There ... | [
10
] | [] | [] | [
"function",
"python"
] | stackoverflow_0007999519_function_python.txt |
Q:
Trouble with zip function in for loop; python
Working in python 2.7.
I have two lists (simplified to make explanation more clear):
T = [[1, 0], [1, 0], [0, 5], [3, -1]]
B = [[1], [3], [2], [2]]
And three functions.
def exit_score(list):
exit_scores = []
length = len(list)
for i in range(0, length):
... | Trouble with zip function in for loop; python | Working in python 2.7.
I have two lists (simplified to make explanation more clear):
T = [[1, 0], [1, 0], [0, 5], [3, -1]]
B = [[1], [3], [2], [2]]
And three functions.
def exit_score(list):
exit_scores = []
length = len(list)
for i in range(0, length):
score = list[i][2] - list[i][0]
exit_... | [
"This time it's list.append(), not list.extend():\ndef score_add(team, exit_scores):\n for t, e in zip(team, exit_scores)\n t.append(e)\n print team\n\nB was a list of lists, while exit_scores is a list of integers.\nEdit: Here is a cleaned-up version of the whole code:\nfor t, b in zip(T, B):\n t.e... | [
4,
0
] | [] | [] | [
"for_loop",
"list",
"map",
"python",
"zip"
] | stackoverflow_0007999001_for_loop_list_map_python_zip.txt |
Q:
Getting Javascript to insert values into my textboxes (AJAX!)
So I have this code, which I am trying to use to make it update my form text boxes when I select a different drop down user.
Here's the code:
<script type="text/javascript">
document.getElementById("useruname").onchange = function() {
var selecteduname ... | Getting Javascript to insert values into my textboxes (AJAX!) | So I have this code, which I am trying to use to make it update my form text boxes when I select a different drop down user.
Here's the code:
<script type="text/javascript">
document.getElementById("useruname").onchange = function() {
var selecteduname = this.value;
}
var xmlhttp;
function loadXMLDoc()
{
if (window.X... | [
"I would seriously consider moving to using a client javascript library like jQuery.\nYour code would be simplified to something like this:\n<script type=\"text/javascript\">\n$(\"#useruname\").change = function() {\n var selecteduname = this.value;\n}\n\n\nfunction updateAdduser()\n{\n var fields = null;\n ... | [
2
] | [] | [] | [
"ajax",
"html",
"javascript",
"python",
"xmlhttprequest"
] | stackoverflow_0007999612_ajax_html_javascript_python_xmlhttprequest.txt |
Q:
'Pixel' object has no attribute 'setPixel' error, cannot figure out why this is
This code down below should draw two vertical lines, one red line from (50,0) to (50,300) and one made up of random pixels from (150,50) to (150,250). Where it says randomRed.setPixel(150,x,randomRed) on line 13, it points out that 'Pi... | 'Pixel' object has no attribute 'setPixel' error, cannot figure out why this is | This code down below should draw two vertical lines, one red line from (50,0) to (50,300) and one made up of random pixels from (150,50) to (150,250). Where it says randomRed.setPixel(150,x,randomRed) on line 13, it points out that 'Pixel' object has no attribute 'setPixel' error. I cannot figure out why this is an err... | [
"My guess would be that you are calling randomRed.setPixel(...) instead of lineImage.setPixel(...).\n",
"randomRed is a Pixel. Why would you set a pixel of a pixel? What are you expecting that to mean?\nYou're trying to draw the randomRed Pixel onto the same lineImage that you draw the redPixel onto, so both time... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007999666_python.txt |
Q:
Greedy match with negative lookahead in a regular expression
I have a regular expression in which I'm trying to extract every group of letters that is not immediately followed by a "(" symbol. For example, the following regular expression operates on a mathematical formula that includes variable names (x, y, and z... | Greedy match with negative lookahead in a regular expression | I have a regular expression in which I'm trying to extract every group of letters that is not immediately followed by a "(" symbol. For example, the following regular expression operates on a mathematical formula that includes variable names (x, y, and z) and function names (movav and movsum), both of which are compose... | [
"Add a word-boundary matcher \\b:\n>>> re.findall(r'[a-zA-Z]+\\b(?!\\()', \"movav(x/2, 2)*movsum(y, 3)*z\")\n['x', 'y', 'z']\n\n\\b matches the empty string in between two words, so now you're looking for letters followed by a word boundary that isn't immediately followed by (. For more details, see the re docs.\n"... | [
3,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007999568_python.txt |
Q:
How to generate a PDF from an HTML / CSS (including images) source in Python?
Let's say I've got an HTML / CSS page with some images in it, and I wanted to generate a PDF from that source in Python - possible?
A:
http://www.xhtml2pdf.com/
install was a little quirky for me, but otherwise it worked fine.
A:
You... | How to generate a PDF from an HTML / CSS (including images) source in Python? | Let's say I've got an HTML / CSS page with some images in it, and I wanted to generate a PDF from that source in Python - possible?
| [
"http://www.xhtml2pdf.com/\ninstall was a little quirky for me, but otherwise it worked fine.\n",
"You can do something like this using Pisa:\ndef receipt(request, id):\n import ho.pisa as pisa\n from django.template.loader import render_to_string\n from datetime import datetime\n\n r = get_or_404(id,... | [
4,
4,
4
] | [] | [] | [
"css",
"html",
"pdf",
"pdf_generation",
"python"
] | stackoverflow_0000786463_css_html_pdf_pdf_generation_python.txt |
Q:
Alternatives to pickle's `persistent_id`?
I have been using Python's pickle
module for implementing a thin file-based persistence layer. The
persistence layer (part of a larger library) relies heavily on pickle's persistent_id feature
to save objects of specified classes as separate files.
The only issue with thi... | Alternatives to pickle's `persistent_id`? | I have been using Python's pickle
module for implementing a thin file-based persistence layer. The
persistence layer (part of a larger library) relies heavily on pickle's persistent_id feature
to save objects of specified classes as separate files.
The only issue with this approach is that pickle files are not human
e... | [
"I haven't tried this yet myself, but I think you should be able to do this elegantly with PyYAML using what they call \"representers\" and \"resolvers\".\nEDIT\nAfter an extensive exchange of comments with the poster, here is a method to achieve the required behavior with PyYAML.\nImportant Note: If a Persistable ... | [
4
] | [] | [] | [
"json",
"persistence",
"pickle",
"python",
"yaml"
] | stackoverflow_0007939718_json_persistence_pickle_python_yaml.txt |
Q:
Does django natively integrate with HTTP Basic Authorization
ONe of my system components is using the Basic HTTP Authrozation ( http://en.wikipedia.org/wiki/Basic_access_authentication ) for log in information. Another part of my system is running a django application which uses the 'django.contrib.auth' app for a... | Does django natively integrate with HTTP Basic Authorization | ONe of my system components is using the Basic HTTP Authrozation ( http://en.wikipedia.org/wiki/Basic_access_authentication ) for log in information. Another part of my system is running a django application which uses the 'django.contrib.auth' app for authentication.
Would code like this work?
def urlHandler(request):... | [
"This has been asked and answered: Can I use HTTP Basic Authentication with Django?\n(The answer is yes. See http://docs.djangoproject.com/en/dev/howto/auth-remote-user/ for details.)\n"
] | [
1
] | [] | [] | [
"authentication",
"basic_authentication",
"django",
"http",
"python"
] | stackoverflow_0008000375_authentication_basic_authentication_django_http_python.txt |
Q:
How to access commit message from Mercurial Input or Changeset hook
I would like to write a hook for Mercurial to do the following, an am struggling to get going.:
Run on central repo, and execute when changeset(s) are pushed (I think I should use the "input" or "changegroup" hook)
Search each commit message for ... | How to access commit message from Mercurial Input or Changeset hook | I would like to write a hook for Mercurial to do the following, an am struggling to get going.:
Run on central repo, and execute when changeset(s) are pushed (I think I should use the "input" or "changegroup" hook)
Search each commit message for a string with the format "issue:[0-9]*"
IF string found, call a webservic... | [
"changegroup hook is called once per push. If you want to analyse each changeset, then you want incoming hook (there's no input hook AFAIK) — it'll be called for each changeset, with ID in HG_NODE environment variable. You can get the commit message with e.g. hg log -r $HG_NODE --template '{desc}' or via the API.\n... | [
2,
2
] | [] | [] | [
"hook",
"mercurial",
"mercurial_hook",
"python"
] | stackoverflow_0008000280_hook_mercurial_mercurial_hook_python.txt |
Q:
How to output XML entity references
I am using Python xml.etree.ElementTree to output XML. I want to output it with entity references that will be substituted when the XML is parsed.
ordinarily '&' is escaped as & because '&' is used to declare entity references. However, I really do want to write an entity ... | How to output XML entity references | I am using Python xml.etree.ElementTree to output XML. I want to output it with entity references that will be substituted when the XML is parsed.
ordinarily '&' is escaped as & because '&' is used to declare entity references. However, I really do want to write an entity reference. For example, I want to write ... | [
"I have decided to go with a relatively palatable hack. In the text, I use && to mean an escaped &. ElementTree converts this to &&. At the end, I simply do a string replacement on it:\n>>> from xml.etree.ElementTree import Element, tostring\n>>> manifest = Element('manifest')\n>>> manifest.text = '&&man... | [
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0007986272_elementtree_python_xml.txt |
Q:
Formatting output of a list in Python
I have a Python script that prints a set of nodes from a list on a unix console by category like so
node_name: 1) node_mgt 2) node103 3) node106 4) node107 5) node109 6) node110 7) node115 8) node116 9) node117 10) node120 11) node121 12) node122
node_sub1... | Formatting output of a list in Python | I have a Python script that prints a set of nodes from a list on a unix console by category like so
node_name: 1) node_mgt 2) node103 3) node106 4) node107 5) node109 6) node110 7) node115 8) node116 9) node117 10) node120 11) node121 12) node122
node_sub1: 170) node126 171) node210 172) node304 ... | [
"Hanging indents are possible using the textwrap module:\nimport textwrap\n\nlines=['node_name: 1) node_mgt 2) node103 3) node106 4) node107 5) node109 6) node110 7) node115 8) node116 9) node117 10) node120 11) node121 12) node122 ',\n'node_sub1: 170) node126 171) node210 172) node304 173) node413 ... | [
4,
1
] | [] | [] | [
"curses",
"python"
] | stackoverflow_0008000415_curses_python.txt |
Q:
Looking for *existing* Python module for determining fiscal months
I'm in calendar hell, and I'm hoping there exists a Python module out there that does what I want.
I'm making a Python web app that deals with subscriptions. It's conceptually similar to a cell phone plan: You start your subscription on a certain d... | Looking for *existing* Python module for determining fiscal months | I'm in calendar hell, and I'm hoping there exists a Python module out there that does what I want.
I'm making a Python web app that deals with subscriptions. It's conceptually similar to a cell phone plan: You start your subscription on a certain date (say 1.13.2011), and for every billing month you have a bunch of "se... | [
"http://labix.org/python-dateutil\nRam's edit: The dateutil.rrule.rrule class is the one that did exactly what I wanted.\n",
"\nRegarding start and end dates: If today is 2.15.2011, then the start date of the current month is 2.13.2011 and its end date is 3.13.2011.\nYou may be thinking this is not so complicated... | [
6,
2,
1
] | [] | [] | [
"billing",
"calendar",
"python"
] | stackoverflow_0008000162_billing_calendar_python.txt |
Q:
Trying to get one cell's values with MySQLdb
I am trying to get a single cell of values from MySQLdb, in Python. Here's my code:
fname = c.execute("""SELECT fname from employees WHERE user = %s;""", (useruname))
However what I get is "1L", which is not what I want - fname should contain a string, not a long integ... | Trying to get one cell's values with MySQLdb | I am trying to get a single cell of values from MySQLdb, in Python. Here's my code:
fname = c.execute("""SELECT fname from employees WHERE user = %s;""", (useruname))
However what I get is "1L", which is not what I want - fname should contain a string, not a long integer.
Why would it do this?
| [
"The method execute \"returns long integer rows affected, if any\".\nTo get the value of fname, you need to fetch the results using for example fetchall or fetchone:\ncursor.execute(\"\"\"SELECT fname from employees WHERE user = %s\"\"\", (useruname,))\nrow = cursor.fetchone()\nprint row[0]\n\n"
] | [
17
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0008001109_mysql_python.txt |
Q:
conversion from float to Decimal in python-2.6: how to do it and why they didn't do it
Direct conversion from float to Decimal was implemented in python-2.7, both in Decimal's constructor and with the Decimal.from_float() classmethod.
Python-2.6 instead throws a TypeError suggesting to convert to string first:
Typ... | conversion from float to Decimal in python-2.6: how to do it and why they didn't do it | Direct conversion from float to Decimal was implemented in python-2.7, both in Decimal's constructor and with the Decimal.from_float() classmethod.
Python-2.6 instead throws a TypeError suggesting to convert to string first:
TypeError: Cannot convert float to Decimal. First convert the float to a string
so my usual w... | [
"Your workaround is not the RightWayToDoIt(tm) because it loses information. The lossless way to convert is shown in the recipe for float_to_decimal() shown in the Decimal FAQ.\nThe reason we didn't include Decimal.from_float in Python 2.6 is because we were being conservative about introducing unintentional inter... | [
11,
4,
0
] | [] | [] | [
"decimal",
"floating_point",
"python"
] | stackoverflow_0008000318_decimal_floating_point_python.txt |
Q:
Python - Calling Linux command from Thread Pool not working
--Hi guys, --
I have about 4000 (1-50MB) files to sort.
I was thinking to have Python call the Linux sort command. And since I'm thinking this might be somewhat I/O bound, I would use the threading library.
So here's what I have but I when I run it and w... | Python - Calling Linux command from Thread Pool not working | --Hi guys, --
I have about 4000 (1-50MB) files to sort.
I was thinking to have Python call the Linux sort command. And since I'm thinking this might be somewhat I/O bound, I would use the threading library.
So here's what I have but I when I run it and watch the system monitor I don't see 25 sort tasks pop up. It see... | [
"You're doing everything correct. \nThere is something which is called GIL in python;\nGlobal Interpreter Lock - which eventually cause python to execute only one thread at time. \nChoose subprocess instead :), python is not multithreaded. \n",
"Actually this does seem to be working. I spoke too soon. I'm no... | [
1,
0,
0
] | [] | [] | [
"linux",
"multithreading",
"python",
"threadpool"
] | stackoverflow_0007998850_linux_multithreading_python_threadpool.txt |
Q:
%s Not Replacing Information
I am trying to put information available on the web, and to do so I am using string formatting:
fields = """{"fname" : %s, "lname" : %s, "email" : %s, "deptid" : deptid, "active" : active, "sentient" : sentient}""", (fname, lname, email)
with various values for each of the three varia... | %s Not Replacing Information | I am trying to put information available on the web, and to do so I am using string formatting:
fields = """{"fname" : %s, "lname" : %s, "email" : %s, "deptid" : deptid, "active" : active, "sentient" : sentient}""", (fname, lname, email)
with various values for each of the three variables.
Anyway, when I try to view f... | [
"fields = \"\"\"{\"fname\" : %s, \"lname\" : %s, \"email\" : %s, \"deptid\" : deptid, \"active\" : active, \"sentient\" : sentient}\"\"\" % (fname, lname, email)\n\nQuite simply, replace your comma (which constructs a tuple) with a % (which is the operator which does string formatting).\nAlso, I would recommend rep... | [
2,
2,
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008001337_python_string.txt |
Q:
How to make a canvas (rectangle) in wxpython?
I am trying to make a windows canvas type rectangle, here is an image if you are having issues understanding what i mean,
Is there any way todo this in wxpython? ( also, is there a way to set it to automatically adjust to the window width -20px?, so a radius around th... | How to make a canvas (rectangle) in wxpython? | I am trying to make a windows canvas type rectangle, here is an image if you are having issues understanding what i mean,
Is there any way todo this in wxpython? ( also, is there a way to set it to automatically adjust to the window width -20px?, so a radius around the window, and will adjust to the users window size.... | [
"EDIT: I asked on the wxPython IRC channel and a fellow named \"r4z\" came up with the following edit to my code which worked for me on Windows 7.\nimport wx\n\n########################################################################\nclass MyPanel(wx.Panel):\n \"\"\"\"\"\"\n\n #------------------------------... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008000987_python_wxpython.txt |
Q:
Dropping an external file into a QTreeWidget
I guess the implementation isn't quite the same for a QTreeWidget, but I'd like to be able to drop an external file, particularly an image or movie file into my QTreeWidget. I'm not trying to drag it into a specific QTreeWidgetItem, but rather just the tree as a whole. ... | Dropping an external file into a QTreeWidget | I guess the implementation isn't quite the same for a QTreeWidget, but I'd like to be able to drop an external file, particularly an image or movie file into my QTreeWidget. I'm not trying to drag it into a specific QTreeWidgetItem, but rather just the tree as a whole. Here's my code:
class moTree(QTreeWidget):
def... | [
"You need to reimplement QTreeWidget.mimeTypes so that it returns a list of the types you want to support:\ndef mimeTypes(self):\n return QtCore.QStringList([\n 'text/uri-list',\n 'application/x-qabstractitemmodeldatalist',\n ])\n\n"
] | [
6
] | [] | [] | [
"drag_and_drop",
"pyqt",
"pyside",
"python",
"qtreewidget"
] | stackoverflow_0008000490_drag_and_drop_pyqt_pyside_python_qtreewidget.txt |
Q:
reverse template with python
I have a file, full of data in a certain format, I want to fill my own data structure with that data
for example, I can have a file like this:
John - Smith : 0123
children:
Sam
Kim
I want to do something with that string, in order to extract the data into for example
firstName =... | reverse template with python | I have a file, full of data in a certain format, I want to fill my own data structure with that data
for example, I can have a file like this:
John - Smith : 0123
children:
Sam
Kim
I want to do something with that string, in order to extract the data into for example
firstName = "John"
lastName = "Smith"
number ... | [
"Here is a regex solution:\n>>> import re\n>>> data = 'John - Smith : 0123\\nchildren: \\n Sam\\n Kim'\n>>> match = re.match(r'(\\w+) - (\\w+) : (\\d+).*?children:(.*)', data, re.S)\n>>> match.groups()\n('John', 'Smith', '0123', ' \\n Sam\\n Kim')\n\nYou can then assign the groups to your variables:\n>>> firstN... | [
4
] | [] | [] | [
"python",
"regex",
"string",
"templates"
] | stackoverflow_0008001537_python_regex_string_templates.txt |
Q:
Get class instance where a certain property has a certain value
I'm sure there is a term for what I'm looking for, or if there's not, there is a very good reason what I'm trying to do is in fact silly.
But anyway. I'm wondering whether there is a (quasi) built-in way of finding a certain class instance that has a ... | Get class instance where a certain property has a certain value | I'm sure there is a term for what I'm looking for, or if there's not, there is a very good reason what I'm trying to do is in fact silly.
But anyway. I'm wondering whether there is a (quasi) built-in way of finding a certain class instance that has a property set to a certain value.
An example:
class Klass(object):
... | [
"Use filter:\nfilter(lambda obj: obj.value == 1, [a, b])\n\nFilter will return a list of objects which meet the requirement you specify. Docs: http://docs.python.org/library/functions.html#filter\nBascially, filter(fn, list) iterates over list, and applies fn to each item. It collects all of the items for which fn ... | [
4,
2
] | [] | [] | [
"class",
"python"
] | stackoverflow_0008001237_class_python.txt |
Q:
Work with instance in session before save in database
I have a system with several steps. Each step increments one single object instance.
I want to save the instance in db only in the final step, on others just update the instance I saved in the session.
My model class seems like this:
class Proposta(models.Model... | Work with instance in session before save in database | I have a system with several steps. Each step increments one single object instance.
I want to save the instance in db only in the final step, on others just update the instance I saved in the session.
My model class seems like this:
class Proposta(models.Model):
Modelo = models.ForeignKey("ModeloVersao", verbose_n... | [
"You might find the answers to this question helpful. \nSummary for quick reference:\n\nUse ModelForms - Based on the ModelForms documentation\nSave it to DB, but use a status field - I think this is less than ideal\n\nI might add that the documentation specifically explains how to deal with M2M fields, in the sect... | [
1
] | [] | [] | [
"django",
"many_to_many",
"mysql",
"python",
"session"
] | stackoverflow_0008001605_django_many_to_many_mysql_python_session.txt |
Q:
app engine python urlfetch timing out
I have two instances of app engine applications running that I want to communicate with a Restful interface. Once the data of one is updated, it calls a web hook on the second which will retrieve a fresh copy of the data for it's own system.
Inside 'site1' i have:
from goog... | app engine python urlfetch timing out | I have two instances of app engine applications running that I want to communicate with a Restful interface. Once the data of one is updated, it calls a web hook on the second which will retrieve a fresh copy of the data for it's own system.
Inside 'site1' i have:
from google.appengine.api import urlfetch
url = ww... | [
"App Engine's urlfetch doesn't always behave as it is expected, you have about 10 seconds to fetch the URL. Assuming the URL you're trying to fetch is up and running, you should be able to catch the DeadlineExceededError by calling from google.appengine.runtime import apiproxy_errors and then wrapping the urlfetch ... | [
3,
3,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"python",
"urlfetch"
] | stackoverflow_0006388778_google_app_engine_python_urlfetch.txt |
Q:
Creating a KML file from a XML file
How can I create KML files from the XML files using python.
I have a lot of XML files. I have already parsed the data from the XML files using the SAX parser.
Now I want to create KML files from the data that I have parsed.
Is there any other way apart from xml.dom.minidom to wr... | Creating a KML file from a XML file | How can I create KML files from the XML files using python.
I have a lot of XML files. I have already parsed the data from the XML files using the SAX parser.
Now I want to create KML files from the data that I have parsed.
Is there any other way apart from xml.dom.minidom to write the KML file.
I am currently thinking... | [
"Try xml.etree.ElementTree. Here's a short example creating a couple of points in a KML file:\nfrom xml.etree import ElementTree as et\n\nclass Kml(object):\n def __init__(self):\n self.root = et.Element('kml')\n self.doc = et.SubElement(self.root,'Document')\n\n def add_placemark(self,name,des... | [
2
] | [] | [] | [
"google_earth",
"kml",
"python",
"xml"
] | stackoverflow_0007999234_google_earth_kml_python_xml.txt |
Q:
Python extension module with variable number of arguments
I am trying to figure out how in C extension modules to have a variable (and maybe) quite large number of arguments to a function.
Reading about PyArg_ParseTuple it seems you have to know how many to accept, some mandatory and some optional but all with the... | Python extension module with variable number of arguments | I am trying to figure out how in C extension modules to have a variable (and maybe) quite large number of arguments to a function.
Reading about PyArg_ParseTuple it seems you have to know how many to accept, some mandatory and some optional but all with their own variable. I was hoping PyArg_UnpackTuple would be able ... | [
"I had used something like this earlier. It could be a bad code as I am not an experienced C coder, but it worked for me. The idea is, *args is just a Python tuple, and you can do anything that you could do with a Python tuple. You can check http://docs.python.org/c-api/tuple.html .\nint\nParseArguments(unsigned lo... | [
11
] | [] | [] | [
"c",
"python",
"python_c_extension"
] | stackoverflow_0008001923_c_python_python_c_extension.txt |
Q:
How to become productive using Vim/Emacs
I've been an Eclipse user for the last 3 years or more. I do Java EE (and Spring) development in it and so far I've done 90% of my tasks without having to touch the mouse. Typically my Eclipse setup is as follow:
Subclipse (or alternatively I use command line)
m2clipse (M... | How to become productive using Vim/Emacs | I've been an Eclipse user for the last 3 years or more. I do Java EE (and Spring) development in it and so far I've done 90% of my tasks without having to touch the mouse. Typically my Eclipse setup is as follow:
Subclipse (or alternatively I use command line)
m2clipse (Maven Eclipse plugin)
Data Source Explorer (de... | [
"If you ask a question which involves \"vim OR emacs\" you will never get an useful answer. It's a religious question, which does not have a correct answer! That said, you should clearly use Vim! ;-)\nBut seriously: Vim is much more lightweight, so it might better suite the scenario you are describing. Vim can be s... | [
5,
3,
2,
1,
1
] | [] | [] | [
"emacs",
"linux",
"python",
"ruby",
"vim"
] | stackoverflow_0008001384_emacs_linux_python_ruby_vim.txt |
Q:
How to set wx.LEFT and wx.TOP to two different values in Wxpython?
self.sizer.Add(self.listBox, proportion=0, flag=wx.TOP | wx.LEFT, border=75)
the border of BOTTOM and LEFT is 75, how can i set the border of wx.LEFT to something else
but still apply it to the same item.
Is there something like?:
wx.LEFT = 40
wx.... | How to set wx.LEFT and wx.TOP to two different values in Wxpython? | self.sizer.Add(self.listBox, proportion=0, flag=wx.TOP | wx.LEFT, border=75)
the border of BOTTOM and LEFT is 75, how can i set the border of wx.LEFT to something else
but still apply it to the same item.
Is there something like?:
wx.LEFT = 40
wx.TOP = 130
If I use my code, it will set both wx.LEFT and wx.TOP to 75 (w... | [
"The easiest way to do this is to nest sizers. So put this sizer itself in a second sizer with the border you want. \n"
] | [
3
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008001997_python_wxpython.txt |
Q:
Can fabric tasks have names that are not valid Python function names?
I'd like my Fabric tasks to have hyphens (-) instead of underscores (_). For example, database-reset instead of database_reset. However, hyphens aren't permitted as Python function names.
Is it possible in Fabric to create tasks whose names do ... | Can fabric tasks have names that are not valid Python function names? | I'd like my Fabric tasks to have hyphens (-) instead of underscores (_). For example, database-reset instead of database_reset. However, hyphens aren't permitted as Python function names.
Is it possible in Fabric to create tasks whose names do not exactly match the corresponding Python function?
| [
"From the documentation:\n@task(alias = 'database-reset')\ndef database_reset():\n ...\n\n",
"Cat Plus Plus has the best solution to what you want to do. Tangentially, however, it is technically possible to have Python global variables (a function name is just a global variable) that don't conform to the usual... | [
6,
3
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0008001777_fabric_python.txt |
Q:
Move a ball inside Tkinter Canvas Widget (simple Arkanoid game)
I'm trying to write a simple Arkanoid with the help of Python and Tkinter. The goal is to make the ball reflect from the top, right and left sides. And if the player misses the ball so it touches the bottom side, the game would stop.
Here's the code:
... | Move a ball inside Tkinter Canvas Widget (simple Arkanoid game) | I'm trying to write a simple Arkanoid with the help of Python and Tkinter. The goal is to make the ball reflect from the top, right and left sides. And if the player misses the ball so it touches the bottom side, the game would stop.
Here's the code:
from Tkinter import *
import time
root = Tk()
canv = Canvas(root, hi... | [
"To move an object you need to use the coords method or the move method, which changes the coordinates of the object. You can use the coords method to get the current coordinates.\nTo do the animation you can use after. Call a function, then have it use after to call itself again a short time in the future. How far... | [
13,
-2
] | [] | [] | [
"canvas",
"python",
"tkinter"
] | stackoverflow_0007984655_canvas_python_tkinter.txt |
Q:
Reading from csv file Python
I am trying to solve this problem.
I am reading data from csv fiile which has the following columns:
id, name, price
So i use the following code to read the csv:
import sys
import csv as input
def readFile(path):
try:
finput = input.reader(open(path,'rb'),delimiter=',',qu... | Reading from csv file Python | I am trying to solve this problem.
I am reading data from csv fiile which has the following columns:
id, name, price
So i use the following code to read the csv:
import sys
import csv as input
def readFile(path):
try:
finput = input.reader(open(path,'rb'),delimiter=',',quotechar='|')
except IOError as... | [
"Just make sure that any single values that contain your delimiter char (,) are enclosed in the quotechar (|, in your example). Thus, any time the name field in a row is of the form <name>, <item_det> the row should read something like ... ,|<name>, <item_det>|, ....\n",
"CSV is exactly that: \"Comma Separated\".... | [
1,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008002495_csv_python.txt |
Q:
Is there any way to sort nested lists without using operator.itemgetter?
I have a file that i'm reading in, then creating nested lists that i want to then sort on the 4 element(zipcode)
jk43:23 Marfield Lane:Plainview:NY:10023
axe99:315 W. 115th Street, Apt. 11B:New York:NY:10027
jab44:23 Rivington Street, Apt. 3R... | Is there any way to sort nested lists without using operator.itemgetter? | I have a file that i'm reading in, then creating nested lists that i want to then sort on the 4 element(zipcode)
jk43:23 Marfield Lane:Plainview:NY:10023
axe99:315 W. 115th Street, Apt. 11B:New York:NY:10027
jab44:23 Rivington Street, Apt. 3R:New York:NY:10002
ap172:19 Boxer Rd.:New York:NY:10005
jb23:115 Karas Dr.:Jer... | [
"Oh yes, there is a way:\nprint sorted(data,key=lambda x: x[4])\n\n",
"A rough workalike would be:\nprint sorted(data, key=lambda items: items[4])\n\nbut operator.itemgetter is a bit faster. I'm using this program to benchmark both approaches:\n#!/usr/bin/env python\n\nimport timeit\n\nwithlambda = 'lst.sort(key=... | [
6,
4,
0
] | [] | [] | [
"nested_lists",
"python",
"sorting"
] | stackoverflow_0008002374_nested_lists_python_sorting.txt |
Q:
Difference between HDF5 file and PyTables file
Is there a difference between HDF5 files and files created by PyTables?
PyTables has two functions .isHDFfile() and .isPyTablesFile() suggesting that there
is a difference between the two formats.
I've done some looking around on Google and have gathered that PyTable... | Difference between HDF5 file and PyTables file | Is there a difference between HDF5 files and files created by PyTables?
PyTables has two functions .isHDFfile() and .isPyTablesFile() suggesting that there
is a difference between the two formats.
I've done some looking around on Google and have gathered that PyTables is built on top of HDF, but I wasn't able to find ... | [
"PyTables files are HDF5 files.\nHowever, as I understand it, PyTables adds some extra metadata to the attributes of each entry in the HDF file.\nIf you're looking for a more \"vanilla\" hdf5 solution for python/numpy, have a look a h5py.\nIt's less database-like (i.e. less \"table-like\") than PyTables, and doesn'... | [
17
] | [] | [] | [
"hdf5",
"numpy",
"pytables",
"python"
] | stackoverflow_0008002569_hdf5_numpy_pytables_python.txt |
Q:
Web based large files upload with resume facility in django or asp.net
We are looking for an approach for developing a web based application which should have facility to upload large files (size upto 10 GB) with resume facility.
We want to develop this application using python/django or C#/asp.net.
Any suggestio... | Web based large files upload with resume facility in django or asp.net | We are looking for an approach for developing a web based application which should have facility to upload large files (size upto 10 GB) with resume facility.
We want to develop this application using python/django or C#/asp.net.
Any suggestion would be appreciated.
| [
"plupload with the Java backend will support files up to any size.\nhttps://github.com/jakobadam/plupload-java-runtime\nYou will need to port the uploading portion to Django. It would be something like this. Although this does not do any checksum verification.\ndef fileUpload(request):\n \"\"\"file upload for p... | [
1,
0
] | [] | [] | [
"asp.net",
"django",
"file_upload",
"python",
"uploading"
] | stackoverflow_0003699968_asp.net_django_file_upload_python_uploading.txt |
Q:
Cant find out if this is the right code?
Hello I have to program the question bellow ( my code is under that) However once your read the question you will understand that I need the code to also add all the previous numbers. If someone could see my code and tell me if it is already doing that and if not how I coul... | Cant find out if this is the right code? | Hello I have to program the question bellow ( my code is under that) However once your read the question you will understand that I need the code to also add all the previous numbers. If someone could see my code and tell me if it is already doing that and if not how I could go about it I tried something which didn't w... | [
"count=0\nnumber1=1\nnum=2\n\nwhile count<63:\n num=num*2\n count+=1\n\nprint\"He payed \",num,\" Pounds.\"\n\nA few comments: you're not using number1 in your code -- it's best to remove unused variables, as their presence can easily distract you from the real flow of the code. Second, because you're starting ... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008003126_python.txt |
Q:
skipping a line while reading a file with a for loop
I am trying to figure out a way to skip the next two lines in a file if a condition in the first line is true. Any ideas on a good way to do this? Here's what I have so far...
def main():
file = open(r'C:\Users\test\Desktop\test2.txt', 'r+')
ctr = 1
... | skipping a line while reading a file with a for loop | I am trying to figure out a way to skip the next two lines in a file if a condition in the first line is true. Any ideas on a good way to do this? Here's what I have so far...
def main():
file = open(r'C:\Users\test\Desktop\test2.txt', 'r+')
ctr = 1
for current_line in file:
assert ctr<3
... | [
"In Python 2.6 or above, use\nnext(file)\nnext(file)\n\nto skip two items of the iterator file, i.e. the next two lines.\n",
"file.next()\nfile.next()\n\ni'd do this way...\n"
] | [
4,
1
] | [] | [] | [
"file_io",
"for_loop",
"iterator",
"python"
] | stackoverflow_0008003293_file_io_for_loop_iterator_python.txt |
Q:
Numpy vectorization algorithms to sum up numbers with the same time stamps
I have two arrays P and T. P[i] is a number, whose time stamp is T[i]; There might be duplicated time stamps.
I want to produce another two arrays Q and U, where Q[i] has time stamp U[i], and Q[i] is the sum of all elements in P that have ... | Numpy vectorization algorithms to sum up numbers with the same time stamps | I have two arrays P and T. P[i] is a number, whose time stamp is T[i]; There might be duplicated time stamps.
I want to produce another two arrays Q and U, where Q[i] has time stamp U[i], and Q[i] is the sum of all elements in P that have time stamp U[i];
For example, for
P = [1, 2, 3, 4, 5]
T = [0, 0, 1, 1, 1]
I wi... | [
"Using numpy 1.4 or better:\nimport numpy as np\n\nP = np.array([1, 2, 3, 4, 5]) \nT = np.array([0, 0, 1, 1, 1])\n\nU,inverse = np.unique(T,return_inverse=True)\nQ = np.bincount(inverse,weights=P)\nprint (Q, U)\n# (array([ 3., 12.]), array([0, 1]))\n\n\nPlease note that this is not the fastest solution. I tested ... | [
4,
2,
1
] | [] | [] | [
"numpy",
"python",
"vectorization"
] | stackoverflow_0008003046_numpy_python_vectorization.txt |
Q:
How to change data in the container while iterating in python
Given the following example:
container = [ (1, "a") ,
(40, "b") ,
(24, "c") , #we intend to change this
(103, "d")
]
for k,v in container:
if k == 24:
v += " good"
print container
Th... | How to change data in the container while iterating in python | Given the following example:
container = [ (1, "a") ,
(40, "b") ,
(24, "c") , #we intend to change this
(103, "d")
]
for k,v in container:
if k == 24:
v += " good"
print container
The (24, "c") data pair in container will still remain its original v... | [
"You can use enumerate() the keep track of the index of the container item you are looking at:\nfor i, (k,v) in enumerate(container):\n if k == 24:\n container[i] = (k, v+\" good\")\n\n",
"Messed up a bit. Fixed now\ncontainer = [ (1, \"a\") , \n (40, \"b\") ,\n (24, \"... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0008003428_python.txt |
Q:
If I have a list of things, how do I associate a item to those things? Python
So I have an assignment that is due later tonight and I'm stuck on this one definition. What I have is a list of random terms:
['i', 'am', 'a', 'brown', 'cow']
And what I want to do with this list is associate each term to a value/term:... | If I have a list of things, how do I associate a item to those things? Python | So I have an assignment that is due later tonight and I'm stuck on this one definition. What I have is a list of random terms:
['i', 'am', 'a', 'brown', 'cow']
And what I want to do with this list is associate each term to a value/term:
[['i', ['term']], ['am', ['term']], ['a', ['term']], ['brown', ['term']], ['cow', ... | [
"Take a look at pythons zip() function.\nAlso python list comprehension may come handy sometimes in these kind of problems.\n",
"If you are a beginner in Python, the most obvious option probably would be simple loop approach:\nd = {}\nlst = ['i', 'am', 'a', 'brown', 'cow']\nfor key in lst:\n d[key] = 'term'\n\nA... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008003436_python.txt |
Q:
Prime number checker function is faulty
I wrote a function to calculate whether or not a number is prime, but try as it might, it just seems unable to give the correct response. It also prints the n value that is being incremented. Here is the code for the function (in Python, by the way):
def isPrime(x):
for ... | Prime number checker function is faulty | I wrote a function to calculate whether or not a number is prime, but try as it might, it just seems unable to give the correct response. It also prints the n value that is being incremented. Here is the code for the function (in Python, by the way):
def isPrime(x):
for n in range(1, x):
print n
if ... | [
"Every number is divisible by 1 and itself. A prime number is a natural number that has no positive divisors other than 1 and itself. Therefore, if you start your for-loop with 1, every number x will pass the condition x % 1 == 0 in the first iteration, returning False. \nTo fix it, you need to start your loop with... | [
6
] | [] | [] | [
"primes",
"python"
] | stackoverflow_0008003669_primes_python.txt |
Q:
how to get lines by blocks
Pretty easy question below
From the code below 'data' is made by a column of numbers, let's say 12 numbers (see below)
def block_generator():
with open ('test', 'r') as lines:
data = lines.readlines ()[5::]
for line in data:
if not line.startswith (" "): # this a... | how to get lines by blocks | Pretty easy question below
From the code below 'data' is made by a column of numbers, let's say 12 numbers (see below)
def block_generator():
with open ('test', 'r') as lines:
data = lines.readlines ()[5::]
for line in data:
if not line.startswith (" "): # this actually gives me the column of 1... | [
"the itertools module provides a recipe that does just what you need:\nfrom itertools import izip_longest\n\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\nWhich looks like:\n>>> c... | [
2
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0008003593_iterator_python.txt |
Q:
Lost with encodings (shell and accents)
I'm having trouble with encodings.
I'm using version
Python 2.7.2+ (default, Oct 4 2011, 20:03:08)
[GCC 4.6.1] on linux2
I have chars with accents like é à.
My scripts uses utf-8 encoding
#!/usr/bin/python
# -*- coding: utf-8 -*-
Users can type strings usings raw_in... | Lost with encodings (shell and accents) | I'm having trouble with encodings.
I'm using version
Python 2.7.2+ (default, Oct 4 2011, 20:03:08)
[GCC 4.6.1] on linux2
I have chars with accents like é à.
My scripts uses utf-8 encoding
#!/usr/bin/python
# -*- coding: utf-8 -*-
Users can type strings usings raw_input() with .
def rlinput(prompt, prefill=''):... | [
"Standard input and output are byte-based on all Unix systems. That's why you have to call the unicode function to get character-strings for them. The decode error indicates that the bytes coming in are not valid UTF-8.\nBasically, the problem is the assumption of UTF-8 encoding, which is not guaranteed. Confirm... | [
2,
0
] | [] | [] | [
"diacritics",
"encoding",
"python",
"shell"
] | stackoverflow_0007992648_diacritics_encoding_python_shell.txt |
Q:
Python: SQL Query and save it in dictionary (Bit Complicated data structure)
Based on couple of Api Calls I have constructed the following data structure (Dictionary). I have used python dictionary as a holding place.
325167 A,
953929 B, A, C
824420 D, B,
796992 K, M, Z,
825116 J, F, E,
I take the each value, and... | Python: SQL Query and save it in dictionary (Bit Complicated data structure) | Based on couple of Api Calls I have constructed the following data structure (Dictionary). I have used python dictionary as a holding place.
325167 A,
953929 B, A, C
824420 D, B,
796992 K, M, Z,
825116 J, F, E,
I take the each value, and send a query to the database and get a results set select something from some_tab... | [
"...\n while not done:\n categoryRow = cursor.fetchone();\n print categoryRow;\n if not categoryRow:\n done = True;\n continue;\n categoryResults.append(categoryRow['cl_to']);\n\n...\ncontinue will wrap to the w... | [
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008003606_dictionary_python.txt |
Q:
Using Python to verify the mouse position is within the circle, when clicking anywhere within the circle.
I am working on a project within Python that is to determine the multi-tasking efficiency of a person. Part of the project is to have a user respond to an event on screen using the mouse. I have decided to hav... | Using Python to verify the mouse position is within the circle, when clicking anywhere within the circle. | I am working on a project within Python that is to determine the multi-tasking efficiency of a person. Part of the project is to have a user respond to an event on screen using the mouse. I have decided to have the user click within a ball. However I am having issues with my code on verifying that the mouse cursor is a... | [
"I don't know pygame, but perhaps you want something like this:\ndistance = sqrt((mouse_position.x - the_ball.x)**2 + (mouse_position.y - the_ball.y)**2)\n\nThis is the standard distance formula to get the distance between the mouse position and the center of the ball. Then you'll want to do:\nreturn distance <= ci... | [
5,
1,
1
] | [] | [] | [
"boolean",
"mouseevent",
"pygame",
"python"
] | stackoverflow_0008003728_boolean_mouseevent_pygame_python.txt |
Q:
Web2py CRUD.read() record created though non-filled condition
So i worte a function in Web2py to create a record into a table in the Database under a Condition, but Web2py create the record allthough that condition is not filled,
here is the function
def buy_product():
price = price_set(db,auth,'product')
... | Web2py CRUD.read() record created though non-filled condition | So i worte a function in Web2py to create a record into a table in the Database under a Condition, but Web2py create the record allthough that condition is not filled,
here is the function
def buy_product():
price = price_set(db,auth,'product')
balance = limit(db,auth,'settings','account_balance')
if balan... | [
"Crud manages inserts/updates internally and it does not use the form.accepts.\nYou have two options:\n1 - Use SQLFORM\n form=SQLFORM(db.letter)\n if form.accepts(request.vars, session):\n tax = float(postage(form.vars.tax_type).replace(\"-\",\".\"))\n ##########################\n # I'm t... | [
3
] | [] | [] | [
"crud",
"python",
"web2py"
] | stackoverflow_0008000602_crud_python_web2py.txt |
Q:
Reading .csv files into Python lists
I have a lot of .csv files in a directory and I'd like to open each of them in a loop within Python such that the first .csv is read into list[0] and the second .csv is read into list[1] and so on.
Unfortunately, while my code loops through all of the .csv files, it puts all th... | Reading .csv files into Python lists | I have a lot of .csv files in a directory and I'd like to open each of them in a loop within Python such that the first .csv is read into list[0] and the second .csv is read into list[1] and so on.
Unfortunately, while my code loops through all of the .csv files, it puts all the .csv files into list[0]. How can I modif... | [
"inside the for loop, near the top, you have to refresh the list rowdata. otherwise you are adding to that one forever. have something like rowdata = [] right after print i\ndef create_data_lists():\n\n for symbol in symbols:\n with open(symbol+'.csv', 'r') as f:\n print symbol\n rowdata =... | [
10,
5
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008003858_csv_python.txt |
Q:
html parser python
I am trying to parse a website. I am using the HTMLParser module. The problem is i want to parse the first <a href=""> after the comment: <!-- /topOfPage -->, but I don't really know how to do it. So I have found in the documentation that there is an function which is called handle_comment, but ... | html parser python | I am trying to parse a website. I am using the HTMLParser module. The problem is i want to parse the first <a href=""> after the comment: <!-- /topOfPage -->, but I don't really know how to do it. So I have found in the documentation that there is an function which is called handle_comment, but I haven't found out how... | [
"You need an additional variable to indicate that the parser has just come past to the comment, so that you can save the reference from the first link after it.\ndef __init__(self, *args, **kwargs):\n # ...\n self.first_link_after_comment = False\n\nThen, when you encounter the comment, the flag must be switc... | [
2,
1
] | [] | [] | [
"html_parsing",
"python"
] | stackoverflow_0008003173_html_parsing_python.txt |
Q:
pyQt Hover event with Svg image
I've been working on this for some time now and I can't figure out what I'm doing wrong. I hope someone here can help.
I'm trying to get hover events to work when I mouse over an Svg item that's in a QGraphicsScene. Here's the code that I've been playing with.
#!/usr/bin/python
im... | pyQt Hover event with Svg image | I've been working on this for some time now and I can't figure out what I'm doing wrong. I hope someone here can help.
I'm trying to get hover events to work when I mouse over an Svg item that's in a QGraphicsScene. Here's the code that I've been playing with.
#!/usr/bin/python
import sys
from PyQt4.QtGui import *
fr... | [
"You are monitoring hover events for MySvg but you are adding another QGraphicsSvgItem to the view that is just an instance (MySvg.image) in MySvg. Your MySvg is not even in the view. Try like this:\n#!/usr/bin/python\n\nimport sys\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtSvg import *\n\... | [
4
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0008004037_pyqt_python.txt |
Q:
Submit a form without refreshing/redirecting of the current page (Python (Django) + jQuery + Ajax)
Any way to submit a form without refreshing the current page at all using Python with jQuery Ajax? I want the end results similar to how Facebook comment works.
I'm currently using jQuery Form to do the Ajax. However... | Submit a form without refreshing/redirecting of the current page (Python (Django) + jQuery + Ajax) | Any way to submit a form without refreshing the current page at all using Python with jQuery Ajax? I want the end results similar to how Facebook comment works.
I'm currently using jQuery Form to do the Ajax. However, it doesn't give me the user experience that I want because:
After submitting using jQuery Form, the U... | [
"You could handle this by instead of using jquery's form, use jquery's ajaxPost. This will allow you to .serialize() the form (to get the parameters) and be able to return to a JS function to do what you want after the 'form is submitted'. Check out jQuery.post()\njsFiddle\nThis will not refresh the page as the pos... | [
8,
3,
1
] | [] | [] | [
"ajax",
"django",
"jquery",
"python"
] | stackoverflow_0007945848_ajax_django_jquery_python.txt |
Q:
Is this possible to dynamically to generate an attribute in a python object?
For example, the object only have two attributes, person object, in this example,
only have first name, and second name.
Is this possible to make a gender attribute on the fly? Thanks.
A:
short answer: yes
class Person(object):
d... | Is this possible to dynamically to generate an attribute in a python object? | For example, the object only have two attributes, person object, in this example,
only have first name, and second name.
Is this possible to make a gender attribute on the fly? Thanks.
| [
"short answer: yes\nclass Person(object):\n def __init__(self):\n self.first_name = 'Will'\n self.second_name = 'Awesome'\n\nmy_guy = Person()\nmy_guy.gender = \"Male\"\nprint(my_guy.gender)\n\nwill print Male\n",
"In case you even know what this attribute is called when you write code, you can\n... | [
8,
2
] | [] | [] | [
"dynamic",
"object",
"python",
"python_3.x"
] | stackoverflow_0008004178_dynamic_object_python_python_3.x.txt |
Q:
Any python libs for parsing Bind zone files?
Any python libs for parsing Bind zone files?
Basically something that will aid in adding/removing zones and records.
This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution.
A:
easyzone is a nice ... | Any python libs for parsing Bind zone files? | Any python libs for parsing Bind zone files?
Basically something that will aid in adding/removing zones and records.
This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution.
| [
"easyzone is a nice layer over dnspython\nZoner provides a web-interface for editing zone files and makes use of easyzone.\n",
"I was unable to use bicop for classical zone files like these:\n $TTL 86400\n@ IN SOA ns1.first-ns.de. postmaster.robot.first-ns.de. (\n 2006040800 ; serial\n 14400 ;... | [
7,
6,
0,
0
] | [] | [] | [
"bind",
"python"
] | stackoverflow_0000236859_bind_python.txt |
Q:
How to crawl a site using Python and Mechanize
How can I use Mechanize with Python to crawl a website, recursively following every link on every page?
Every example I've seen in tutorials and Mechanize documentation shows how to follow a browsing "path" if I can call it that (e.g. go to home page, populate a form,... | How to crawl a site using Python and Mechanize | How can I use Mechanize with Python to crawl a website, recursively following every link on every page?
Every example I've seen in tutorials and Mechanize documentation shows how to follow a browsing "path" if I can call it that (e.g. go to home page, populate a form, press submit, do something with the response), rath... | [
"here is some psudo code to get you started, let me know if you need more:\nbr = make browser object\nvisited=set()\nmax_depth=10\ndef crawl_all_links(browser,depth):\n if depth <= max_depth:\n for link in browser.links():\n if link not in visited:\n visited.add(link)\n ... | [
2
] | [] | [] | [
"mechanize",
"python",
"web_crawler"
] | stackoverflow_0008003979_mechanize_python_web_crawler.txt |
Q:
Can I use python static variables to communicate between two modules?
I have two files, one that performs a step in an automated test and a second that stores and emails the test results. Both files are kicked off using a Hudson server and I need the first module to share information with the second, but when I ac... | Can I use python static variables to communicate between two modules? | I have two files, one that performs a step in an automated test and a second that stores and emails the test results. Both files are kicked off using a Hudson server and I need the first module to share information with the second, but when I access the static variables in the Reporter module, they have the initial val... | [
"No. The problem is that only one module can be \"__main__\", therefore only one main stanza will be run.\nThere's nothing wrong with your code though, except that you import Monkey_Reporter when you probably mean to import Reporter. And no, accessing it via reports wouldn't change anything; they're still the same ... | [
2
] | [] | [] | [
"python",
"static_members"
] | stackoverflow_0008004477_python_static_members.txt |
Q:
SWIG: Add comments to generated .py file
Using SWIG to generate a Python interface to a C++ application, is there any way to have it comment the functions in the generated .py file? I'm actually pulling in an entire .h file into the .i file, but for a small example:
%module example
bool do_something_interesting(i... | SWIG: Add comments to generated .py file | Using SWIG to generate a Python interface to a C++ application, is there any way to have it comment the functions in the generated .py file? I'm actually pulling in an entire .h file into the .i file, but for a small example:
%module example
bool do_something_interesting(int number, string text);
swig -python example... | [
"Look at the docstring feature in SWIG for Python.\nProbably putting the following line in your .i file\n%feature(\"autodoc\", \"1\")\n\nwould do what you want (see http://www.swig.org/Doc2.0/Python.html#Python_nn65 for more options)\n"
] | [
6
] | [] | [] | [
"c++",
"comments",
"python",
"swig"
] | stackoverflow_0008001082_c++_comments_python_swig.txt |
Q:
python: functions
I am attempting to create a text-based adventure game for class, but I have been experiencing problems in getting the 'use' function to work when using an item in inventory.
The game has 2 interactive menus, the main menu (where you can travel, search, display and use inventory, display an ASCII... | python: functions | I am attempting to create a text-based adventure game for class, but I have been experiencing problems in getting the 'use' function to work when using an item in inventory.
The game has 2 interactive menus, the main menu (where you can travel, search, display and use inventory, display an ASCII map, or quit) and the ... | [
"There are two issues that stand out to me. First, use(...) is returning a boolean value, not the item used. No matter what the item used is, use(...) will return True. Second, in the eHouseAction method, you are testing to see if the value returned from showInv(...) is equal to True.\nSince use(...) returns Tru... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008005188_python.txt |
Q:
Email body text?
hi everyone I am using a script which involves:
import oauth2 as oauth
import oauth2.clients.imap as imaplib
import email
conn = imaplib.IMAP4_SSL('imap.googlemail.com')
conn.debug = 4
# This is the only thing in the API for impaplib.IMAP4_SSL that has
# changed. You now authenticate with the U... | Email body text? | hi everyone I am using a script which involves:
import oauth2 as oauth
import oauth2.clients.imap as imaplib
import email
conn = imaplib.IMAP4_SSL('imap.googlemail.com')
conn.debug = 4
# This is the only thing in the API for impaplib.IMAP4_SSL that has
# changed. You now authenticate with the URL, consumer, and toke... | [
"From email docs:\n\nYou can pass the parser a string or a file object, and the parser will\n return to you the root Message instance of the object structure.\nFor simple, non-MIME messages the payload of this root object will\n likely be a string containing the text of the message. For MIME\n messages, the root... | [
4
] | [] | [] | [
"email",
"python"
] | stackoverflow_0008005320_email_python.txt |
Q:
How can I detect whether a given line in a file is a proper English sentence?
I need to detect if a given "line" in a file is an English sentence or not. I am using Python. An approximate answer would do. I understand this is an NLP question but is there a lightweight tool that gives a reasonable approximation? I ... | How can I detect whether a given line in a file is a proper English sentence? | I need to detect if a given "line" in a file is an English sentence or not. I am using Python. An approximate answer would do. I understand this is an NLP question but is there a lightweight tool that gives a reasonable approximation? I do not want to use a full-fledged NLP toolkit for this though if that is the only w... | [
"Perhaps you are looking for Punkt Tokenizer from the nltk library, which can provide you the english sentences from a given text. You can then act upon the sentences by doing a grammar check(pointed out by Acron)\n",
"Currently, computer software cannot tell you whether a given string of tokens is a grammatical ... | [
2,
1,
0
] | [] | [] | [
"nlp",
"python"
] | stackoverflow_0005927688_nlp_python.txt |
Q:
What is causing this djcelery error: NotRegistered?
Running this script in a django shell:
import processors.topics.tasks as t
t.test.delay()
Gives this error:
NotRegistered: 'processors.topics.tasks.test'
The weird thing is that chorus.processors.topics.tasks.test is definitely included in the [Tasks] printout ... | What is causing this djcelery error: NotRegistered? | Running this script in a django shell:
import processors.topics.tasks as t
t.test.delay()
Gives this error:
NotRegistered: 'processors.topics.tasks.test'
The weird thing is that chorus.processors.topics.tasks.test is definitely included in the [Tasks] printout when I run
python celeryd --verbosity=2 --loglevel=INFO -... | [
"It has to do with the way you are importing the task for example, You are importing the task from the project instead of the app, chorus.processors.topics tasks instead of processors.topics.tasks. This creates problems for Celery, since the name will be different in the client and the server.\nHere are the docs th... | [
1
] | [] | [] | [
"django",
"django_celery",
"python"
] | stackoverflow_0008005311_django_django_celery_python.txt |
Q:
How do I write multi enter box input into .txt?
How do I make it so that "file.write(repr(fieldNames1))" writes what I input into "fieldNames1"?
import easygui
#Multi Enter Box
fieldNames1= ['Situation:(Example: Waiting for a friend who is late.)','Thoughts:(EXAMPLE: My friend Bob is always late!)','Emotions:(EXA... | How do I write multi enter box input into .txt? | How do I make it so that "file.write(repr(fieldNames1))" writes what I input into "fieldNames1"?
import easygui
#Multi Enter Box
fieldNames1= ['Situation:(Example: Waiting for a friend who is late.)','Thoughts:(EXAMPLE: My friend Bob is always late!)','Emotions:(EXAMPLE: Mad & Stressed)','Behavior:(EXAMPLE: Arguing wi... | [
"The problem is that calling repr() on the list will create a single string from the list. What you're wanting is something like:\nf = open('output.txt', 'a')\nf.write('\\n'.join(fieldNames1))\nf.close()\n\nThe write() method doesn't automatically create newlines, so you have join() the list of strings together usi... | [
2
] | [] | [] | [
"easygui",
"python",
"text_files",
"tkinter"
] | stackoverflow_0008005349_easygui_python_text_files_tkinter.txt |
Q:
python, how to call function in as parameter in self.response.out.write()
class GuestBook(webapp.RequestHandler):
def post(self):
self.response.out.write(
'<h2>You wrote:</h2> %s' %self.request.get('content') )
I want to pass this: %self.request.get('content') into a function. And u... | python, how to call function in as parameter in self.response.out.write() | class GuestBook(webapp.RequestHandler):
def post(self):
self.response.out.write(
'<h2>You wrote:</h2> %s' %self.request.get('content') )
I want to pass this: %self.request.get('content') into a function. And use function return in the old place.I am python newbie. I tried.but failed. nee... | [
"First of all you ought to (re-)read about string interpolation\nThe % is an operator applicable to string and unicode objects, so such an object must precede its usage. So you could do\ndef ept(s):\n return \"%s is good\" % s\n\nept(self.request.get('content'))\n\n% is applicable to integers as well, but that's... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008005626_python.txt |
Q:
postgresql+python: how to adapt for copy_from?
What function can I use to adapt values for suitable use in a COPY FROM statement? I tried this adapt function:
from psycopg2.extensions import adapt
However, it gives the wrong thing for datetimes (appends ::timestsamp to the string, postgres doesn't like it) and st... | postgresql+python: how to adapt for copy_from? | What function can I use to adapt values for suitable use in a COPY FROM statement? I tried this adapt function:
from psycopg2.extensions import adapt
However, it gives the wrong thing for datetimes (appends ::timestsamp to the string, postgres doesn't like it) and string (wraps them in single quotes, e.g. empty string... | [
"You shouldn't just use adapt with copy_from.\ncopy_from expects a format different than SQL quoting.\nFor strings, I'd suggest to write your own copy_adapt function, which should escape tabs with \\t, CR with \\r and LF with \\n. \nValues for timestamp / date columns should be formatted (with strftime?) like the s... | [
1
] | [] | [] | [
"database",
"postgresql",
"python",
"sql",
"sqlbulkcopy"
] | stackoverflow_0008002555_database_postgresql_python_sql_sqlbulkcopy.txt |
Q:
Efficiently querying extra fields on Django ManyToMany Through
Let's assume models that look like this:
class GraphNode(models.Model):
name = models.CharField(...)
edges = models.ManyToManyField('self', through=Edge,
symmetrical=False)
class Edge(models.Model):
sou... | Efficiently querying extra fields on Django ManyToMany Through | Let's assume models that look like this:
class GraphNode(models.Model):
name = models.CharField(...)
edges = models.ManyToManyField('self', through=Edge,
symmetrical=False)
class Edge(models.Model):
source = models.ForeignKey(GraphNode, ...)
destination = models.For... | [
"Your mistake #1 is trying to use Edge as a ManyToMany connection table to itself. If you use via parameter, it has to be a 3rd table. It's impossible in relation algebra to do m2m via one of the two tables.\nSecondly, you don't need many to many here. With many to many you can't set a limit on a number of nodes in... | [
0
] | [] | [] | [
"django",
"django_models",
"django_orm",
"python"
] | stackoverflow_0008004757_django_django_models_django_orm_python.txt |
Q:
boost::python and swig integration
I have two classes, the first called "Radish" and the second called "RadishCont".
All the code is written in C++ and need to be used in python.
Radish have been exposed to python using SWIG; RadishCont, instead, have been exposed using boost::python.
I need to add a method into t... | boost::python and swig integration | I have two classes, the first called "Radish" and the second called "RadishCont".
All the code is written in C++ and need to be used in python.
Radish have been exposed to python using SWIG; RadishCont, instead, have been exposed using boost::python.
I need to add a method into the class RadishCont that has this syntax... | [
"I'm pretty sure that you are better off rewriting your SWIG interface to include the new function. SWIG uses a internal registration system for classes/functions which is not compatible with boost::pythons system (or at least not out of the box).\n",
"At the end, I have done it.\nI have created a class instance ... | [
2,
1,
0
] | [] | [] | [
"boost_python",
"c++",
"python",
"swig"
] | stackoverflow_0007915965_boost_python_c++_python_swig.txt |
Q:
Is there a Python library that can generate charts within Excel?
I know python can manipulate Excel data but I don't know whether it can generate charts in it.
Does such a library exist?
A:
Excel is an OLE Automation server (which is built on COM), which means it has a discoverable interface that makes it possib... | Is there a Python library that can generate charts within Excel? | I know python can manipulate Excel data but I don't know whether it can generate charts in it.
Does such a library exist?
| [
"Excel is an OLE Automation server (which is built on COM), which means it has a discoverable interface that makes it possible to automate it from any tool that understands COM. Providing you're on Windows, Python is one of many such tools and you already have (or can easily obtain) the library you need: it's Pytho... | [
2
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0007977221_excel_python.txt |
Q:
How do I use Neo4j-embedded for Python (threads) in Flask microframework?
I'm following the Flask Tutorial (Flaskr) in order to experiment with using Neo4j-embedded for Python. This is in a virtualenv. Here is my 'main' app code:
import os
import jpype
from neo4j import GraphDatabase
from flask import Flask, reque... | How do I use Neo4j-embedded for Python (threads) in Flask microframework? | I'm following the Flask Tutorial (Flaskr) in order to experiment with using Neo4j-embedded for Python. This is in a virtualenv. Here is my 'main' app code:
import os
import jpype
from neo4j import GraphDatabase
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
app = Flask(_... | [
"One issue with this pattern is that you run the risk of starting multiple databases pointed at the same location, which will lead to problems. What you would want is a single instance of the database that follows the full lifecycle of your application.\nWhy it's not finding the lucene provider is a harder question... | [
6,
3
] | [] | [] | [
"flask",
"neo4j",
"python"
] | stackoverflow_0007999532_flask_neo4j_python.txt |
Q:
Python and a JSON Array
I am having problems with Python (Django) Framework. I at first attempted to send a Javascript Array straight to Django except it pulled only the last value. So I use now JSON.stringify which sends my JSON to Python.
At Python it looks like this
QueryDict: {u'[{"key:":"interface.dns","val... | Python and a JSON Array | I am having problems with Python (Django) Framework. I at first attempted to send a Javascript Array straight to Django except it pulled only the last value. So I use now JSON.stringify which sends my JSON to Python.
At Python it looks like this
QueryDict: {u'[{"key:":"interface.dns","value:":192.168.0.1"}]':[u'']}
... | [
"QueryDict objects implement the file interface. So you could decode the JSON simply with the standard JSON library:\nimport json\n...\nparsed_json = json.load(request.POST) # Or GET, depends on what you are using\n\n",
"You can use Djangos json deserializer:\ndata = request.POST.keys()[0]\nfor obj in serializers... | [
1,
0
] | [] | [] | [
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0008007375_django_javascript_jquery_python.txt |
Q:
Setting up emacs with autocomplete, python-mode, and rope
I have all of the above installed. Rope seems to work just fine but I get the error below when I try to run auto-complete:
Symbol's function definition is void: rope-completions
I can't figure this out for the life of me. Any suggestions where to look for ... | Setting up emacs with autocomplete, python-mode, and rope | I have all of the above installed. Rope seems to work just fine but I get the error below when I try to run auto-complete:
Symbol's function definition is void: rope-completions
I can't figure this out for the life of me. Any suggestions where to look for this error would be great??
| [
"According to this blog, you need the latest development version of Rope and Ropemacs for emacs to have rope-completions defined.\n"
] | [
2
] | [] | [] | [
"emacs",
"python",
"python_mode",
"rope"
] | stackoverflow_0008006032_emacs_python_python_mode_rope.txt |
Q:
Django ImportError looks like a loop
In my django project I have the following:
apps1/models.py: Post (model)
apps2/models.py: Blogs (model)
apps2/functions.py: get_blogs (method)
The apps1/models.py file imports the Blogs model from apps2/models.py.
The apps2/models.py file imports the get_blogs method from apps2... | Django ImportError looks like a loop | In my django project I have the following:
apps1/models.py: Post (model)
apps2/models.py: Blogs (model)
apps2/functions.py: get_blogs (method)
The apps1/models.py file imports the Blogs model from apps2/models.py.
The apps2/models.py file imports the get_blogs method from apps2/functions.py.
The apps2/functions.py file... | [
"If the only reason you import Blogs in apps1.models is that you have a relationship field in Post, how about using a lazy relationship instead? As far as I understand, those were designed specifically to deal with import loops like the one you're experiencing.\nIt is quite easy, instead of\nfrom apps2.models impor... | [
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008006872_django_python.txt |
Q:
How can I get my RegEx to capture text on both sides of a colon?
I am trying to parse some input text from a file, which are originally grabbed from the Twitter API. The file is straight text and I am not actually grabbing the JSON in this case. This is a snippet of the input text:
.....HootSuite</a>", "text": "Fo... | How can I get my RegEx to capture text on both sides of a colon? | I am trying to parse some input text from a file, which are originally grabbed from the Twitter API. The file is straight text and I am not actually grabbing the JSON in this case. This is a snippet of the input text:
.....HootSuite</a>", "text": "For independent news reports on the crisis in #Japan,
see @DemocracyNow... | [
"If you're using the Twitter API, I imagine it's returning JSON back to you. JSON supports arbitrary nesting, and a regular expression will never be able to parse it correctly in every scenario. You would be better served using a JSON parser. Since YAML is a superset of JSON, you could use a YAML parser too. I woul... | [
1,
0,
0
] | [] | [] | [
"findall",
"parsing",
"python",
"regex"
] | stackoverflow_0007990001_findall_parsing_python_regex.txt |
Q:
Redraw events lost?
I've got a pygtk app which uses gtk print_run_page_setup_dialog. For some reason, some widgets (siblings to button that invoked the dialog) are no more redrawn after closing this dialog. Forcibly calling queue_draw on them works fine.
I'd like to identify where are the events going, and reconne... | Redraw events lost? | I've got a pygtk app which uses gtk print_run_page_setup_dialog. For some reason, some widgets (siblings to button that invoked the dialog) are no more redrawn after closing this dialog. Forcibly calling queue_draw on them works fine.
I'd like to identify where are the events going, and reconnect them to proper locatio... | [
"It sounds incredibly unlikely that the dialog should somehow mess with event handler connections for unrelated widgets.\nMake sure the dialog is not stuck in a nested main loop (the call you mention has run in its name, implying a call to gtk_main() is taking place to make the dialog modal).\n"
] | [
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0008008220_gtk_pygtk_python.txt |
Q:
Django + JQuery Ajax post
I have read all on the theme but I can't understand what's wrong.
$(document).ready(function() {
$.post("tweet.py", {
lat : searchResult._point.__lat,
lng : searchResult._point.__lng,
text : searchResult.text
}, function(data) {
alert(data);
... | Django + JQuery Ajax post | I have read all on the theme but I can't understand what's wrong.
$(document).ready(function() {
$.post("tweet.py", {
lat : searchResult._point.__lat,
lng : searchResult._point.__lng,
text : searchResult.text
}, function(data) {
alert(data);
});
});
The handler's... | [
"Please add in your urls.py an url like \n(r'^ajaxrequest$', 'app.views.iEventAjax')\n\nand then change\n$(document).ready(function() {\n $.post(\"/ajaxrequest\", {\n lat : searchResult._point.__lat,\n lng : searchResult._point.__lng,\n text : searchResult.text\n }, function(data) {\n ... | [
1
] | [] | [] | [
"ajax",
"django",
"jquery",
"post",
"python"
] | stackoverflow_0008008127_ajax_django_jquery_post_python.txt |
Q:
Getting reusable tasks to work in a setup with one celery server and 3k+ django sites, each with its own database
Here's the problem: I have one celery server and 3k+ django sites, each with its own database. New sites (and databases) can be added dynamically.
I'm writing celery tasks which need to be run for each... | Getting reusable tasks to work in a setup with one celery server and 3k+ django sites, each with its own database | Here's the problem: I have one celery server and 3k+ django sites, each with its own database. New sites (and databases) can be added dynamically.
I'm writing celery tasks which need to be run for each site, through the common celery server. The code is in an app which is meant to be reusable, so it shouldn't be writte... | [
"This is hard to accomplish because of an inherent limitation in Django: The settings are global. So unless all the apps shared the same settings, this is going to be a problem.\nYou could try spawning new worker processes for every task and create the django environment each time. Don't use django-celery, but us... | [
0
] | [] | [] | [
"celery",
"django",
"python"
] | stackoverflow_0008003497_celery_django_python.txt |
Q:
Bubble sort error
I am trying to write and optimized bubble sort, but my code does not actually sort right through the list. Any suggestions as to why it is stopping early?
#!/usr/bin/env python
from random import *
import time
def bubble(lst):
counter = 0
n = len(lst)
while n > 0:
temp = 0
... | Bubble sort error | I am trying to write and optimized bubble sort, but my code does not actually sort right through the list. Any suggestions as to why it is stopping early?
#!/usr/bin/env python
from random import *
import time
def bubble(lst):
counter = 0
n = len(lst)
while n > 0:
temp = 0
for i in range(1... | [
"This should fix it:\ndef bubble(lst):\n counter = 0\n n = len(lst)\n while n > 0:\n temp = 0\n for i in range(0,n-1): # <- first element is at position 0\n if lst[i] > lst[i+1]:\n lst[i],lst[i+1] = lst[i+1],lst[i] #swap\n ... | [
1
] | [] | [] | [
"bubble_sort",
"python"
] | stackoverflow_0008001111_bubble_sort_python.txt |
Q:
How to set dates in x axis with non-uniform interval?
I would like to draw a time-plot using the matplotlib.dates module. From the tutorial, I know how to set regular interval date like the following:
ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_major_formatter(DateFormatter("%Y-%m"))
ax.xaxis.set_minor_.... | How to set dates in x axis with non-uniform interval? | I would like to draw a time-plot using the matplotlib.dates module. From the tutorial, I know how to set regular interval date like the following:
ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_major_formatter(DateFormatter("%Y-%m"))
ax.xaxis.set_minor_...
However, in my data there are some months missing. My x... | [
"If I understand correctly you may need to use\nmatplotlib.ticker.FixedLocator\n\nExample which puts labels at data points 1, 10 and the last one:\nimport pylab as plt\nfrom matplotlib.ticker import FixedLocator\nfrom matplotlib.dates import DateFormatter\nimport numpy as np\nfrom datetime import datetime\n\n# date... | [
2,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007986410_matplotlib_python.txt |
Q:
How to get duration of steaming data with GStreamer
I'm writing a program for converting media file to mp3 file with GStreamer. It works, but I would like to know the duration of audio stream, too. Following is the simplified code.
import logging
import pygst
pygst.require('0.10')
import gst
# this is very impor... | How to get duration of steaming data with GStreamer | I'm writing a program for converting media file to mp3 file with GStreamer. It works, but I would like to know the duration of audio stream, too. Following is the simplified code.
import logging
import pygst
pygst.require('0.10')
import gst
# this is very important, without this, callbacks from gstreamer thread
# wil... | [
"Unfortunately with appsrc it is not possible to get the exact duration of the stream, although with some formats that have fixed bitrate it is possible to estimate it based on file length, but other formats that use variable bitrates report an unknown length.\nBecause appsrc works on the incoming buffers (either p... | [
1
] | [] | [] | [
"audio",
"gstreamer",
"python"
] | stackoverflow_0008005765_audio_gstreamer_python.txt |
Q:
Multiple locale file lookup in Django
In my Django app i have the usual django.po locale file under each of the languages. However, I'd like to create a custom locale file called custom.po. Is there any way I could Django to first check for a translation string in the custom.po file and if it doesn't exist, check ... | Multiple locale file lookup in Django | In my Django app i have the usual django.po locale file under each of the languages. However, I'd like to create a custom locale file called custom.po. Is there any way I could Django to first check for a translation string in the custom.po file and if it doesn't exist, check the django.po file
Thanks.
| [
"Check the LOCALE_PATHS setting. This tuple is order-specific, so if you put the path to your custom.po first, you will achieve the effect you're after.\nEdit: Additional link for detailed information about How Django discovers translations.\n"
] | [
6
] | [] | [] | [
"django",
"localization",
"python"
] | stackoverflow_0008008115_django_localization_python.txt |
Q:
Python open a JAR shortcut
I have a JAR file saved on my desktop, is there a way that I ca get python to pen this up, as if I was just clicking on the link from my desk top, I am very new to python and know this is a dumb question, but would help me out alot.
A:
Why do you want to execute it via Python?
In my Wi... | Python open a JAR shortcut | I have a JAR file saved on my desktop, is there a way that I ca get python to pen this up, as if I was just clicking on the link from my desk top, I am very new to python and know this is a dumb question, but would help me out alot.
| [
"Why do you want to execute it via Python?\nIn my Windows environment such .jar file is executed by Java:\nC:\\jre7\\bin\\javaw.exe -jar \"%1\" %*\n\nOf course your OS should be able to change such association to open .jar with other program. On my Windows I can use local menu to open .jar file with Java, Eclipse, ... | [
2,
0
] | [] | [] | [
"jar",
"python"
] | stackoverflow_0008007274_jar_python.txt |
Q:
emacs python mode, python-send-buffer/string/region gives "Invalid Syntax" error
I have used python-mode's python-send-buffer(and similar ones) successfully in a different system in the past.
I don't get why I'm getting error here. And worse, googling doesn't help..
Below is the output when I try sending "from mat... | emacs python mode, python-send-buffer/string/region gives "Invalid Syntax" error | I have used python-mode's python-send-buffer(and similar ones) successfully in a different system in the past.
I don't get why I'm getting error here. And worse, googling doesn't help..
Below is the output when I try sending "from math import sqrt" to Python by C-c C-r
>>> emacs.eexecfile("/var/folders/qy/qyS-532mGoWXH... | [
"From the error message the problem is that you have inserted some whitespace in front of the line: the circumflex is pointing at a blank space. Indentation is significant in Python, you cannot start a script with an indented line.\n"
] | [
0
] | [] | [] | [
"emacs",
"macos",
"python"
] | stackoverflow_0008005519_emacs_macos_python.txt |
Q:
Django forms: reasons to use them?
Are there any real reason to use builtin forms in django?
One of them as I understand is validation. Ok. And maybe some convinience (but not for me).
Anything else?
Is there any acceleration in site work with forms?
A:
From Django documentation -
While it is possible to proc... | Django forms: reasons to use them? | Are there any real reason to use builtin forms in django?
One of them as I understand is validation. Ok. And maybe some convinience (but not for me).
Anything else?
Is there any acceleration in site work with forms?
| [
"From Django documentation - \n\nWhile it is possible to process form submissions just using Django’s\n HttpRequest class, using the form library takes care of a number of\n common form-related tasks. Using it, you can:\n\nDisplay an HTML form with automatically generated form widgets. \nCheck submitted data agai... | [
5,
3,
2
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0008005948_django_django_forms_python.txt |
Q:
shutil.rmtree(...) does not work in my script
I try to delete a created directory in my destructor:
shutil.rmtree("C:\\projects\\project_alpha\\tmp")
It does not work with my python script but when I execute this command via python console it works and the tmp-directory will deleted.
Where is the difference?
A:
... | shutil.rmtree(...) does not work in my script | I try to delete a created directory in my destructor:
shutil.rmtree("C:\\projects\\project_alpha\\tmp")
It does not work with my python script but when I execute this command via python console it works and the tmp-directory will deleted.
Where is the difference?
| [
"I assume by \"destructor\" you mean the __del__ method.\nFrom the docs on del\n\nIt is not guaranteed that del() methods are called for objects that still exist when the interpreter exits.\n\nWhat you might want to do is register an atexit handler.\nFor example at module level:\nimport atexit\n\ndef cleanup_direct... | [
4
] | [] | [] | [
"python",
"shutil"
] | stackoverflow_0008009808_python_shutil.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.