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:
Installing a module/script in Python on OSX
I am running Python 2.6.2 in Mac OSX 10.5.8.
I am trying to generate scientific graphs for a publication and am experimenting with python/matplotlib to do that. Varun Hiremath created a module called plot_settings.py (link text and I am trying to figure out how to insta... | Installing a module/script in Python on OSX | I am running Python 2.6.2 in Mac OSX 10.5.8.
I am trying to generate scientific graphs for a publication and am experimenting with python/matplotlib to do that. Varun Hiremath created a module called plot_settings.py (link text and I am trying to figure out how to install the module so that I can import it. I'm not s... | [
"Put that file in the same folder as your script and import it: import plot_settings.\n"
] | [
1
] | [] | [] | [
"installation",
"macos",
"module",
"python"
] | stackoverflow_0003886324_installation_macos_module_python.txt |
Q:
python: breaking a string into substrings using a for loop
i have a string like this:
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
i h... | python: breaking a string into substrings using a for loop | i have a string like this:
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
i have this loop:
for n in range (1,int(len(row)/55)+1):
print row[... | [
"import textwrap\n\nrow='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'\n\nprint(textwrap.fill(row,width=55))\n# saint george 1739 1799 violin ... | [
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003886465_python.txt |
Q:
PyQT4 and Ctrl C
I have a programs that runs several threads (on a while loop until
Ctrl C is pressed). The app also has a GUI that I developed in PyQt. However, I am facing the following problem:
If I press Ctrl C on the console, and then close the GUI, the program exits fine. However, if I close the GUI first... | PyQT4 and Ctrl C | I have a programs that runs several threads (on a while loop until
Ctrl C is pressed). The app also has a GUI that I developed in PyQt. However, I am facing the following problem:
If I press Ctrl C on the console, and then close the GUI, the program exits fine. However, if I close the GUI first, the other threads wo... | [
"In Qt you would overload the OnClose method for the widget/frame or hook the lastwindowsdclosed signal to do whatever you need to shut down the app - don't know if it's diiferent from python\n"
] | [
0
] | [] | [] | [
"copy_paste",
"multithreading",
"pyqt",
"python"
] | stackoverflow_0003886500_copy_paste_multithreading_pyqt_python.txt |
Q:
python: turning textwrap into a list
i have a variable:
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
i am doing this:
textwrap.fill(ro... | python: turning textwrap into a list | i have a variable:
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
i am doing this:
textwrap.fill(row,55)
i would like some list line to have... | [
"use textwrap.wrap instead of textwrap.fill\n",
"textwrap.wrap returns a list. Why not use that?\ntextwrap.fill(text, ...) is the equivalent of \"\\n\".join(wrap(text, ...)). As explained in the docs.\n",
"You can just split it using e.g.\ntextwrap.fill(row, 55).split('\\n')\n\nor use textwrap.wrap instead.\n"... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003886540_python.txt |
Q:
how to prevent QTableModel from updating table depending on some condition
i have a mysql tables that uses lock-write mechanism. the lock might go for too long (we're talking about 1-2 minutes here).
i had to make a check if the table is in use or not before the update is done (using beforeUpdate signal)
but aft... | how to prevent QTableModel from updating table depending on some condition | i have a mysql tables that uses lock-write mechanism. the lock might go for too long (we're talking about 1-2 minutes here).
i had to make a check if the table is in use or not before the update is done (using beforeUpdate signal)
but after checking and returning that my table is in use , system hang until the other ... | [
"Python threading: http://docs.python.org/library/thread.html You can create threads that wait until the table is finished and it should be negligible in system resources, also your end user wont have to wait for the system to respond to continue with a different task.\n"
] | [
0
] | [] | [] | [
"mysql",
"pyqt",
"python",
"qt"
] | stackoverflow_0003854049_mysql_pyqt_python_qt.txt |
Q:
Is appengine Python datastore query much (>3x) slower than Java?
I've been investigating the appengine to see if I can use it for a
project and while trying to choose between Python and Java, I ran into
a surprising difference in datastore query performance: medium to
large datastore queries are more than 3 times ... | Is appengine Python datastore query much (>3x) slower than Java? | I've been investigating the appengine to see if I can use it for a
project and while trying to choose between Python and Java, I ran into
a surprising difference in datastore query performance: medium to
large datastore queries are more than 3 times slower in Python than in
Java.
My question is: is this performance dif... | [
"This would be an expected difference between Python and Java. Most likely you aren't seeing differences in the amount of time to make the query, but the amount of time it takes to parse the result and fill the receiving data structure.\nYou can test this by comparing the time it takes to query a single record. Rem... | [
5
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"java",
"python"
] | stackoverflow_0003886341_google_app_engine_google_cloud_datastore_java_python.txt |
Q:
Basic Widget Interaction with PyQt
Please can someone tell me what im doing wrong here with respect to calling pwTxt.text.
#!/usr/bin/python
import sys
from PyQt4 import QtCore, QtGui
from mainwindow import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.... | Basic Widget Interaction with PyQt | Please can someone tell me what im doing wrong here with respect to calling pwTxt.text.
#!/usr/bin/python
import sys
from PyQt4 import QtCore, QtGui
from mainwindow import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui ... | [
"Try:\nprint self.ui.pwTxt.text()\n\n"
] | [
2
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0003886745_pyqt_python.txt |
Q:
Specify Framework Version on OSX
I am compiling a program that embeds Python, in particular Python v3.1. On my system I have several versions of the Python framework: 3.1, 2.5, 2.6. When I pass "-framework Python" to g++ when compiling, g++ seems to pull in version 2.6 (lives at "/System/Library/Frameworks/") inst... | Specify Framework Version on OSX | I am compiling a program that embeds Python, in particular Python v3.1. On my system I have several versions of the Python framework: 3.1, 2.5, 2.6. When I pass "-framework Python" to g++ when compiling, g++ seems to pull in version 2.6 (lives at "/System/Library/Frameworks/") instead of version 3.1 (lives at "/Library... | [
"Try first changing the Current symlink in the Python framework in /Library/Frameworks:\n$ cd /Library/Frameworks/Python.framework/Versions\n$ ls -l\ntotal 4\ndrwxrwxr-x 8 root admin 340 Aug 31 02:10 2.6/\ndrwxrwxr-x 8 root admin 340 Oct 6 21:56 2.7/\ndrwxrwxr-x 7 root admin 306 Oct 6 14:00 3.1/\nlrwxr-x... | [
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0003884470_macos_python.txt |
Q:
Tuple to string
I have a tuple.
tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
And I want to convert it to a string..
print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"
what is a good way to do this?
Thanks!
A:
tst2 = str(tst)
E.g.:
>>> tst = ([['name', u'bob-21'], ['name', u'john-28'... | Tuple to string | I have a tuple.
tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
And I want to convert it to a string..
print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"
what is a good way to do this?
Thanks!
| [
"tst2 = str(tst)\n\nE.g.:\n>>> tst = ([['name', u'bob-21'], ['name', u'john-28']], True)\n>>> tst2 = str(tst)\n>>> print tst2\n([['name', u'bob-21'], ['name', u'john-28']], True)\n>>> repr(tst2)\n'\"([[\\'name\\', u\\'bob-21\\'], [\\'name\\', u\\'john-28\\']], True)\"'\n\n",
"While I like Adam's suggestion for st... | [
17,
4
] | [] | [] | [
"python"
] | stackoverflow_0003886669_python.txt |
Q:
Why does initializing a variable via a python default variable keep state across object instantiation?
I hit an interesting python bug today in which instantiating a class repeatedly appears to be holding state. In later instantiation calls the variable is already defined.
I boiled down the issue into the followi... | Why does initializing a variable via a python default variable keep state across object instantiation? | I hit an interesting python bug today in which instantiating a class repeatedly appears to be holding state. In later instantiation calls the variable is already defined.
I boiled down the issue into the following class/shell interaction. I realize that this is not the best way to initialize a class variable, but it s... | [
"It is a feature that pretty much all Python users run into once or twice. The main usage is for caches and the like to avoid repetitive lengthy calculations (simple memoizing, really), although I am sure people have found other uses for it.\nThe reason for this is that the def statement only gets executed once, wh... | [
15,
5,
3
] | [] | [] | [
"arguments",
"python"
] | stackoverflow_0003887079_arguments_python.txt |
Q:
Letting users to choose what type of content they want to input
This is my first post here, and I'd like to describe what I want to do as specific as possible.
I'd like to make a model that is 'selectable.'
for example,
class SimpleModel(models.Model):
property = models.CharField(max_length=255)
value = G... | Letting users to choose what type of content they want to input | This is my first post here, and I'd like to describe what I want to do as specific as possible.
I'd like to make a model that is 'selectable.'
for example,
class SimpleModel(models.Model):
property = models.CharField(max_length=255)
value = GeneralField()
GeneralField can be "CharField", "URLField", "TextFiel... | [
"How about creating a separate model for each type of field you want to support, and then another model consisting of a list of (table_name, entry_id) pairs, which could be customized to use any combination of fields?\n"
] | [
0
] | [] | [] | [
"django_models",
"field",
"input",
"python"
] | stackoverflow_0003887017_django_models_field_input_python.txt |
Q:
python: append only specific elements from a list
i have a list of a list:
b=[[1,2,3],[4,5,6],[7,8,9]]
i have a list:
row = [1,2,3]
how do i append to b only row[0] and '3847' and row[2] such that b will equal:
b=[[1,2,3],[4,5,6],[7,8,9],[1,3847,3]]
A:
You're going to have to be more specific.
This will accomp... | python: append only specific elements from a list | i have a list of a list:
b=[[1,2,3],[4,5,6],[7,8,9]]
i have a list:
row = [1,2,3]
how do i append to b only row[0] and '3847' and row[2] such that b will equal:
b=[[1,2,3],[4,5,6],[7,8,9],[1,3847,3]]
| [
"You're going to have to be more specific.\nThis will accomplish what you want:\nb.append([row[0], 3847, row[2]])\n\nBut isn't really a general solution.\n",
"b.append([ x if x != 2 else 3847 for x in row])\n\n",
"b + [[row[0],3847,row[2]]]\n\n",
"b + [row[0],3847,row[2]] would give you:\n>>> b + [row[0],3847... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003887336_python.txt |
Q:
Automate paster create -t plone3_buildout
I want to automate the process of plone3_buildout.
Explanation:
The default(the one I use) way of building a plone site is using paster, like so:
paster create -t plone3_buildout
This asks me a few questions and then create a default buildout for the site.
What I want:
I ... | Automate paster create -t plone3_buildout | I want to automate the process of plone3_buildout.
Explanation:
The default(the one I use) way of building a plone site is using paster, like so:
paster create -t plone3_buildout
This asks me a few questions and then create a default buildout for the site.
What I want:
I want to automate this process using buildout. M... | [
"The paster create command can accept a --config option. This allows you to generate or use a file with answers to the questions.\n$ paster create -t plone3_buildout --config=saved.cfg my-buildout\n...\nanswer questions\n...\n\nNow there will be a buildout.config file in the current directory.\n$ cat saved.cfg\n[pa... | [
2,
1
] | [] | [] | [
"automation",
"buildout",
"plone",
"python"
] | stackoverflow_0002894455_automation_buildout_plone_python.txt |
Q:
Python Desktop Integration - Drag and drop
I have a pygame window that I want to know when a file has been dragged and dropped onto it. I only need to be able to fetch the name of the file. How can this be accomplished?
A:
Here's a forum thread that might be what you're looking for.
And another forum.
And a li... | Python Desktop Integration - Drag and drop | I have a pygame window that I want to know when a file has been dragged and dropped onto it. I only need to be able to fetch the name of the file. How can this be accomplished?
| [
"Here's a forum thread that might be what you're looking for. \nAnd another forum.\nAnd a link to the msdn page. You'll probably want the pythoncom library.\n",
"one option for a similar effect is is to use pygame's scrap module so you can copy-paste into the window, your program would just need to look for ctr... | [
3,
0
] | [] | [] | [
"desktop_integration",
"drag_and_drop",
"pygame",
"python"
] | stackoverflow_0000682692_desktop_integration_drag_and_drop_pygame_python.txt |
Q:
Modelling Data with Google App Engine Datastore
I am currently building a web application on Google App Engine in Python to harvest horse racing data of the form. The basic data structure is Course has many Meetings has many Races has many Horses has one Jockey and had one Trainer. So far I have got the following ... | Modelling Data with Google App Engine Datastore | I am currently building a web application on Google App Engine in Python to harvest horse racing data of the form. The basic data structure is Course has many Meetings has many Races has many Horses has one Jockey and had one Trainer. So far I have got the following models (reduced number of fields for sake of brevity)... | [
"You are on the right track with using HorseResult, TrainerResult, and JockeyResult models. Do not forget, the datastore does not have grouping or aggregate functions, so you might want to pre-compute any aggregates or statistics of interest when you are loading the data.\nPerhaps you will also want to have statis... | [
0
] | [] | [] | [
"betfair",
"google_app_engine",
"python"
] | stackoverflow_0003885012_betfair_google_app_engine_python.txt |
Q:
Sending data received in one Twisted factory to second factory
I am trying to write a simple program using Twisted framework and I am struggling with resolving (or even with imaging how to write it) issue I couldnt find any relevant documentation for:
The main reactor uses two factories, one custom, listening for ... | Sending data received in one Twisted factory to second factory | I am trying to write a simple program using Twisted framework and I am struggling with resolving (or even with imaging how to write it) issue I couldnt find any relevant documentation for:
The main reactor uses two factories, one custom, listening for TCP connections on given port (say, 8000) and second one, to log int... | [
"Factories are just objects. To pass data from one to another, you define and call methods and pass the data as parameter, or set attributes. I think this faq question will help you:\n\nHow do I make input on one connection\n result in output on another?\nThis seems like it's a Twisted\n question, but actually it... | [
6,
0,
0
] | [] | [] | [
"factory",
"irc",
"python",
"twisted",
"xmpp"
] | stackoverflow_0003737885_factory_irc_python_twisted_xmpp.txt |
Q:
How to display an image next to a menu item?
I am trying to get an image to appear next to a menu item but it isn't working.
In order to make this as simple as possible, I have created a very simple example below that highlights the problem:
import pygtk
pygtk.require('2.0')
import gtk
class MenuExample:
def... | How to display an image next to a menu item? | I am trying to get an image to appear next to a menu item but it isn't working.
In order to make this as simple as possible, I have created a very simple example below that highlights the problem:
import pygtk
pygtk.require('2.0')
import gtk
class MenuExample:
def __init__(self):
window = gtk.Window()
... | [
"Hmmm... it turns out the answer was that my desktop theme had disabled icons for menus. (Who knows why.)\nAfter enabling the option, the icons now show up.\n"
] | [
2
] | [] | [] | [
"image",
"menuitem",
"pygtk",
"python"
] | stackoverflow_0003887944_image_menuitem_pygtk_python.txt |
Q:
Changing the active database in django
i'm writing a testing application that i'm using to test the rest of my code base. What i'd like to be able to do for it is when i test using this manage.py command, automatically change to be logging to a different database. is there a good way to do this?
A:
Django automa... | Changing the active database in django | i'm writing a testing application that i'm using to test the rest of my code base. What i'd like to be able to do for it is when i test using this manage.py command, automatically change to be logging to a different database. is there a good way to do this?
| [
"Django automatically creates and drops a test database for you. Unless otherwise specified (we'll see how to in a second) this will be test_ + <the name of the database in the settings file>. So if your settings uses database foo, the tests will be executed against test_foo. No configuration changes are needed for... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003886298_django_python.txt |
Q:
Can You Use a Single Regular Expression to Parse Function Parameters?
Problem
There is a program file that contains the following code snippet at some point in the file.
...
food($apples$ , $oranges$ , $pears$ , $tomato$){
...
}
...
This function may contain any number of parameters but they must be strings s... | Can You Use a Single Regular Expression to Parse Function Parameters? | Problem
There is a program file that contains the following code snippet at some point in the file.
...
food($apples$ , $oranges$ , $pears$ , $tomato$){
...
}
...
This function may contain any number of parameters but they must be strings separated by commas. All the parameter strings are lowercase words.
I want t... | [
"To answer your question \"Can it be done in a single regex?\": Yes, but not in Python.\nIf you want to match and capture (individually) an unknown number of matches as in your example, using only a single regular expression, then you need a regex engine that supports captures (as opposed to capturing groups). Only... | [
3,
2,
2,
0,
0
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0003885653_parsing_python_regex.txt |
Q:
Need help processing upload form with Google App Engine Blobstore
I'm trying to learn the blobstore API... and I'm able to successfully upload files and get them back, but I'm not having any luck trying to combine an upload form with a regular webform to be able to associated extra info with the file, such as a ni... | Need help processing upload form with Google App Engine Blobstore | I'm trying to learn the blobstore API... and I'm able to successfully upload files and get them back, but I'm not having any luck trying to combine an upload form with a regular webform to be able to associated extra info with the file, such as a nickname for the file.
Below is the code for a simple app I've been playi... | [
"The problem is that your posted form data is lost when you redirect the request to \"/save/%s\", which is normal.\nInstead of redirecting, you should put your code inside UploadHandler, like this (untested code) :\nclass UploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n try:\n... | [
4
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0003887535_blobstore_google_app_engine_python.txt |
Q:
How to return and use an array of strings from a jQuery ajax call?
I'm using Google App Engine (Python) along with jQuery for Ajax calls to the server. I have a page where I want to load up a list of strings in Javascript from an Ajax call to the server.
The server method I want to invoke:
class BrowseObjects(w... | How to return and use an array of strings from a jQuery ajax call? | I'm using Google App Engine (Python) along with jQuery for Ajax calls to the server. I have a page where I want to load up a list of strings in Javascript from an Ajax call to the server.
The server method I want to invoke:
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_id... | [
"The SDK of Google AppEngine provided by django the lib \"simplejson\".\nfrom django.utils import simplejson\nSo your handler maybe it simply:\nfrom django.utils import simplejson\nclass BrowseObjects(webapp.RequestHandler):\n def get(self):\n ids_to_return = get_ids_to_return()\n response_json = si... | [
6,
3
] | [] | [] | [
"ajax",
"google_app_engine",
"javascript",
"jquery",
"python"
] | stackoverflow_0003887266_ajax_google_app_engine_javascript_jquery_python.txt |
Q:
pythonic way to optimize the logic to filter/extract data from list
I have a list like below:
['1 (UID 3234 FLAGS (seen \\Seen))', '2 (UID 3235 FLAGS (\\Seen))',
'3 (UID 3236 FLAGS (\\Deleted))', '4 (UID 3237 FLAGS (-FLAGS \\Seen +FLAGS))',
'5 (UID 3241 FLAGS (-FLAGS \\Seen +FLAGS))', '6 (UID 3242 FLAGS (\\Seen)... | pythonic way to optimize the logic to filter/extract data from list | I have a list like below:
['1 (UID 3234 FLAGS (seen \\Seen))', '2 (UID 3235 FLAGS (\\Seen))',
'3 (UID 3236 FLAGS (\\Deleted))', '4 (UID 3237 FLAGS (-FLAGS \\Seen +FLAGS))',
'5 (UID 3241 FLAGS (-FLAGS \\Seen +FLAGS))', '6 (UID 3242 FLAGS (\\Seen))',
'7 (UID 3243 FLAGS (\\Seen))', '8 (UID 3244 FLAGS (\\Seen))',
'9 ... | [
"The best thing to do would be to turn your data into a dict mapping UID to FLAGS, then searching it will be easy. So the data will look something like this:\n{'3254': '', '3304': '', '3236': '\\\\Deleted', '3237': '-FLAGS \\\\Seen +FLAGS', '3234': 'seen \\\\Seen', '3235': '\\\\Seen', '3430': '\\\\Seen', '3431': '... | [
3,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"filtering",
"python"
] | stackoverflow_0003889038_filtering_python.txt |
Q:
How do I get access to the request object when validating a django.contrib.comments form?
I would like to run a check on the IP-adress when users post with django comments.
I can easily override and customize the form used by django.comments, but I need access to the request object to add an IP-test to its clean()... | How do I get access to the request object when validating a django.contrib.comments form? | I would like to run a check on the IP-adress when users post with django comments.
I can easily override and customize the form used by django.comments, but I need access to the request object to add an IP-test to its clean(). Is it possible to get access to this in a clean way?
An alternative could be to check the IP ... | [
"The comments framework provides a comment_will_be_posted signal:\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/comments/signals/#comment-will-be-posted\nIf you register at this signal, your handler will be passed the (not yet saved) comment object and the request as arguments. If your handler returns False, th... | [
1,
0,
0
] | [] | [] | [
"comments",
"django",
"python"
] | stackoverflow_0003888322_comments_django_python.txt |
Q:
Using Python code coverage tool for understanding and pruning back source code of a large library
My project targets a low-cost and low-resource embedded device. I am dependent on a relatively large and sprawling Python code base, of which my use of its APIs is quite specific.
I am keen to prune the code of this ... | Using Python code coverage tool for understanding and pruning back source code of a large library | My project targets a low-cost and low-resource embedded device. I am dependent on a relatively large and sprawling Python code base, of which my use of its APIs is quite specific.
I am keen to prune the code of this library back to its bare minimum, by executing my test suite within a coverage tools like Ned Batchelde... | [
"What you want isn't \"test coverage\", it is the transitive closure of \"can call\" from the root of the computation. (In threaded applications, you have to include \"can fork\").\nYou want to designate some small set (perhaps only 1) of functions that make up the entry points of your application, and want to tra... | [
9,
2,
0
] | [] | [] | [
"code_analysis",
"code_coverage",
"python",
"reverse_engineering"
] | stackoverflow_0003883484_code_analysis_code_coverage_python_reverse_engineering.txt |
Q:
Why is tempfile using DOS 8.3 directory names on my XP box?
>>> import tempfile
>>> tempfile.mkstemp()
(3, 'c:\\docume~1\\k0811260\\locals~1\\temp\\tmpk6tpd3')
It works, but looks a bit strange. and the actual temporary file name is more than 8 letters.
Why doesn't it use long file names instead?
A:
mkstemp use... | Why is tempfile using DOS 8.3 directory names on my XP box? | >>> import tempfile
>>> tempfile.mkstemp()
(3, 'c:\\docume~1\\k0811260\\locals~1\\temp\\tmpk6tpd3')
It works, but looks a bit strange. and the actual temporary file name is more than 8 letters.
Why doesn't it use long file names instead?
| [
"mkstemp uses the environment variables TMPDIR, TEMP or TMP (the first one that is set) to determine where to put your temporary file. One of these is probably set to c:\\docume~1\\k0811260\\locals~1\\temp on your system. Issue\necho %%tmp%%\n\netc. in a command window (\"DOS box\") to find out for sure.\nWhich, in... | [
3
] | [] | [] | [
"python",
"temporary_files"
] | stackoverflow_0003890233_python_temporary_files.txt |
Q:
How to stream my webcam through my site?
Is it possible to stream my webcam form my local machine that's connected to the internet to show up on my website without using any media server or something similar?
A:
You could do it with some kind of java applet or flash/silverlight application, just look at sites li... | How to stream my webcam through my site? | Is it possible to stream my webcam form my local machine that's connected to the internet to show up on my website without using any media server or something similar?
| [
"You could do it with some kind of java applet or flash/silverlight application, just look at sites like \"chat roulette\"\n",
"If you are wanting for other people to see it, then no.\nWeb pages have two scopes: Client and Server. Something running on one Client (user) cannot be shown to other Clients (users) wit... | [
1,
0
] | [] | [] | [
"python",
"webcam"
] | stackoverflow_0003890271_python_webcam.txt |
Q:
Building tree structure from flat list derived from zope catalog call without recursion
I have all objects which get looked up to provide interpreter with both parents objects and object subobjects. I hope to do this without recursion for zope not appreciating this conventional recursion.
I set the view context as... | Building tree structure from flat list derived from zope catalog call without recursion | I have all objects which get looked up to provide interpreter with both parents objects and object subobjects. I hope to do this without recursion for zope not appreciating this conventional recursion.
I set the view context as root object for recursion to start attaching object on then iterate across this filtered lis... | [
"Maybe this little trick will be usefull for you as it was for me.\nYou can restrict your search results by PathIndex (getPhysicalPath) and then just sort it alphabetically:\nlst = context.Catalog.searchResults(path='/parentNodeId')\nlst.sort()\nprint lst\n\nYou will see something like this:\n# /parentNodeId/\n# /p... | [
1
] | [] | [] | [
"plone",
"python",
"recursion",
"zope"
] | stackoverflow_0003774874_plone_python_recursion_zope.txt |
Q:
add properties to users google app engine
What is the best way to save a user profile with Google App Engine (Python) ?
What I did to solve this problem is create another Model, with a UserProperty, but requesting the profile from the user I have to do something like this:
if user:
profile = Profile.all().filt... | add properties to users google app engine | What is the best way to save a user profile with Google App Engine (Python) ?
What I did to solve this problem is create another Model, with a UserProperty, but requesting the profile from the user I have to do something like this:
if user:
profile = Profile.all().filter('user =', user).fetch(1)
if profile:
... | [
"If you make the user_id of the user the key_name of the user's Profile entity, you can fetch it using Profile.get_by_key_name(), which will be faster than querying and then fetching.\nMemcaching including the user_id as part of the key will allow even faster access to the profile.\n",
"No, this is a pretty corre... | [
4,
1,
1
] | [] | [] | [
"google_app_engine",
"profiling",
"python"
] | stackoverflow_0002504748_google_app_engine_profiling_python.txt |
Q:
quick question: clear an attribute of a model in django
i think this is a pretty easy question for you.
I want to clear an attribute of a django-model.
If i have something like this:
class Book(models.Model):
name = models.TextField()
pages = models.IntegerField()
img = models.ImageField()
... | quick question: clear an attribute of a model in django | i think this is a pretty easy question for you.
I want to clear an attribute of a django-model.
If i have something like this:
class Book(models.Model):
name = models.TextField()
pages = models.IntegerField()
img = models.ImageField()
In an abstract function i want to clear an attribute, but at ... | [
"I don't think there is a clean way of doing it. However, assuming you've set a default value (which you don't have) you can do it like this:\nbook.img = book._meta.get_field('img').default\n\nDo note that your current model won't allow a None value. To allow those you have to set null=True and blank=True. For page... | [
1
] | [] | [] | [
"django",
"model",
"python"
] | stackoverflow_0003890525_django_model_python.txt |
Q:
Filter results for Django paginator in template
I'm filtering out results from my page_obj in a generic view to only show entries published in the same language as the languge currently set by django-cms (http://www.django-cms.org/en/documentation/2.0/i18n/).
This works fine, but adding in support for Django pagin... | Filter results for Django paginator in template | I'm filtering out results from my page_obj in a generic view to only show entries published in the same language as the languge currently set by django-cms (http://www.django-cms.org/en/documentation/2.0/i18n/).
This works fine, but adding in support for Django pagination (http://docs.djangoproject.com/en/1.2/topics/pa... | [
"The soultion, ultimately, was to rebuild the views. Extensive rebuilding required in this case.\nMoral of the sory: don't filter in templates!\n"
] | [
0
] | [] | [] | [
"django",
"django_generic_views",
"django_templates",
"paginator",
"python"
] | stackoverflow_0003512085_django_django_generic_views_django_templates_paginator_python.txt |
Q:
Question on Django: Displaying many to many fields
I seem to have a problem with Django when it comes Rendering ManyToManyField in a template. I can make it work partially, but I cannot make it work properly as I want it.
Firstly I have an invoice template which displays Invoice details from my data base
#invoice_... | Question on Django: Displaying many to many fields | I seem to have a problem with Django when it comes Rendering ManyToManyField in a template. I can make it work partially, but I cannot make it work properly as I want it.
Firstly I have an invoice template which displays Invoice details from my data base
#invoice_details.html
{% extends "base.html" %}
{% block content... | [
"The content of {{invoice.work_orders.all} is a list of Work_Order objects. \nIf you want to print them, you should iterate the list: \n{% for invoice in invoice.work_orders.all %}\n {{invoice}}<br />\n{% endfor %}\n\n"
] | [
5
] | [] | [] | [
"django",
"html",
"manytomanyfield",
"python"
] | stackoverflow_0003891321_django_html_manytomanyfield_python.txt |
Q:
how to link python static library with my c++ program
I am implementing a C++ program that uses python/C++ Extensions. As of now I am explicitly linking my program to python static library I compiled. I am wondering is there any way to link my program with system installed python(i mean the default python installa... | how to link python static library with my c++ program | I am implementing a C++ program that uses python/C++ Extensions. As of now I am explicitly linking my program to python static library I compiled. I am wondering is there any way to link my program with system installed python(i mean the default python installation that comes with linux)
| [
"Yes. There is a command line utility called python-config:\nUsage: /usr/bin/python-config [--prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--help]\n\nFor linkage purposes, you have to invoke it with --ldflags parameter. It will print a list of flags you have to pass to the linker (or g++) in order to l... | [
20
] | [] | [] | [
"python"
] | stackoverflow_0003891202_python.txt |
Q:
Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' "
I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'"
Here is the full stack trace:
Traceback (most recent call last):
File "D:\Projects\GoogleAppEngine\google_appengine\googl... | Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' " | I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'"
Here is the full stack trace:
Traceback (most recent call last):
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__
handler.post(*groups)
File "... | [
"In this line:\nif value is not None and not value.has_key():\n\nvalue is a unicode string. It looks like the code is expecting it to be a db.Model,\n(From what I can see, has_key is a method of db.Model, as well as a method of Python dictionaries, but this must be the db.Model one because it's being called with n... | [
6,
3,
2,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001314617_google_app_engine_python.txt |
Q:
Python: loop through a file for specific lines
I have the following lines in a file where I want to take the third column; In the file I don't have the numbers column:
Red; Blue; Green; White; Orange;
Green; White; Orange;
Blue; Green; White;
Red; Blue; Green; White;
Blue; Green; White; Orange;
Orange
Green; Whit... | Python: loop through a file for specific lines | I have the following lines in a file where I want to take the third column; In the file I don't have the numbers column:
Red; Blue; Green; White; Orange;
Green; White; Orange;
Blue; Green; White;
Red; Blue; Green; White;
Blue; Green; White; Orange;
Orange
Green; White; Orange;
White; Orange
Green;
I used this code li... | [
"what about something like this:\ncols = i.split(\";\")\nif (len(cols) >= 3):\n lines = cols[2]\nelse:\n #whatever you want here\n\n",
"The simple solution is to check the number of columns and ignore lines with less than three columns.\nthird_columns = []\nwith open(\"...\") as infile:\n for line in inf... | [
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003891299_python.txt |
Q:
Appengine - Upload to Google Spreadsheet datastore values
I´d like to know how to upload to a Google Spreadsheet, values stored in the database of my application.
Objective:
Connecting to Google Spreadsheet and automatically fill in a chart in the admin area with values that were passed by the upload.
I've been... | Appengine - Upload to Google Spreadsheet datastore values | I´d like to know how to upload to a Google Spreadsheet, values stored in the database of my application.
Objective:
Connecting to Google Spreadsheet and automatically fill in a chart in the admin area with values that were passed by the upload.
I've been giving a look in the docs and it seems to me that I have to us... | [
"The Bulk Loader has nothing to do with interacting with a Google Docs Spreadsheet. It is used for adding records to your application's datastore.\nTo manipulate a Google Spreadsheet, you'll need to use the Google Spreadsheet API, which you could easily find on your own using Google.\nNo one here is going to write ... | [
3
] | [] | [] | [
"bigtable",
"django",
"google_app_engine",
"google_sheets",
"python"
] | stackoverflow_0003888445_bigtable_django_google_app_engine_google_sheets_python.txt |
Q:
How is generated the python grammar and how the interpreter understand it
I wonder how is generated the grammar of the Python language and how it is understood by the interpreter.
In python, the file graminit.c seems to implement the grammar, but i don't clearly understand it.
More broadly, what are the different ... | How is generated the python grammar and how the interpreter understand it | I wonder how is generated the grammar of the Python language and how it is understood by the interpreter.
In python, the file graminit.c seems to implement the grammar, but i don't clearly understand it.
More broadly, what are the different ways to generate a grammar and are there differences between how the grammar is... | [
"Grammars are generally of the same form: Backus-Naur Form (BNF) is typical.\nLexer/parsers can take very different forms. \nThe lexer breaks up the input file into tokens. The parser uses the grammar to see if the stream of tokens is \"valid\" according to its rules.\nUsually the outcome is an abstract syntax tr... | [
8,
2
] | [] | [] | [
"grammar",
"python"
] | stackoverflow_0003890321_grammar_python.txt |
Q:
Twill - how do choose multiple selects with same name
I am using twill and python to write a web crawler. showforms() returns
Form name=customRatesForm (#1)
## ## __Name__________________ __Type___ __ID________ __Value__________________
10 originState hidden originState TN
11 destState ... | Twill - how do choose multiple selects with same name | I am using twill and python to write a web crawler. showforms() returns
Form name=customRatesForm (#1)
## ## __Name__________________ __Type___ __ID________ __Value__________________
10 originState hidden originState TN
11 destState hidden destState IL
12 originZip ... | [
"as far as i've found till now, there is no way to do this with twill. any solution is going to be a workaround outside of twill.\n"
] | [
1
] | [] | [] | [
"jquery",
"python",
"twill",
"web_crawler"
] | stackoverflow_0003755595_jquery_python_twill_web_crawler.txt |
Q:
Is there a way to debug a subprocess using pydev?
I'm using Eclipse / PyDev trying to find a way to debug code that uses subprocess.Popen to create a child process: I want to be able to debug the child process that is created. The problem is that I cannot find a way to debug accross process boundaries, and I'm gu... | Is there a way to debug a subprocess using pydev? | I'm using Eclipse / PyDev trying to find a way to debug code that uses subprocess.Popen to create a child process: I want to be able to debug the child process that is created. The problem is that I cannot find a way to debug accross process boundaries, and I'm guessing that it is actually not possible. Still, you ne... | [
"I does not seem PyDev can do it (neither can PyDbg and WinDbg), but it looks like gdb can: http://wiki.python.org/moin/DebuggingWithGdb.\n",
"I've found something of a workaround that might work for you.\nLike you, I first found the remote debugging option of manually inserting calls to pydevd.settrace() at desi... | [
4,
3
] | [] | [] | [
"debugging",
"eclipse",
"pydev",
"python",
"waf"
] | stackoverflow_0001624932_debugging_eclipse_pydev_python_waf.txt |
Q:
Python: how to make HTTP request internally/localhost
I want to send some parameters from a python script on my server to a php script on my server using HTTP. Suggestions?
A:
This is pretty easy using urllib:
import urllib
myurl = 'http://localhost/script.php?var1=foo&var2=bar'
# GET is the default action
res... | Python: how to make HTTP request internally/localhost | I want to send some parameters from a python script on my server to a php script on my server using HTTP. Suggestions?
| [
"This is pretty easy using urllib:\nimport urllib\n\nmyurl = 'http://localhost/script.php?var1=foo&var2=bar'\n\n# GET is the default action\nresponse = urllib.urlopen(myurl) \n\n# Output from the GET assuming response code was 200\ndata = response.read() \n\n"
] | [
2
] | [] | [] | [
"http",
"php",
"python"
] | stackoverflow_0003889283_http_php_python.txt |
Q:
subprocess replacement of popen2 with Python
I tried to run this code from the book 'Python Standard Library' of 'Fred Lunde'.
import popen2, string
fin, fout = popen2.popen2("sort")
fout.write("foo\n")
fout.write("bar\n")
fout.close()
print fin.readline(),
print fin.readline(),
fin.close()
It runs well with a... | subprocess replacement of popen2 with Python | I tried to run this code from the book 'Python Standard Library' of 'Fred Lunde'.
import popen2, string
fin, fout = popen2.popen2("sort")
fout.write("foo\n")
fout.write("bar\n")
fout.close()
print fin.readline(),
print fin.readline(),
fin.close()
It runs well with a warning of
~/python_standard_library_oreilly_lu... | [
"import subprocess\nproc=subprocess.Popen(['sort'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)\nproc.stdin.write('foo\\n')\nproc.stdin.write('bar\\n')\nout,err=proc.communicate()\nprint(out)\n\n",
"Within the multiprocessing module there is a method called 'Pool' which might be perfect for your needs considerin... | [
10,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003892556_python_subprocess.txt |
Q:
How to adapt my current splash screen to allow other pieces of my code to run in the background?
Currently I have a splash screen in place. However, it does not work as a real splash screen - as it halts the execution of the rest of the code (instead of allowing them to run in the background).
This is the current... | How to adapt my current splash screen to allow other pieces of my code to run in the background? | Currently I have a splash screen in place. However, it does not work as a real splash screen - as it halts the execution of the rest of the code (instead of allowing them to run in the background).
This is the current (reduced) arquitecture of my program, with the important bits displayed in full. How can I adapt the ... | [
"Your code is pretty messy/complicated. There's no need to override wx.SplashScreen and no reason your splash screen close event should be creating the main application window. Here's how I do splash screens.\nimport wx\n\ndef show_splash():\n # create, show and return the splash screen\n bitmap = wx.Bitmap... | [
13,
0
] | [] | [] | [
"initialization",
"multithreading",
"python",
"splash_screen",
"wxpython"
] | stackoverflow_0003892327_initialization_multithreading_python_splash_screen_wxpython.txt |
Q:
Best Django 'CMS' component for integration into existing site
So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables ad... | Best Django 'CMS' component for integration into existing site | So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms.
... | [
"I have worked with all three (and more) and they are all built for different use cases IMHO. I would agree that these are the top-teir choices.\nThe grid comparison at djangopluggables.com certainly can make evaluating each of these easier.\ndjango-cms is the most full-featured and is something you could actually ... | [
26,
7,
5,
4,
3,
2,
1
] | [] | [] | [
"content_management_system",
"django",
"python"
] | stackoverflow_0000302983_content_management_system_django_python.txt |
Q:
Anyone have a favorite Python coding style enforcer?
I'm trying to find a Python coding style enforcer (tool, not person!). Any recommendations?
A:
I only know pylint, but it is not an automatic code formatter, rather a marking tool.
A:
Don't forget PEP8, both the PEP8 style guide (http://www.python.org/dev/pe... | Anyone have a favorite Python coding style enforcer? | I'm trying to find a Python coding style enforcer (tool, not person!). Any recommendations?
| [
"I only know pylint, but it is not an automatic code formatter, rather a marking tool.\n",
"Don't forget PEP8, both the PEP8 style guide (http://www.python.org/dev/peps/pep-0008/) and the tool\nNot a lint like tool, but keeps your style in line with the main python community.\nyapf (https://pypi.python.org/pypi/y... | [
2,
1,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0003892656_coding_style_python.txt |
Q:
Which embedded database to use for file indexing applications
I need to develop a file indexing application in python and wanted to know which embedded database is the best one to use for indexing.
Any help on this topic is appreciated.
Thanks,
Rajesh
A:
you could use sqlite :
http://www.sqlite.org/
https://g... | Which embedded database to use for file indexing applications | I need to develop a file indexing application in python and wanted to know which embedded database is the best one to use for indexing.
Any help on this topic is appreciated.
Thanks,
Rajesh
| [
"you could use sqlite : \n\nhttp://www.sqlite.org/ \nhttps://github.com/ghaering/pysqlite\n\nAnother one that you could explore is\n\nhttp://www.equi4.com/metakit/\n\nFor file indexing there are tools like pylucene, xapian.\n\nPython file indexing and searching\n\nOther relevant link on SO\n\nFile indexing (using B... | [
3,
0
] | [] | [] | [
"database",
"embedded_database",
"filesystems",
"indexing",
"python"
] | stackoverflow_0003878617_database_embedded_database_filesystems_indexing_python.txt |
Q:
How to properly iterate over a huge QuerySet in django?
I need to retrieve 5 objects that match a certain complex criteria, and I can't/don't want to pass that criteria to the WHERE clause(filter in django), so I need to iterate over the results, testing each record for the criteria until I get my 5 objects, after... | How to properly iterate over a huge QuerySet in django? | I need to retrieve 5 objects that match a certain complex criteria, and I can't/don't want to pass that criteria to the WHERE clause(filter in django), so I need to iterate over the results, testing each record for the criteria until I get my 5 objects, after that I want to throw the query set away and never see it aga... | [
"Why do you worry about caching? Let Django or mysql do what they do. \nIf you are bent on it. You could disable caching for Django. This is quite simple thing to do in settings.py for your project.\nFor Mysql, you need to run some querie(s) to disable the query cache -\nTry using the SQL_NO_CACHE option in your qu... | [
1,
0
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0003893006_django_django_queryset_python.txt |
Q:
C++ and Embedded Python - NUL Terminated Strings
I'm working on embedding Python 2.6 into an existing c++ application. So far I have the Libraries linked in and am able to successfully initialize the Python Interpreter and can also transfer data to Python. I'm having trouble retrieving it, and hope someone can s... | C++ and Embedded Python - NUL Terminated Strings | I'm working on embedding Python 2.6 into an existing c++ application. So far I have the Libraries linked in and am able to successfully initialize the Python Interpreter and can also transfer data to Python. I'm having trouble retrieving it, and hope someone can steer me the right direction. I'm working with this:
P... | [
"A few points:\n\nDon't use strings. You might even be\nable to make them work here with some\ncontortions on *_StringAndSize()\nfunctions, but it won't be what you\nwant. You should store your data in\na custom data structure (or a buffer) that is just\na sequence of bytes (do you really\nwant clients performing... | [
1
] | [] | [] | [
"c++",
"embedded_language",
"python",
"string",
"termination"
] | stackoverflow_0003892961_c++_embedded_language_python_string_termination.txt |
Q:
Problem sorting IntegerProperty in Google App Engine
http://code.google.com/appengine/articles/update_schema.html
Trying to work this out for a nice little updater across my web application. The only difference is rather than sorting on a StringProperty as shown in the example I am using an IntegerProperty.
No mat... | Problem sorting IntegerProperty in Google App Engine | http://code.google.com/appengine/articles/update_schema.html
Trying to work this out for a nice little updater across my web application. The only difference is rather than sorting on a StringProperty as shown in the example I am using an IntegerProperty.
No matter which way round I turn the query I cannot get it to re... | [
"You need to convert bfid to int; self.request.get() returns a string.\nYou also have a problem with your logic; if bfid is None the query will be done twice, the second time with all results less than or equal to None. (This isn't what's causing your problem here, though.)\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003893137_google_app_engine_python.txt |
Q:
Switch-case in Python doesn't work; need another pattern
I need a help with some code here. I wanted to implement the switch case pattern in Python, so like some tutorial said, I can use a dictionary for that, but here is my problem:
# Type can be either create or update or ..
message = { 'create':msg(some_dat... | Switch-case in Python doesn't work; need another pattern | I need a help with some code here. I wanted to implement the switch case pattern in Python, so like some tutorial said, I can use a dictionary for that, but here is my problem:
# Type can be either create or update or ..
message = { 'create':msg(some_data),
'update':msg(other_data)
# can... | [
"message = { 'create':msg(some_data or ''),\n 'update':msg(other_data or '')\n # can have more\n }\n\nBetter yet, to prevent msg from being executed just to fill the dict:\nmessage = { 'create':(msg,some_data),\n 'update':(msg,other_data),\n # can have more\n ... | [
9,
9,
4,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0003886641_design_patterns_python.txt |
Q:
Saving a deep copy of an object, then modifying it and saving another copy?
I have a 'GameBoard' class and am doing a search on it. I want to save the current gameboard in a list, change the state of the gameboard, save THAT one in a list, and so on (so I would have incremental versions of the gameboard as a game... | Saving a deep copy of an object, then modifying it and saving another copy? | I have a 'GameBoard' class and am doing a search on it. I want to save the current gameboard in a list, change the state of the gameboard, save THAT one in a list, and so on (so I would have incremental versions of the gameboard as a game progresses).
I'm currently doing this with copy.deepcopy, but it doesn't seem to... | [
"Your code is valid for a simple dictionary object:\nseq = 1\na_dict = {}\nmoves = []\nwhile seq < 4:\n a_dict['key' + str(seq)] = 'value' + str(seq)\n moves.append(copy.deepcopy(a_dict))\n seq = seq + 1\n\nprint moves\n\nSomehow for your object, deepcopy does not reach the contents of your gameboard. \nIs your gam... | [
0
] | [] | [] | [
"copy",
"python"
] | stackoverflow_0003891757_copy_python.txt |
Q:
python: retrieve names of all builtins
How can I retrieve names of all builtins for my current python distribution during runtime?
A:
I am not sure if this suffices, but you can fire up the interpreter and do the following
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseExcepti... | python: retrieve names of all builtins | How can I retrieve names of all builtins for my current python distribution during runtime?
| [
"I am not sure if this suffices, but you can fire up the interpreter and do the following\n>>> dir(__builtins__)\n['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingP... | [
4
] | [] | [] | [
"built_in",
"python"
] | stackoverflow_0003893287_built_in_python.txt |
Q:
What python html generator module should I use in a non-web application?
I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be v... | What python html generator module should I use in a non-web application? | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to outp... | [
"Maybe you could try Markdown instead, and convert it to HTML on the fly?\n",
"You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:\nhttp://github.com/Yelp/PushmasterApp/blob/master/pushmaster/taglib.py\n(Full disclosure, I work with the ... | [
6,
4,
3,
2,
2,
1
] | [] | [] | [
"html_generation",
"python"
] | stackoverflow_0003887393_html_generation_python.txt |
Q:
Read multiple lines from subprocess.Popen.stdout
I modified the source code from Fred Lundh's Python Standard Library.
The original source uses popen2 to communicate to subprocess, but I changed it to use subprocess.Popen() as follows.
import subprocess
import string
class Chess:
"Interface class for chessto... | Read multiple lines from subprocess.Popen.stdout | I modified the source code from Fred Lundh's Python Standard Library.
The original source uses popen2 to communicate to subprocess, but I changed it to use subprocess.Popen() as follows.
import subprocess
import string
class Chess:
"Interface class for chesstool-compatible programs"
def __init__(self, engine... | [
"To interact with gnuchess, I'd use pexpect.\nimport pexpect\nimport sys\ngame = pexpect.spawn('/usr/games/gnuchess')\n# Echo output to stdout\ngame.logfile = sys.stdout\ngame.expect('White')\ngame.sendline('a2a4')\ngame.expect('White')\ngame.sendline('b2b3')\ngame.expect('White')\ngame.sendline('quit')\n\n",
"I ... | [
2,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003893473_python_subprocess.txt |
Q:
what's the quickest way to simple-merge files and what's the quickest way to split an array?
what's the quickest way to take a list of files and a name of an output file and merge them into a single file while removing duplicate lines?
something like
cat file1 file2 file3 | sort -u > out.file
in python.
prefer not... | what's the quickest way to simple-merge files and what's the quickest way to split an array? | what's the quickest way to take a list of files and a name of an output file and merge them into a single file while removing duplicate lines?
something like
cat file1 file2 file3 | sort -u > out.file
in python.
prefer not to use system calls.
AND:
what's the quickest way to split a list in python into X chunks (list o... | [
"First:\nlines = set()\nfor filename in filenames:\n with open(filename) as inF:\n lines.update(inF)\nwith open(outfile, 'w') as outF:\n outF.write(''.join(lines))\n\nSecond: \ndef chunk(bigList, x):\n chunklen = len(bigList) / x\n for i in xrange(0, len(bigList), chunklen):\n yield bigLis... | [
2
] | [
"For the first:\nlines = []\nfor filename in filenames:\n f = open(filename)\n lines.extend(f.read().split('\\n')\n f.close()\nlines = list(set(lines)) #remove duplicates\nf = open(outfile_name, 'w')\nf.write(''.join(lines))\n\nassuming that the files are a reasonable length as all the data from the files ... | [
-1
] | [
"python"
] | stackoverflow_0003893696_python.txt |
Q:
Getting implicit property names on a db.Model in Google App Engine?
How can I get access to the implicit property names of a db.Model in Google App Engine? In particular, assume I have the following:
class Foo(db.Model):
specific = db.IntegerProperty()
class Bar(db.Model):
foo = db.ReferenceProperty(Foo, colle... | Getting implicit property names on a db.Model in Google App Engine? | How can I get access to the implicit property names of a db.Model in Google App Engine? In particular, assume I have the following:
class Foo(db.Model):
specific = db.IntegerProperty()
class Bar(db.Model):
foo = db.ReferenceProperty(Foo, collection_name = "bars")
if I attempt to get the property names on Foo, li... | [
"(That model definition looks like a strange hybrid of Python and Ruby.)\nI'm not clear on what you're trying to achieve here, but you can get a list of model property members using introspection: \n[x for x in dir(Foo) if isinstance(getattr(Foo,x), db.Property)]\n\nIf you're just trying to add instances of Bar to ... | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003893405_google_app_engine_google_cloud_datastore_python.txt |
Q:
what can cause pdb.set_trace() to be ignored?
I'm trying to debug a Python program and I inserted a classic 'import pdb;pdb.set_trace()' line in a function, just before a call which generates a stack trace. However that call seems to be ignored, i.e. nothing happens and I don't get a pdb prompt.
At that point of ... | what can cause pdb.set_trace() to be ignored? | I'm trying to debug a Python program and I inserted a classic 'import pdb;pdb.set_trace()' line in a function, just before a call which generates a stack trace. However that call seems to be ignored, i.e. nothing happens and I don't get a pdb prompt.
At that point of the program, there is only one active thread. No mo... | [
"Perhaps you've got some tricky code that manipulates the trace function in a complicated way? Or are you using an accelerator like psyco?\n",
"This is going to waste the time of a number Python developers. Tonight I added myself to their ranks. I wish I had found this post before I spent 2 hours discovering a s... | [
7,
5,
1
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0003466552_debugging_python.txt |
Q:
Terminate subprocess in Windows, access denied
-
import time
import subprocess
from os.path import expanduser
chrome_path = expanduser('~\Local Settings\Application Data\Google\Chrome\Application\chrome.exe')
proc = subprocess.Popen(chrome_path)
time.sleep(4)
proc.terminate()
Output: WindowsError: [Error 5] Ac... | Terminate subprocess in Windows, access denied | -
import time
import subprocess
from os.path import expanduser
chrome_path = expanduser('~\Local Settings\Application Data\Google\Chrome\Application\chrome.exe')
proc = subprocess.Popen(chrome_path)
time.sleep(4)
proc.terminate()
Output: WindowsError: [Error 5] Access is denied
How can I kill the Chrome process?
Py... | [
"I don't know about Windows, but have noticed on Linux that Google Chrome \"protects\" itself from operating system control signals in a way that few programs do:\n$ ps -lp 2345\nF S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD\n4 S 1000 2345 1 0 80 0 - 17699 skb_re ? 00:00:00 ... | [
2,
0,
0
] | [] | [] | [
"python",
"subprocess",
"terminate",
"windows"
] | stackoverflow_0002868129_python_subprocess_terminate_windows.txt |
Q:
python - strtotime equivalent?
I'm using this to convert date time strings to a unix timestamp:
str(int(time.mktime(time.strptime(date,"%d %b %Y %H:%M:%S %Z"))))
However often the date structure isn't the same so I keep getting the following error message:
time data did not match format: data=Tue, 26 May 2009 1... | python - strtotime equivalent? | I'm using this to convert date time strings to a unix timestamp:
str(int(time.mktime(time.strptime(date,"%d %b %Y %H:%M:%S %Z"))))
However often the date structure isn't the same so I keep getting the following error message:
time data did not match format: data=Tue, 26 May 2009 19:58:20 -0500 fmt=%d %b %Y %H:%M:%S... | [
"from dateutil.parser import parse\n\nparse('Tue, 26 May 2009 19:58:20 -0500').strftime('%s')\n\n# returns '1243364300'\n\n"
] | [
27
] | [] | [] | [
"python"
] | stackoverflow_0003894010_python.txt |
Q:
Python to javascript communication
OK so im using websockets to let javascript talk to python and that works very well BUT the data i need to send often has several parts like an array, (username,time,text) but how could i send it ? I originally though to encode each one in base64 or urlencode then use a character... | Python to javascript communication | OK so im using websockets to let javascript talk to python and that works very well BUT the data i need to send often has several parts like an array, (username,time,text) but how could i send it ? I originally though to encode each one in base64 or urlencode then use a character like | which those encoding methods wil... | [
"JSON is definitely the way to go. It has a very small overhead and is capable of storing almost any kind of data. I am not a python expert, but i am sure that there is some kind of en/decoder available.\n",
"Use json module (or simplejson prior to Python 2.6).\nYou'd only need to remember two functions: json.dum... | [
7,
1
] | [] | [] | [
"encoding",
"javascript",
"python",
"sockets"
] | stackoverflow_0003890390_encoding_javascript_python_sockets.txt |
Q:
SpringPython error following the book: AttributeError: 'module' object has no attribute 'ObjBase'
Well, I bought the book Spring Python 1.1 and I have been facing some problems that I cannot solve. I am going to write the code of each file in order to make sure everything is clear. If some of you know what is the ... | SpringPython error following the book: AttributeError: 'module' object has no attribute 'ObjBase' | Well, I bought the book Spring Python 1.1 and I have been facing some problems that I cannot solve. I am going to write the code of each file in order to make sure everything is clear. If some of you know what is the problem, please let me know because I am desperate.
simple_service.py
class Service(object):
def happy_... | [
"I wonder what your Pyro version is. Here using Pyro 3.9.1-1 from Ubuntu 10.04 I have no problems with running your code. Could it be that you're using Pyro 4.x which if I recall correctly was released after the book had been published?\n"
] | [
1
] | [] | [] | [
"python",
"spring"
] | stackoverflow_0003889684_python_spring.txt |
Q:
Clustering problem
I've been tasked to find N clusters containing the most points for a certain data set given that the clusters are bounded by a certain size. Currently, I am attempting to do this by plugging in my data into a kd-tree, iterating over the data and finding its nearest neighbor, and then merging the... | Clustering problem | I've been tasked to find N clusters containing the most points for a certain data set given that the clusters are bounded by a certain size. Currently, I am attempting to do this by plugging in my data into a kd-tree, iterating over the data and finding its nearest neighbor, and then merging the points if the cluster t... | [
"Check out scipy.clustering for a start. Key word searches can then give a lot of info on the different algorithms that are used there. Clustering is a big field, with a lot of research and practical applications, and a number of simple approaches that have been found to work fairly well, so you may not want to s... | [
7,
0,
0
] | [] | [] | [
"algorithm",
"classification",
"cluster_analysis",
"nearest_neighbor",
"python"
] | stackoverflow_0003891645_algorithm_classification_cluster_analysis_nearest_neighbor_python.txt |
Q:
How to access a specific class instance by attribute in python?
Say I have a class Box with two attributes, self.contents and self.number. I have instances of box in a list called Boxes. Is there anyway to access/modify a specific instance by its attribute rather than iterating through Boxes? For example, if I wan... | How to access a specific class instance by attribute in python? | Say I have a class Box with two attributes, self.contents and self.number. I have instances of box in a list called Boxes. Is there anyway to access/modify a specific instance by its attribute rather than iterating through Boxes? For example, if I want a box with box.number = 40 (and the list is not sorted) what would ... | [
"If you need to do it more frequently and you have unique numbers, then create a dictionary:\nnumberedBox = dict((b.number, b) for b in Boxes)\n\nyou can then access your boxes directly with numbers:\nnumberedBox[40]\n\nbut if you want to change their number, you will have to modify the numberedBox dictionary too..... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003893495_python.txt |
Q:
Filtering of an Object's property's property in google app engine
In an App Engine app, I store registered members in a table that looks like this:
class Member(db.Model):
user = db.UserProperty(required=True)
#other stuff
The problem starts when I need to check if a User is already in my Member table. GA... | Filtering of an Object's property's property in google app engine | In an App Engine app, I store registered members in a table that looks like this:
class Member(db.Model):
user = db.UserProperty(required=True)
#other stuff
The problem starts when I need to check if a User is already in my Member table. GAE documentation says user value is not guaranteed not to change in time... | [
"You should be able to do this:\nu = users.get_current_user()\nrm = Member.all().filter('user =', u).get()\n\n",
"Maybe you can identify your user by a unique key_name:\nkey_name = \"member/%s\" % users.get_current_user ().user_id\nuser_ref = Member.get_or_insert (key_name)\n\n"
] | [
1,
0
] | [
"GAE User API explicitly mentions user_id() as a permanent identifier that persists across e-mail changes. You can store it in separate field in model.\nNote that it is only supported for Google Accounts.\n"
] | [
-1
] | [
"google_app_engine",
"python"
] | stackoverflow_0003890285_google_app_engine_python.txt |
Q:
Background Running Python Script keeps stopping
I made a .pyw python script that I want to have running in the background of my computer.
Right now I have it set to launch by putting it in the Startup folder of my Windows 7 computer, which should trigger it to launch whenever it starts up.
The problem is that the ... | Background Running Python Script keeps stopping | I made a .pyw python script that I want to have running in the background of my computer.
Right now I have it set to launch by putting it in the Startup folder of my Windows 7 computer, which should trigger it to launch whenever it starts up.
The problem is that the script seems to stop running at some point for some r... | [
"If there really is need for a continuously running background process, you should look into making a service.\npywin32 helps in creating NT services with python\nIf you're into .NET, you can try also IronPython, but I don't know whether that is more easy.\n"
] | [
0
] | [] | [] | [
"background_process",
"python",
"sleep"
] | stackoverflow_0003894360_background_process_python_sleep.txt |
Q:
Python web programming with standard library
I want to write a simple python web application to provide a gui to a command line program (think of hg serve, for example). It would run locally only. I don't want it to have any external dependencies for an easier deployment, so python web programming in general would... | Python web programming with standard library | I want to write a simple python web application to provide a gui to a command line program (think of hg serve, for example). It would run locally only. I don't want it to have any external dependencies for an easier deployment, so python web programming in general wouldn't apply here
How can it be done with a minimal h... | [
"The wsgiref package from the standard library has a simple server to serve wsgi applications. You can use it to run your own framework-less wsgi application, a minimal wsgi application isn't terribly difficult (see the hello world example at the end of the wsgiref documentation page)\nYou might want to relax the \... | [
4,
0,
0
] | [] | [] | [
"cgi",
"python",
"standard_library"
] | stackoverflow_0003893774_cgi_python_standard_library.txt |
Q:
PyQt and QSignalMapper/lambdas - multiple signals, single slot
I have a list of actions on a menu in PyQt, one for each different feed I want to display. So I have a Y that sets the active feed to Y, Z sets it to Z, etc. (For a webcomic reading program).
I have each on the menu, and felt that an automated approach... | PyQt and QSignalMapper/lambdas - multiple signals, single slot | I have a list of actions on a menu in PyQt, one for each different feed I want to display. So I have a Y that sets the active feed to Y, Z sets it to Z, etc. (For a webcomic reading program).
I have each on the menu, and felt that an automated approach might be better; rather than typing out each time. Something like a... | [
"You can use functools.partial (link to the documentation):\nimport functools\n...\n\n# note that these are the 'new style' slot connections (not necessarily needed)\nself.menu_entry_x.triggered.connect(functools.partial(myfunc, x))\nself.menu_entry_y.triggered.connect(functools.partial(myfunc, y))\n\nThe example i... | [
5
] | [] | [] | [
"pyqt",
"python",
"qt",
"signals",
"signals_slots"
] | stackoverflow_0003893876_pyqt_python_qt_signals_signals_slots.txt |
Q:
example function in Python: counting words
I'm a bit rusty in Python and am just looking for help implementing an example function to count words (this is just a sample target for a scons script that doesn't do anything "real"):
def countWords(target, source, env):
if (len(target) == 1 and len(source) == 1):
... | example function in Python: counting words | I'm a bit rusty in Python and am just looking for help implementing an example function to count words (this is just a sample target for a scons script that doesn't do anything "real"):
def countWords(target, source, env):
if (len(target) == 1 and len(source) == 1):
fin = open(str(source[0]), 'r')
# do someth... | [
"from collections import defaultdict\n\ndef countWords(target, source, env):\n words = defaultdict(int)\n if (len(target) == 1 and len(source) == 1):\n with open(str(source[0]), 'r') as fin:\n for line in fin:\n for word in line.split():\n words[word] += 1\n... | [
7,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_2.6"
] | stackoverflow_0003894265_python_python_2.6.txt |
Q:
python + mongo issue
I'm playing around with mongodb (documentation isn't very complete):
tmpQuery = collection.find({"title_full": "kdsljfklsadfklj"})
print tmpQuery[0]['title_full']
That just echo's "no such item for Cursor instance", what is an if statement to determine if the variable tmpQuery has a valid res... | python + mongo issue | I'm playing around with mongodb (documentation isn't very complete):
tmpQuery = collection.find({"title_full": "kdsljfklsadfklj"})
print tmpQuery[0]['title_full']
That just echo's "no such item for Cursor instance", what is an if statement to determine if the variable tmpQuery has a valid result set and not empty?
| [
"oh geez, issue solved with:\ntmpQuery.count()\n\n"
] | [
4
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0003894419_mongodb_python.txt |
Q:
String to datetime
I saved a datetime.datetime.now() as a string.
Now I have a string value, i.e.
2010-10-08 14:26:01.220000
How can I convert this string to
Oct 8th 2010
?
Thanks
A:
from datetime import datetime
datetime.strptime('2010-10-08 14:26:01.220000'[:-7],
'%Y-%m-%d %H:%M:%S').strfti... | String to datetime | I saved a datetime.datetime.now() as a string.
Now I have a string value, i.e.
2010-10-08 14:26:01.220000
How can I convert this string to
Oct 8th 2010
?
Thanks
| [
"\nfrom datetime import datetime\ndatetime.strptime('2010-10-08 14:26:01.220000'[:-7], \n '%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')\n\n",
"You don't need to create an intermediate string.\nYou can go directly from a datetime to a string with strftime():\n>>> datetime.now().strftime('%b %d %Y')\n'Oc... | [
6,
2,
0
] | [] | [] | [
"date_format",
"datetime",
"python"
] | stackoverflow_0003894462_date_format_datetime_python.txt |
Q:
Replace numeric character references in XML document using Python
I am struggling with the following issue: I have an XML string that contains the following tag and I want to convert this, using cElementTree, to a valid XML document:
<tag>#55296;#57136;#55296;#57149;#55296;#57139;#55296;#57136;#55296;#57151;#5529... | Replace numeric character references in XML document using Python | I am struggling with the following issue: I have an XML string that contains the following tag and I want to convert this, using cElementTree, to a valid XML document:
<tag>#55296;#57136;#55296;#57149;#55296;#57139;#55296;#57136;#55296;#57151;#55296;
#57154;#55296;#57136;</tag>
but each # sign is preceded by a & sign... | [
"Eurgh. You've got surrogates (UTF-16 code units in the range D800-DFFF), which some fool has incorrectly encoded individually instead of using a pair of code units for a single character. It would be ideal to replace this mess with what it should look like:\n<tag>𐌰𐌽𐌳𐌰𐌿𐍂... | [
4
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0003894564_python_xml.txt |
Q:
Timed out after 30000ms
When I use SeleniumRC,sometimes I meet a error, but sometimes not. I guess it's related to the time of wait_for_page_to_load(), but I don't know how long will it need?
The error information:
Exception: Timed out after 30000ms
File "C:\Users\Herta\Desktop\test\newtest.py", line 9, in <module... | Timed out after 30000ms | When I use SeleniumRC,sometimes I meet a error, but sometimes not. I guess it's related to the time of wait_for_page_to_load(), but I don't know how long will it need?
The error information:
Exception: Timed out after 30000ms
File "C:\Users\Herta\Desktop\test\newtest.py", line 9, in <module>
sel.open(url)
File "C:\Us... | [
"Timing is a big issue when automating UI pages. You want to make sure you use timeouts when needed and provide the needed time for certain events. I see that you have\nsel.open(url)\nsel.wait_for_page_to_load(1000)\n\nThe sel.wait_for_page_to_load command after a sel.open call is redundant. All sel.open commands h... | [
1,
0,
0
] | [] | [] | [
"python",
"selenium_rc"
] | stackoverflow_0003458830_python_selenium_rc.txt |
Q:
figuring out how to get all of the public ips of a machine
I am running my code on multiple VPSes (with more than one IP, which are set up as aliases to the network interfaces) and I am trying to figure out a way such that my code acquires the IP addresses from the network interfaces on the fly and bind to it. Any... | figuring out how to get all of the public ips of a machine | I am running my code on multiple VPSes (with more than one IP, which are set up as aliases to the network interfaces) and I am trying to figure out a way such that my code acquires the IP addresses from the network interfaces on the fly and bind to it. Any ideas on how to do it in python without adding a 3rd party libr... | [
"The IP addresses are assigned to your VPSes, no possibility to change them on the fly.\nYou have to open a SSH tunnel to or install a proxy on your VPSes.\nI think a SSH tunnel would be the best way how to do it, and then use it as SOCKS5 proxy from Python.\n",
"This is how to get all IP addresses of the server ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003881951_python.txt |
Q:
json.dumps(pickle.dumps(u'å')) raises UnicodeDecodeError
Is this a bug?
>>> import json
>>> import cPickle
>>> json.dumps(cPickle.dumps(u'å'))
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.p... | json.dumps(pickle.dumps(u'å')) raises UnicodeDecodeError | Is this a bug?
>>> import json
>>> import cPickle
>>> json.dumps(cPickle.dumps(u'å'))
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 230, in dumps
return _default_encoder.encode(obj)... | [
"The json module is expecting strings to encode text. Pickled data isn't text, it's 8-bit binary.\nOne simple workaround, if you really need to send pickled data over JSON, is to use base64:\nj = json.dumps(base64.b64encode(cPickle.dumps(u'å')))\ncPickle.loads(base64.b64decode(json.loads(j)))\n\nNote that this is ... | [
7,
1,
0
] | [] | [] | [
"json",
"pickle",
"python"
] | stackoverflow_0003895036_json_pickle_python.txt |
Q:
Open file into array, search for string and return value
Alright, I've been working on this for a while and cannot get it.
I'm making a method that accepts a filename, and a pattern.
E.g findPattern(fname, pat)
Then the goal is to look for that pattern, say the string "apple" within the text file that is opened, a... | Open file into array, search for string and return value | Alright, I've been working on this for a while and cannot get it.
I'm making a method that accepts a filename, and a pattern.
E.g findPattern(fname, pat)
Then the goal is to look for that pattern, say the string "apple" within the text file that is opened, and return it's location by [line, beginning character index]
I... | [
"The only way to get text data into an array is as chars:\na = array.array('c', open(filename, 'rb').read())\n\nFrom there, you can simply iterate over it and convert each subarray with the same length as your substring to a string to compare:\nfor i in xrange(len(a)):\n if ''.join(a[i:i+len(substring)]) == subst... | [
1
] | [] | [] | [
"arrays",
"file",
"python",
"search",
"string"
] | stackoverflow_0003894572_arrays_file_python_search_string.txt |
Q:
Python: Changing process name with setproctitle
I have a python script which launches a number of C++ programs, each program is passed a command line parameter as shown below
process_path "~/test/"
process_name "test"
num_process = 10
for p in range(1, num_processes, 1):
subprocess.Popen([process_path + proc... | Python: Changing process name with setproctitle | I have a python script which launches a number of C++ programs, each program is passed a command line parameter as shown below
process_path "~/test/"
process_name "test"
num_process = 10
for p in range(1, num_processes, 1):
subprocess.Popen([process_path + process_name, str(p)], shell = False)
Is it possible to ... | [
"setproctitle can only change it's \"own\" process title as I would presume a safety element, but the technique of rewriting the process table is an ancient rootkit technique -- so clearly it is possible. \nFurthermore, setproctitle has support for multiple operating systems, so the method in which you change the p... | [
2,
1,
0
] | [] | [] | [
"process",
"python"
] | stackoverflow_0003548294_process_python.txt |
Q:
python global object cache
Little question concerning app architecture:
I have a python script, running as a daemon.
Inside i have many objects, all inheriting from one class (let's name it 'entity')
I have also one main object, let it be 'topsys'
Entities are identified by pair (id, type (= class, roughly)), and ... | python global object cache | Little question concerning app architecture:
I have a python script, running as a daemon.
Inside i have many objects, all inheriting from one class (let's name it 'entity')
I have also one main object, let it be 'topsys'
Entities are identified by pair (id, type (= class, roughly)), and they are connected in many wicke... | [
"There's not enough detail here to be certain of what's best, but in general I'd store the actual object registry as a module-level (global) variable in the top class, and have a method in the base class to access it.\n_entities = []\nclass entity(object):\n @staticmethod\n def get_entity_registry(): \n ... | [
6,
0
] | [] | [] | [
"class_design",
"design_patterns",
"global_variables",
"python"
] | stackoverflow_0003895359_class_design_design_patterns_global_variables_python.txt |
Q:
python RSA module how to use java decrypt
I use python rsa module(http://stuvel.eu/rsa) get private_key and public_key.
How can I use these private_key and public_key to encrypt or decrypt in java?
A:
Thank you all. I think I have got the method.
The python's Rsa module can generate (n,p,q,e,d).I can use follow ... | python RSA module how to use java decrypt | I use python rsa module(http://stuvel.eu/rsa) get private_key and public_key.
How can I use these private_key and public_key to encrypt or decrypt in java?
| [
"Thank you all. I think I have got the method.\nThe python's Rsa module can generate (n,p,q,e,d).I can use follow method in Java\nKeyFactory s=KeyFactory.getInstance(\"RSA\");\nKey pri_k=s.generatePrivate(new RSAPrivateKeySpec(new BigInteger(n=p*q),new BigInteger(e));\nKey pub_k=s.generatePublic(new RSAPublicKeyS... | [
2,
0
] | [] | [] | [
"java",
"python",
"rsa"
] | stackoverflow_0003889416_java_python_rsa.txt |
Q:
How importing works. Why imported modules not inheriting other imported modules
I just "thought" I understood how importing and modules work but obviously I need more schooling.
Here is an example program (just a test case of somerthing I'm doing that is much bigger in scope and scale) and a module:
quick.py
impor... | How importing works. Why imported modules not inheriting other imported modules | I just "thought" I understood how importing and modules work but obviously I need more schooling.
Here is an example program (just a test case of somerthing I'm doing that is much bigger in scope and scale) and a module:
quick.py
import gtk
from quick_window import *
w.show_all()
gtk.main()
quick_window.py
w = gtk.Wi... | [
"The details of importing get very complicated, but conceptually it is very simple.\nWhen you write:\nimport some_module\n\nIt is equivalent to this:\nsome_module = import_module(\"some_module\")\n\nwhere import_module is kind of like:\ndef import_module(modname):\n if modname in sys.modules:\n module = s... | [
13,
6
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003895346_import_module_python.txt |
Q:
transforming an image into an array of lines to draw
How do I generate a list of lines to draw if I have pixel data for an image, so I don't have to draw every pixel? Any language will do, although I listed what I have a working knowledge for. C is ok as well. There was a limit to how many tags I could choose. Als... | transforming an image into an array of lines to draw | How do I generate a list of lines to draw if I have pixel data for an image, so I don't have to draw every pixel? Any language will do, although I listed what I have a working knowledge for. C is ok as well. There was a limit to how many tags I could choose. Also, you can just point me toward an algorithm.
| [
"In general, bitmaps are stored in sequential memory, ideal for 'blitting' to the display; your GUI framework of choice will have a function for drawing bitmaps, and this function will be very carefully optimised.\nOn the other hand, decomposing an image into lines - vectorizing the image - is the domain of special... | [
1,
1,
1,
0,
0
] | [] | [] | [
"c#",
"c++",
"image",
"lua",
"python"
] | stackoverflow_0003878873_c#_c++_image_lua_python.txt |
Q:
Why the connect failed for ipv6 at python?
Why the connect failed for ipv6 ??
# python
>>> import socket
>>> s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
>>> sa = ('2000::1',2000,0,0)
>>> s.connect(sa)
>>> sa = ('fe80::21b:78ff:fe30:7c6', 2000, 0, 0)
>>> s.connect(... | Why the connect failed for ipv6 at python? | Why the connect failed for ipv6 ??
# python
>>> import socket
>>> s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
>>> sa = ('2000::1',2000,0,0)
>>> s.connect(sa)
>>> sa = ('fe80::21b:78ff:fe30:7c6', 2000, 0, 0)
>>> s.connect(sa)
Traceback (most recent call last):
... | [
"Link-local addresses (e.g. fe80::whatever) typically require a scope id to be specified in order to work. Try\nsa = ('fe80::21b:78ff:fe30:7c6%en0', 2000, 0, 0) \n\ninstead. (If the computer you're trying to connect() to is accessible via a network interface other than en0, substitute in the name of the interfac... | [
6
] | [] | [] | [
"connect",
"ipv6",
"python",
"sockets"
] | stackoverflow_0003895570_connect_ipv6_python_sockets.txt |
Q:
This code for creating a QPolygon in Pyqt is stopping my application! Help?
HI all,
The following code:
self.painter = QtGui.QPainter(self)
self.painter.setRenderHint(QPainter.Antialiasing)
self.painter.translate(482,395)
self.painter.scale(300,300)
self.painter.save()
needle = Qt.QPolygon([QPoint(30, 0), QPoint(-... | This code for creating a QPolygon in Pyqt is stopping my application! Help? | HI all,
The following code:
self.painter = QtGui.QPainter(self)
self.painter.setRenderHint(QPainter.Antialiasing)
self.painter.translate(482,395)
self.painter.scale(300,300)
self.painter.save()
needle = Qt.QPolygon([QPoint(30, 0), QPoint(-30, 0), QPoint(0, 200)])
self.painter.setBrush(Qt.cyan)
self.painter.setPen(Qt.bl... | [
"Save the list which you pass the the constructor of QPolygon in a local variable. I guess that the elements get garbage collected as soon as the call returns so when you draw the polygon, they are no longer around.\npoints = [QPoint(30, 0), QPoint(-30, 0), QPoint(0, 200)]\nneedle = Qt.QPolygon(points)\n\n",
"Bec... | [
2,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"windows"
] | stackoverflow_0003828489_pyqt_pyqt4_python_qt_windows.txt |
Q:
Accessing session variable in Django template with Google App Engine (Webapp) - Python
I have a Django template as my front-end. At the back-end, I used the sessions provided from Gaeutilities to store a variable (email).
Front-end:
{% if session.Email %}
<div id="entersite">WELCOME <em>{{session.Email}}</... | Accessing session variable in Django template with Google App Engine (Webapp) - Python | I have a Django template as my front-end. At the back-end, I used the sessions provided from Gaeutilities to store a variable (email).
Front-end:
{% if session.Email %}
<div id="entersite">WELCOME <em>{{session.Email}}</em></div>
{% else %}
<div id= "entersite"><a href="/login/" id= "entersite">Ente... | [
"You need to set your session object in a django template context, no?\ntemplate.render(temp, {'session':self.session})\n\n",
"By doing so, you are just rendering the template with the session value. What happens is that when I click on a link to another page, and from that page return back to the same template, ... | [
2,
1
] | [] | [] | [
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0003887664_django_templates_google_app_engine_python.txt |
Q:
How to make a light query for a many to many relationship in Google Apps Engine?
How to make a light query for a many to many relationship?
Users has many Lists
the ListUser is the model that links them
Currently I'm doing like this but there are a lot of get queries to get all this data.
lists = []
for list in us... | How to make a light query for a many to many relationship in Google Apps Engine? | How to make a light query for a many to many relationship?
Users has many Lists
the ListUser is the model that links them
Currently I'm doing like this but there are a lot of get queries to get all this data.
lists = []
for list in user.lists:
lists.append(list.list)
Now I got this:
list_users = user.lists.fetch(1... | [
"You should use get_value_for_datastore.\nlist_keys = [ListUser.list.get_value_for_datastore(list_user)\n for list_user in list_users]\nlists = db.get(list_keys)\n\nIf you have not already, you might want to take a look at some of the 'mastering the datastore' articles. Specifically the one on modelin... | [
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003895304_google_app_engine_google_cloud_datastore_python.txt |
Q:
Call python script from AIR application?
How can we invoke a python script using AIR 1.5?
A:
You cannot directly invoke system commands or run an executable (the python interpreter) from within an AIR application. If it's possible to share what exactly you want to do, maybe we can suggest alternatives.
If it's ... | Call python script from AIR application? | How can we invoke a python script using AIR 1.5?
| [
"You cannot directly invoke system commands or run an executable (the python interpreter) from within an AIR application. If it's possible to share what exactly you want to do, maybe we can suggest alternatives. \nIf it's really really (that's two reallys) important to run an executable from AIR lookup the CommandP... | [
1,
0,
0
] | [
"Hypothetically, Adobe Alchemy technology may allow you to port Python interpreter to Flash.\nThough I seriously doubt that's the approach you want to use. Depending on task there should be easier solutions.\n"
] | [
-1
] | [
"air",
"flex3",
"python"
] | stackoverflow_0000771738_air_flex3_python.txt |
Q:
Installed python3, getting command not found error in terminal
I installed python3, I can open idle and it says it is running python3.0.1, but when I enter python3 in the terminal (on OSX) I get an error saying 'command not found'. Entering python gets me the 2.x version that came on the computer. Any advice on ho... | Installed python3, getting command not found error in terminal | I installed python3, I can open idle and it says it is running python3.0.1, but when I enter python3 in the terminal (on OSX) I get an error saying 'command not found'. Entering python gets me the 2.x version that came on the computer. Any advice on how I can access python3 from the terminal?
Thanks
| [
"First, don't use Python 3.0.1. It has many problems and was officially retired upon the release of Python 3.1 (currently 3.1.2). You can find the python.org Mac OS X installer for 3.1.2 here. Once it is installed, then you need to ensure that the bin directory from the 3.1.2 framework (/Library/Frameworks/Pytho... | [
16
] | [] | [] | [
"macos",
"path",
"python"
] | stackoverflow_0003895756_macos_path_python.txt |
Q:
Selecting area of the screen with Python
I'm developing a screen shot utility in Python. At the moment it is specifically for Linux. So far I have the ability to take a screen shot of the full desktop, and have it upload to Imgur, then copy the link to clipboard. Now I want to expand into functions such as screen ... | Selecting area of the screen with Python | I'm developing a screen shot utility in Python. At the moment it is specifically for Linux. So far I have the ability to take a screen shot of the full desktop, and have it upload to Imgur, then copy the link to clipboard. Now I want to expand into functions such as screen shots of the active window, or of a specific s... | [
"The functionality will depend on what you are using for image grabbing.\n\nWith PIL\n\n\nhttp://effbot.org/imagingbook/imagegrab.htm\n\n\nWith GTK\n\nTo take a screenshot of active window : \n\nhttp://faq.pygtk.org/index.py?req=show&file=faq23.039.htp\n\nAlso look at the pixbuf api\n\nhttp://library.gnome.org/deve... | [
2
] | [] | [] | [
"python",
"screenshot"
] | stackoverflow_0003895732_python_screenshot.txt |
Q:
Python's print function that flushes the buffer when it's called?
Possible Duplicates:
How to flush output of Python print?
unbuffered stdout in python (as in python -u) from within the program
I have the following code to flushing out the output buffer.
print 'return 1'
sys.stdout.flush()
Can I setup the prin... | Python's print function that flushes the buffer when it's called? |
Possible Duplicates:
How to flush output of Python print?
unbuffered stdout in python (as in python -u) from within the program
I have the following code to flushing out the output buffer.
print 'return 1'
sys.stdout.flush()
Can I setup the print function so that it automatically flushes the buffer when it's calle... | [
"You can start python in unbuffered mode using the -u flag, e.g.\npython -u script.py\n\nor\n#!/usr/bin/env python -u\n\nas \"shebang\" header for your script.\n"
] | [
15
] | [] | [] | [
"flush",
"python"
] | stackoverflow_0003895481_flush_python.txt |
Q:
SHA256 hash in Python 2.4
Is there a way I can calculate a SHA256 hash in Python 2.4? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in this question, but using Python 2.4.
A:
Yes yo... | SHA256 hash in Python 2.4 | Is there a way I can calculate a SHA256 hash in Python 2.4? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in this question, but using Python 2.4.
| [
"Yes you can. With Python 2.4, there was SHA-1 module which does exactly this. See the documentation.\nHowever, bear in mind that code importing from this module will cause DeprecationWarnings when run with newer Python.\nOk, as the requirement was tightened to be SHA-256, using the SHA-1 module in standard library... | [
10,
8,
4
] | [] | [] | [
"python",
"python_2.4",
"sha256"
] | stackoverflow_0001328155_python_python_2.4_sha256.txt |
Q:
use sqlalchemy entity isolately
i just want to use an entity modify it to show something,but don't want to change to the db,
but after i use it ,and in some other place do the session.commit()
it will add this entity to db,i don't want this happen,
any one could help me?
A:
You can expunge it from session before... | use sqlalchemy entity isolately | i just want to use an entity modify it to show something,but don't want to change to the db,
but after i use it ,and in some other place do the session.commit()
it will add this entity to db,i don't want this happen,
any one could help me?
| [
"You can expunge it from session before modifying object, then this changes won't be accounted on next commits unless you add the object back to session. Just call session.expunge(obj).\n"
] | [
1
] | [] | [] | [
"entity",
"python",
"sqlalchemy"
] | stackoverflow_0003881364_entity_python_sqlalchemy.txt |
Q:
Using sqlchemy in Pyqt, is it possible?
Hi i am new to Pyqt and i am wondering if it is possible to have goodness of sqlalchemy e.g. connection pooling and managing, abstracting away all the menial low level details?
A:
Have a look at Camelot. http://www.python-camelot.com/
| Using sqlchemy in Pyqt, is it possible? | Hi i am new to Pyqt and i am wondering if it is possible to have goodness of sqlalchemy e.g. connection pooling and managing, abstracting away all the menial low level details?
| [
"Have a look at Camelot. http://www.python-camelot.com/\n"
] | [
1
] | [] | [] | [
"pyqt",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0003892071_pyqt_python_sql_sqlalchemy.txt |
Q:
Why is this python operation returning a tuple?
from datetime import date
from datetime import timedelta
a = date.today() - timedelta(1)
# a above is a tuple and not datetime
# Since I am a C programmer, I would expect python to cast back to datetime
# but it is casting it to a tuple
Can you please tell me why t... | Why is this python operation returning a tuple? | from datetime import date
from datetime import timedelta
a = date.today() - timedelta(1)
# a above is a tuple and not datetime
# Since I am a C programmer, I would expect python to cast back to datetime
# but it is casting it to a tuple
Can you please tell me why this is happening? and also how I can see that the ope... | [
"Perhaps the repr of a confuses you:\n>>> a\ndatetime.date(2010, 10, 8)\n\nthis is not a tuple, it's what datetime uses as repr(). Print it to get its string() representation:\n>>> print a\n2010-10-08\n\nEither str() a yourself explicitly or use a.strftime() to do you own formatting.\n",
"Having looked at your im... | [
5,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003896408_python.txt |
Q:
Is there a way to move many files quickly in Python?
I have a little script that moves files around in my photo collection, but it runs a bit slow.
I think it's because I'm doing one file move at a time. I'm guessing I can speed this up if I do all file moves from one dir to another at the same time. Is there a wa... | Is there a way to move many files quickly in Python? | I have a little script that moves files around in my photo collection, but it runs a bit slow.
I think it's because I'm doing one file move at a time. I'm guessing I can speed this up if I do all file moves from one dir to another at the same time. Is there a way to do that?
If that's not the reason for my slowness, ho... | [
"What platform are you on? And does it really have to be Python? If not, you can simply use system tools like mv (*nix) , or move (windows). \n$ stat -c \"%s\" file\n382849574\n\n$ time python -c 'import shutil;shutil.move(\"file\",\"/tmp\")'\n\nreal 0m29.698s\nuser 0m0.349s \nsys 0m1.862s \n\n$ time mv f... | [
4,
3,
2
] | [] | [] | [
"file",
"move",
"performance",
"python",
"shutil"
] | stackoverflow_0003896451_file_move_performance_python_shutil.txt |
Q:
Extract content from a file with mime multipart
I have a file that contain a tiff image and a document xml in a multipart mime document.
I would extract the image from this file.
How I can get it?
I have this code, but it requires an infinite time to extract it, if I have a big file (for example 30Mb), so this is... | Extract content from a file with mime multipart | I have a file that contain a tiff image and a document xml in a multipart mime document.
I would extract the image from this file.
How I can get it?
I have this code, but it requires an infinite time to extract it, if I have a big file (for example 30Mb), so this is unuseful.
f=open("content_file.txt","rb")
msg = emai... | [
"Solved:\ndef extract_mime_part_matching(stream, mimetype):\n\"\"\"Return the first element in a multipart MIME message on stream\nmatching mimetype.\"\"\"\n\nmsg = mimetools.Message(stream)\nmsgtype = msg.gettype()\nparams = msg.getplist()\n\ndata = StringIO.StringIO()\nif msgtype[:10] == \"multipart/\":\n\n fi... | [
4,
0
] | [] | [] | [
"mime",
"mime_types",
"python"
] | stackoverflow_0003894923_mime_mime_types_python.txt |
Q:
How to bulk insert data to mysql with python
Currently i'm using Alchemy as a ORM, and I look for a way to speed up my insert operation, I have bundle of XML files to import
for name in names:
p=Product()
p.name="xxx"
session.commit()
i use above code to insert my data paser from batch xml file to mys... | How to bulk insert data to mysql with python | Currently i'm using Alchemy as a ORM, and I look for a way to speed up my insert operation, I have bundle of XML files to import
for name in names:
p=Product()
p.name="xxx"
session.commit()
i use above code to insert my data paser from batch xml file to mysql,it's very slow
also i tried to
for name in nam... | [
"You could bypass the ORM for the insertion operation and use the SQL Expression generator instead.\nSomething like:\nconn.execute(Product.insert(), [dict(name=name) for name in names])\n\nThat should create a single statement to do your inserting.\nThat example was taken from lower down the same page.\n(I'd be int... | [
1
] | [] | [] | [
"bulkinsert",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0003874320_bulkinsert_mysql_python_sqlalchemy.txt |
Q:
Python nested loop with condition
my_list = [[1,2],[1,3],[1,3],[1,3]]
my_var = 7
My goal is to be able to see if my_var is larger than all of the positions at my_list[0][1] and my_list[1][1] and my_list[2][1] and so on.
my_list can vary in length and my_var can also vary so I am thinking a loop is the best bet?
*... | Python nested loop with condition | my_list = [[1,2],[1,3],[1,3],[1,3]]
my_var = 7
My goal is to be able to see if my_var is larger than all of the positions at my_list[0][1] and my_list[1][1] and my_list[2][1] and so on.
my_list can vary in length and my_var can also vary so I am thinking a loop is the best bet?
*very new to python
| [
"all(variable > element for element in list)\n\nor for element i of lists within a list\nall(variable > sublist[i] for sublist in list)\n\nThis has the advantage of kicking out early if any of the elements is too large. This works because the ... for ... in list is an instance of Python's powerful and multifarious... | [
4,
1
] | [] | [] | [
"conditional_statements",
"list",
"loops",
"python"
] | stackoverflow_0003895713_conditional_statements_list_loops_python.txt |
Q:
How do I extract certain digits from raw input in Python?
Let's say I ask a users for some random letters and numbers. let's say they gave me 1254jf4h. How would I take the letters jfh and convert them inter a separate variable and then take the numbers 12544 and make them in a separate variable?
A:
>>> s="1254j... | How do I extract certain digits from raw input in Python? | Let's say I ask a users for some random letters and numbers. let's say they gave me 1254jf4h. How would I take the letters jfh and convert them inter a separate variable and then take the numbers 12544 and make them in a separate variable?
| [
">>> s=\"1254jf4h\"\n>>> num=[]\n>>> alpah=[]\n>>> for n,i in enumerate(s):\n... if i.isdigit():\n... num.append(i)\n... else:\n... alpah.append(i)\n...\n>>> alpah\n['j', 'f', 'h']\n>>> num\n['1', '2', '5', '4', '4']\n\n",
"A for loop is simple enough. Personally, I would use filter().\ns = \"1254jf... | [
2,
2,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003896368_python_regex_string.txt |
Q:
Python - Fastest way to find the average value over entire dict each time it gets modified?
I'm trying to find the fastest/most efficient way to extract the average value from a dict. The task I'm working on requires that it do this thousands of times, so simply iterating over all the values in the dict each time ... | Python - Fastest way to find the average value over entire dict each time it gets modified? | I'm trying to find the fastest/most efficient way to extract the average value from a dict. The task I'm working on requires that it do this thousands of times, so simply iterating over all the values in the dict each time to find the average would be entirely inefficient. Hundreds and hundreds of new key,value pairs g... | [
"Create your own dict subclass that tracks the count and total, and then can quickly return the average:\nclass AvgDict(dict):\n def __init__(self):\n self._total = 0.0\n self._count = 0\n\n def __setitem__(self, k, v):\n if k in self:\n self._total -= self[k]\n self... | [
11,
2,
1
] | [] | [] | [
"average",
"dictionary",
"iteration",
"python"
] | stackoverflow_0003897040_average_dictionary_iteration_python.txt |
Q:
GUI development package
I am new to GUI development. What is the best GUI development package for python on linux (ubuntu being more specific)?
A:
There are numerous decent GUI toolkits, the most popular being PyQt, PyGTK, wxPython and Tkinter. Personally, I prefer Qt, but that's really subjective.
A:
This is ... | GUI development package | I am new to GUI development. What is the best GUI development package for python on linux (ubuntu being more specific)?
| [
"There are numerous decent GUI toolkits, the most popular being PyQt, PyGTK, wxPython and Tkinter. Personally, I prefer Qt, but that's really subjective.\n",
"This is much more a matter of personal taste.\nI use GTK+ with Glade.\n"
] | [
3,
1
] | [] | [] | [
"linux",
"python",
"user_interface"
] | stackoverflow_0003897101_linux_python_user_interface.txt |
Q:
Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc
Hey there, I love regular expressions, but I'm just not good at them at all.
I have a list of some 400 shortened words such as lol, omg, lmao...etc. Whenever someone types one of these shortened words, it is replaced with its English counterpart ([laught... | Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc | Hey there, I love regular expressions, but I'm just not good at them at all.
I have a list of some 400 shortened words such as lol, omg, lmao...etc. Whenever someone types one of these shortened words, it is replaced with its English counterpart ([laughter], or something to that effect). Anyway, people are annoying a... | [
"FIRST APPROACH -\nWell, using regular expression(s) you could do like so - \nimport re\nre.sub('g+', 'g', 'omgggg')\nre.sub('l+', 'l', 'lollll')\n\netc.\nLet me point out that using regular expressions is a very fragile & basic approach to dealing with this problem. You could so easily get strings from users which... | [
7,
4
] | [] | [] | [
"python",
"regex",
"string_matching"
] | stackoverflow_0003895874_python_regex_string_matching.txt |
Q:
Python threads and global vars
Say I have the following function in a module called "firstModule.py":
def calculate():
# addCount value here should be used from the mainModule
a=random.randint(0,5) + addCount
Now I have a different module called "secondModule.py":
def calculate():
# addCount value here too... | Python threads and global vars | Say I have the following function in a module called "firstModule.py":
def calculate():
# addCount value here should be used from the mainModule
a=random.randint(0,5) + addCount
Now I have a different module called "secondModule.py":
def calculate():
# addCount value here too should be used from the mainModule
... | [
"Pass 'addCount' to the function 'calculate', return the value of 'a' in 'calculate', and assign it to a new attribute in MyThread instance.\ndef calculate(addCount):\n a = random.randint(0, 5) + addCount\n return a\n\n",
"Modules in python are singletons, so you can put your global variables in module glob... | [
4,
2
] | [] | [] | [
"global_variables",
"multithreading",
"python"
] | stackoverflow_0003896210_global_variables_multithreading_python.txt |
Q:
How to get windows user id in web2py for an intranet application?
I'm using web2py for an intranet site and need to get current login windows user id in my controller. Whether any function is available?
A:
You need to install an NTLM authentication module on your web server such as mod_sspi or mod_ntlm then chec... | How to get windows user id in web2py for an intranet application? | I'm using web2py for an intranet site and need to get current login windows user id in my controller. Whether any function is available?
| [
"You need to install an NTLM authentication module on your web server such as mod_sspi or mod_ntlm then check the REMOTE_USER environment variable of the request. Here is something similar in Django:\nhttp://brandonkonkle.com/blog/2008/sep/13/django-apache-and-mod_auth_sspi/\n",
"If you mean you need code at the ... | [
4,
1
] | [
"I don't know if that works but try psutil module, which is supposed to work on both Windows and Unix.\nimport os, psutil\n\nownPid = os.getpid() #This one works in Windows, but os.getuid() does not...\nownUid = [p.uid for p in psutil.process_iter() \n if p.pid == ownPid][0]\n\n"
] | [
-1
] | [
"python",
"web2py",
"windows"
] | stackoverflow_0003798606_python_web2py_windows.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.