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:
Upgrade to Python 2.6.5 on mac
I'd like to upgrade to Python 2.6.5 on Mac.
I've seen this question on how to upgrade to 2.6 using macports, but it only talks about how to get 2.6 - I need 2.6.5 specifically, I currently have 2.6.1 installed.
Please could someone advise?
Thanks!
A:
There's no reason to use the ma... | Upgrade to Python 2.6.5 on mac | I'd like to upgrade to Python 2.6.5 on Mac.
I've seen this question on how to upgrade to 2.6 using macports, but it only talks about how to get 2.6 - I need 2.6.5 specifically, I currently have 2.6.1 installed.
Please could someone advise?
Thanks!
| [
"There's no reason to use the macports version -- just use the official framework build from http://www.python.org/download/releases/2.6.5/\n(Note that there's a 2.6.6 version now.)\n",
"port install python26 @2.6.5\n"
] | [
1,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0004517455_macos_python.txt |
Q:
Print statements on server give IOError: failed to write data
I am running Pylons on my local machine with paster, and on a Debian server using WSGI. I want to add some print statements to debug a problem: am not a Pylons or Python expert.
On my local machine this works fine: print statements go to the terminal. O... | Print statements on server give IOError: failed to write data | I am running Pylons on my local machine with paster, and on a Debian server using WSGI. I want to add some print statements to debug a problem: am not a Pylons or Python expert.
On my local machine this works fine: print statements go to the terminal. On the server, the statements don't print to the log files: instead ... | [
"It's wrong for a WSGI application to use sys.stdout or sys.stderr. If you want to spit debug to a server error log, use environ['wsgi.errors'].write().\n",
"Don't use print statements, use the logging module. We can't help you without knowing the setup of the server.\n"
] | [
3,
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0004517397_pylons_python.txt |
Q:
Python 2.4: Speed of imports in normal script vs imports in execfile'd script
I've just stumbled across something that makes no sense to me. Where I work, we have a number of Python CGI webpages (just a simple Apache server setup, not running Django / Turbogears or the like) and I've been getting a bit frustrated ... | Python 2.4: Speed of imports in normal script vs imports in execfile'd script | I've just stumbled across something that makes no sense to me. Where I work, we have a number of Python CGI webpages (just a simple Apache server setup, not running Django / Turbogears or the like) and I've been getting a bit frustrated with how long it takes the scripts to run. I chucked lots of time.time() calls and ... | [
"My guess is that there is no real difference. It only looks like a big difference. Try and test it like this to be sure:\n# time python test.py\n0.0514879226685\npython test.py 0.06s user 0.01s system 95% cpu 0.071 total\n\n# time python -c 'execfile\n0.0515019893646\npython -c 'execfile(\"test.py\")' 0.06s user... | [
0
] | [] | [] | [
"execfile",
"import",
"python",
"sqlalchemy"
] | stackoverflow_0004517797_execfile_import_python_sqlalchemy.txt |
Q:
python setup.py install changes script interpreter
I have a Python package that includes a few scripts in a scripts/ folder. My setup.py file includes::
#!/usr/bin/env python
from distutils.core import setup
scripts = ['script1', 'script2', 'script3']
setup(name='Test',
version='0.1.0',
packages=['t... | python setup.py install changes script interpreter | I have a Python package that includes a few scripts in a scripts/ folder. My setup.py file includes::
#!/usr/bin/env python
from distutils.core import setup
scripts = ['script1', 'script2', 'script3']
setup(name='Test',
version='0.1.0',
packages=['test'],
scripts=['scripts/' + x for x in scripts]
... | [
"The install scripts checks, where the python is installed and changes this python to the proper one. It does it on every machine, where your package is installed.\nFrom docs:\n\nScripts are files containing Python\n source code, intended to be started\n from the command line. Scripts don’t\n require Distutils ... | [
4
] | [] | [] | [
"installation",
"path",
"python",
"virtualenv"
] | stackoverflow_0004517934_installation_path_python_virtualenv.txt |
Q:
Storing Templates and Object-Oriented vs Relational Databases
I'm designing some custom blog software, and have run into a conundrum regarding database design. The software requires that there be multiple content types, each of which will require different entry forms and presentation templates.
My initial instin... | Storing Templates and Object-Oriented vs Relational Databases | I'm designing some custom blog software, and have run into a conundrum regarding database design. The software requires that there be multiple content types, each of which will require different entry forms and presentation templates.
My initial instinct is to create these content types as objects, then serialize them... | [
"Please do Not Store templates (that might be altered by a user) in a database. There's no sane way to migrate from a staging environment to production if you have to deal with doffs of database dumps. We are dumping some software right one for this very reason.\nApart from that I'd simply store the source (user ed... | [
2,
0
] | [] | [] | [
"database_design",
"object_oriented_database",
"python",
"relational_database"
] | stackoverflow_0004503301_database_design_object_oriented_database_python_relational_database.txt |
Q:
Is there any way to program hover over behavior for files shown in windows explorer?
I want to pop up my own label when mouse hovers over a directory/file in windows explorer. How to do this?
A:
This is done by creating a Shell Extension of the Infotip handler variety.
These two URLs will help you, at least if y... | Is there any way to program hover over behavior for files shown in windows explorer? | I want to pop up my own label when mouse hovers over a directory/file in windows explorer. How to do this?
| [
"This is done by creating a Shell Extension of the Infotip handler variety.\nThese two URLs will help you, at least if you can map the Win32 C++ stuff to Python. (Sorry, I don't know much about Python to know how easy that part is.)\n\nMSDN: Creating Shell Extension Handlers\nCodeProject: The Complete Idiot's Guide... | [
0
] | [] | [] | [
"python",
"user_interface",
"winapi"
] | stackoverflow_0004517898_python_user_interface_winapi.txt |
Q:
can i get date of friendship in twitter?
is there a way to get the date of friendship creation for both my friends and followers in twitter?
especially for python-twitter....
A:
Twitter doesn't preserve the date a friendship or follow is created, and it doesn't return it in the API. Going forward you can query ... | can i get date of friendship in twitter? | is there a way to get the date of friendship creation for both my friends and followers in twitter?
especially for python-twitter....
| [
"Twitter doesn't preserve the date a friendship or follow is created, and it doesn't return it in the API. Going forward you can query friends/ids and followers/id every day and record any new relationships with the current date in a database. \n"
] | [
3
] | [] | [] | [
"python",
"python_twitter",
"twitter"
] | stackoverflow_0004517265_python_python_twitter_twitter.txt |
Q:
How can I capture the return value of shutil.copy() in Python ( on DOS )?
I am trying to record the success or failure of a number of copy commands, into a log file. I'm using shutil.copy() - e.g.
str_list.append(getbitmapsfrom)
game.bigbitmap = "i doubt this is there.bmp"
str_list.append(game.bigbitmap)
source =... | How can I capture the return value of shutil.copy() in Python ( on DOS )? | I am trying to record the success or failure of a number of copy commands, into a log file. I'm using shutil.copy() - e.g.
str_list.append(getbitmapsfrom)
game.bigbitmap = "i doubt this is there.bmp"
str_list.append(game.bigbitmap)
source = '\\'.join(str_list)
shutil.copy(source, newbigbmpname)
I forced one of the co... | [
"You'll want to look at the exceptions section of the Python tutorial. In the case of shutil.copy() not finding one of the arguments, an IOError exception will be raised. You can get the message from the exception instance.\ntry:\n shutil.copy(src, dest)\nexcept IOError, e:\n print \"Unable to copy file. %s... | [
20,
4,
2
] | [] | [] | [
"exception",
"logging",
"python"
] | stackoverflow_0001662261_exception_logging_python.txt |
Q:
How to raise exception if None value encountered in dict?
I want to raise a KeyError exception if the value returned is None, but the following throws a SyntaxError: invalid syntax exception.
try:
protocol = serverInfo_D['protocol'] or raise KeyError("protocol not present")
except KeyError:
print "Improper s... | How to raise exception if None value encountered in dict? | I want to raise a KeyError exception if the value returned is None, but the following throws a SyntaxError: invalid syntax exception.
try:
protocol = serverInfo_D['protocol'] or raise KeyError("protocol not present")
except KeyError:
print "Improper server config"
What's a simple way to get this working?
| [
"You're getting a SyntaxError because raise is a statement not an expression, so the or raise KeyError part doesn't make [syntactic] sense. One workaround is to put just that into a function like the following, which is only called if the looked-up value is something non-True, like None, 0, '', and []. \nCaveat: No... | [
10,
7,
2,
2,
0
] | [] | [] | [
"python",
"python_2.x"
] | stackoverflow_0004517411_python_python_2.x.txt |
Q:
Python data transfer
I want develop a system where I can transfer some images and after run some algorithms on cluster.
My cluster job submitter should be able to connect for more than one user.
I read a little about paramiko but is necessary a ssh user and I don't want use it.
Other specifications, my client will... | Python data transfer | I want develop a system where I can transfer some images and after run some algorithms on cluster.
My cluster job submitter should be able to connect for more than one user.
I read a little about paramiko but is necessary a ssh user and I don't want use it.
Other specifications, my client will send and receive the imag... | [
"Any of the following packages would probably do what you want\n\nCelery http://pypi.python.org/pypi/celery/2.1.4\nParallel Python http://pypi.python.org/pypi/pp/1.6.0\nAsynQueue http://pypi.python.org/pypi/AsynQueue/0.3\nPyro http://pypi.python.org/pypi/Pyro4/4.2\n\n"
] | [
2
] | [] | [] | [
"cluster_computing",
"networking",
"python",
"sockets"
] | stackoverflow_0004519270_cluster_computing_networking_python_sockets.txt |
Q:
Implementing a custom string method
How do you add a custom method to a built-in python datatype? For example, I'd like to implement one of the solutions from this question but be able to call it as follows:
>>> s = "A string with extra whitespace"
>>> print s.strip_inner()
>>> A string with extra whitespace... | Implementing a custom string method | How do you add a custom method to a built-in python datatype? For example, I'd like to implement one of the solutions from this question but be able to call it as follows:
>>> s = "A string with extra whitespace"
>>> print s.strip_inner()
>>> A string with extra whitespace
So how would I define a custom .strip_i... | [
"You can't. And you don't need to.\nSee Extending builtin classes in python for an alternative solution. Subclassing is the way to go here.\n",
"The built-in classes such as str are implemented in C, so you can't manipulate them. What you can do, instead, is extend the str class:\n>>> class my_str(str):\n... ... | [
6,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004519702_python.txt |
Q:
How do I change 'example.com' in my code?
I built a a.py in my mysite file,
a.py:
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
from django.contrib.sites.models import Site
domain = Site.objects.get_current().domain
print domain
It prints:
:example.com
Ho... | How do I change 'example.com' in my code? | I built a a.py in my mysite file,
a.py:
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
from django.contrib.sites.models import Site
domain = Site.objects.get_current().domain
print domain
It prints:
:example.com
How do I change the 'domain' to 127.0.0.1:8000?
... | [
"Go to the Site model in the admin interface and change the value there. Or do a query on Site at the Django prompt and modify and save the model.\n",
"Put a file call initial_data.json in your project directory with the following content :\n[{\n \"pk\": 1,\n \"model\": \"sites.site\",\n \"fi... | [
8,
4,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002107456_django_python.txt |
Q:
How to run a standalone application from the current one?
I've got an GUI application written in python.
After GUI starts it should run standalone daemon. But if I close GUI or it crashes, daemon quits too. Is there a way to run one application from another independently?
A:
Under Linux, I've handled this by hav... | How to run a standalone application from the current one? | I've got an GUI application written in python.
After GUI starts it should run standalone daemon. But if I close GUI or it crashes, daemon quits too. Is there a way to run one application from another independently?
| [
"Under Linux, I've handled this by having my parent process (in your case the GUI), launch the second python process via subprocess or os.system. The 2nd process immediately daemonizes itself. To do that see here or here.\n",
"While I don't start a daemon, I have a pygtk program which starts another program usi... | [
2,
1
] | [] | [] | [
"process",
"python"
] | stackoverflow_0004519736_process_python.txt |
Q:
web2py: How do I add javascript to Web2py Crud form?
Working with Web2Py. I'm trying to attach some javascript either to a field (onchange) or to the form (onsubmit), but I see absolutely no way to pass such argument to crud.create or to form.custom.widget.
Anyone has an idea?
A:
Of course there is a way. The ap... | web2py: How do I add javascript to Web2py Crud form? | Working with Web2Py. I'm trying to attach some javascript either to a field (onchange) or to the form (onsubmit), but I see absolutely no way to pass such argument to crud.create or to form.custom.widget.
Anyone has an idea?
| [
"Of course there is a way. The appropriate way is to ask people on the web2py mailing list who know how to, as opposed to generic stack overflow users who will guess an incorrect answer. :-)\nAnyway, assume you have:\ndb.define_table('image',\n Field('name'),\n Field('file', 'upload'))\n\nYou can do\ndef uplo... | [
4,
0
] | [] | [] | [
"crud",
"javascript",
"python",
"web2py"
] | stackoverflow_0004517691_crud_javascript_python_web2py.txt |
Q:
Differences between Python game libraries Pygame and Pyglet?
I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.
How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?
Finally, would you say that... | Differences between Python game libraries Pygame and Pyglet? | I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.
How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?
Finally, would you say that one is more Pythonic than the other?
| [
"I was considering both Pygame and Pyglet for a small 2D shooter, and after looking at source code and some tutorials went with Pyglet. I was very happy with the results.\nPyglet worked immediately and was enjoyable to work with, and conceptually very clean. It certainly had a Pythonic feel to me: you could get a s... | [
32,
31,
16,
5,
4
] | [] | [] | [
"pygame",
"pyglet",
"python"
] | stackoverflow_0000370680_pygame_pyglet_python.txt |
Q:
Where should settings files be stored?
I'm writing an application in python (using wxPython for the gui) and I'm looking for a platform independent way to decide where to store application settings files. On linux systems, where is it customary to store application settings files? How about on Mac, and Windows (... | Where should settings files be stored? | I'm writing an application in python (using wxPython for the gui) and I'm looking for a platform independent way to decide where to store application settings files. On linux systems, where is it customary to store application settings files? How about on Mac, and Windows (all modern versions)?
Ideally I'd like t... | [
"wxPython has your back. You want wx.StandardPaths. There's a good example included with the wxPython demo.\n",
"There is a standard for this by freedesktop.org that you may find useful:\nhttp://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html\n",
"On linux, there's really not a standard way. A l... | [
6,
3,
0
] | [] | [] | [
"application_settings",
"python",
"wxpython"
] | stackoverflow_0004516459_application_settings_python_wxpython.txt |
Q:
Modify subclassed string in place
I've got the following string subclass:
class S(str):
def conc(self, next_val, delimiter = ' '):
"""Concatenate values to an existing string"""
if not next_val is None:
self = self + delimiter + next_val
return self
I expect this to work as... | Modify subclassed string in place | I've got the following string subclass:
class S(str):
def conc(self, next_val, delimiter = ' '):
"""Concatenate values to an existing string"""
if not next_val is None:
self = self + delimiter + next_val
return self
I expect this to work as follows:
>>> x = S("My")
>>> x.conc("n... | [
"You can't do what you're asking, because strings are immutable. The docs tell you to wrap the str class; that is, to make a class with an attribute which is the current value of the \"mutable string\". This exists in the standard library of Python 2.x as UserString.MutableString (but is gone in Python 3); it's pre... | [
4,
3,
1,
0,
0
] | [] | [] | [
"python",
"subclassing"
] | stackoverflow_0004520298_python_subclassing.txt |
Q:
Assigning Multiple Cores to a Python Program
I notice when I run my heavily CPU dependant python programs, it only uses a single core. Is it possible to assign multiple cores to the program when I run it?
A:
You have to program explicitly for multiple cores. See the Symmetric Multiprocessing options on this page... | Assigning Multiple Cores to a Python Program | I notice when I run my heavily CPU dependant python programs, it only uses a single core. Is it possible to assign multiple cores to the program when I run it?
| [
"You have to program explicitly for multiple cores. See the Symmetric Multiprocessing options on this page for the many parallel processing solutions in Python. Parallel Python is a good choice if you can't be bothered to compare the options, look at the examples here.\nSome problems can't take advantage of multipl... | [
16,
5,
4
] | [] | [] | [
"cpu_cores",
"parallel_processing",
"python"
] | stackoverflow_0004519951_cpu_cores_parallel_processing_python.txt |
Q:
pyGTK/GTK filechooser - Is it possible to validate user entry before file or folder is written to disc?
I would like to validate the users choice of folder name in a gtk.FileChooser dialogue when creating a new folder.
I tried connecting to the dialogue 'response' signal, but it is already too late, the new folder... | pyGTK/GTK filechooser - Is it possible to validate user entry before file or folder is written to disc? | I would like to validate the users choice of folder name in a gtk.FileChooser dialogue when creating a new folder.
I tried connecting to the dialogue 'response' signal, but it is already too late, the new folder will be written to disc.
Is there a way to achieve this other then validate the folder after it is written t... | [
"I can see a couple ways of doing this. \nOne, simply write your own response id handler instead of using gtk.RESPONSE_OK (which to the widget means create the folder). If you do it this way you'll be responsible for actually creating the folder after validation (os.path.mkdir). \nTwo, you could override the cli... | [
3
] | [] | [] | [
"filechooser",
"gtk",
"pygtk",
"python"
] | stackoverflow_0004515916_filechooser_gtk_pygtk_python.txt |
Q:
How can I load the parent directory of a script as a module, without adding all of the siblings of that directory's parent directory to my sys.path?
I'm hoping there's an easy answer to this question that I'm simply overlooking.
Here's the setup:
foo/
__init__.py
run.py
Contents of run.py:
import foo
Run... | How can I load the parent directory of a script as a module, without adding all of the siblings of that directory's parent directory to my sys.path? | I'm hoping there's an easy answer to this question that I'm simply overlooking.
Here's the setup:
foo/
__init__.py
run.py
Contents of run.py:
import foo
Run the script:
$ python run.py
Traceback (most recent call last):
File "run.py", line 1, in <module>
import foo
ImportError: No module named foo
The... | [
"I don't quite see why run is meant to import its own parent package. After all, a package is just meant to be a way of collecting modules together; it's not meant to have significant functionality of its own.\n\nPackages are a way of structuring\n Python’s module namespace by using\n “dotted module names”. For e... | [
0
] | [] | [] | [
"python",
"sys.path"
] | stackoverflow_0004520433_python_sys.path.txt |
Q:
Two Foreign keys for an Inline form in the admin in Django
I want to have 2 Foreign Keys for an Inline form in the admin.
I have a Timesheet model with the following fields:
class Timesheet(models.Model):
date = models.ForeignKey(DateTimesheet, related_name="day")
supervisor = models.ForeignKey(DateTimeshe... | Two Foreign keys for an Inline form in the admin in Django | I want to have 2 Foreign Keys for an Inline form in the admin.
I have a Timesheet model with the following fields:
class Timesheet(models.Model):
date = models.ForeignKey(DateTimesheet, related_name="day")
supervisor = models.ForeignKey(DateTimesheet, related_name="superintendent")
job = models.ForeignKey(J... | [
"If Timesheet is the parent model and DateTimesheet the inline (or vice-versa), there is no need for composite keys, just:\n\nmake the supervisor in both Models a ForeignKey(User)\nommit the supervisor field in the inline form \nset it to the vaule of parent model field when saving by overriding the save_formset me... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004520219_django_python.txt |
Q:
How to set up Python interpreter in Emacs on OS X?
I have emacs and python working on OSX, but I'd like to get a python interpreter working in a split window so I can view output as I code. Is this possible?
thanks
A:
While in python-mode, hit C-c ! or do an M-x py-shell RET. Should work with defaults.
| How to set up Python interpreter in Emacs on OS X? | I have emacs and python working on OSX, but I'd like to get a python interpreter working in a split window so I can view output as I code. Is this possible?
thanks
| [
"While in python-mode, hit C-c ! or do an M-x py-shell RET. Should work with defaults. \n"
] | [
5
] | [] | [] | [
"emacs",
"osx_leopard",
"python"
] | stackoverflow_0004520851_emacs_osx_leopard_python.txt |
Q:
using pyxml library pyjamas
I need to write a small web app that does xml parsing on the client browser
I am considering pyjamas as the front end framework and django for the backend.
I understand that with pyjamas one can code in python and javascript is automatically generated
my question is: can I use external ... | using pyxml library pyjamas | I need to write a small web app that does xml parsing on the client browser
I am considering pyjamas as the front end framework and django for the backend.
I understand that with pyjamas one can code in python and javascript is automatically generated
my question is: can I use external python libraries such as pyxml to... | [
"No. See 'supported modules' in the Pyjamas docs.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004521124_django_python.txt |
Q:
Java int to python int
I have a Java server that will accept a connection from a python socket and return an int of the new port that they python script should connect to. However the 'string" that the python script gets back is blatantly unable to be converted.
Here's the python snippet:
s._PORT = int(s._sock.rec... | Java int to python int | I have a Java server that will accept a connection from a python socket and return an int of the new port that they python script should connect to. However the 'string" that the python script gets back is blatantly unable to be converted.
Here's the python snippet:
s._PORT = int(s._sock.recv(1024))
print s._PORT
And ... | [
"sock.getOutPutStream().write(Integer.toString(mPort))\n\ns._PORT = int(s._sock.recv(1024))\n\n"
] | [
2
] | [] | [] | [
"java",
"primitive",
"python",
"sockets"
] | stackoverflow_0004521265_java_primitive_python_sockets.txt |
Q:
Why is Python not fully object-oriented?
I want to know why Python is not fully object-oriented. For example, it does not support private, public, protected access level modifiers.
What are the advantages and disadvantages of this? By these expressions, Python is suitable for what applications (Desktop, Scientific... | Why is Python not fully object-oriented? | I want to know why Python is not fully object-oriented. For example, it does not support private, public, protected access level modifiers.
What are the advantages and disadvantages of this? By these expressions, Python is suitable for what applications (Desktop, Scientific, Web or other)?
| [
"Python doesn't support strong encapsulation, which is only one of many features associated with the term \"object-oriented\".\nThe answer is simply philosophy. Guido doesn't like hiding things, and many in the Python community agree with him.\n",
"Guido once said that \"we are all consenting adults here\". Here'... | [
102,
48,
14,
4,
2,
2
] | [
"A language is said to Full Objective Oriented if it has no primitive data types. Each data type we need to construct.\n"
] | [
-5
] | [
"oop",
"python"
] | stackoverflow_0003325343_oop_python.txt |
Q:
How to get RMSE from scipy.optimize.leastsq module
Can I get the vaule of RMSE from scipy.optimize.leastsq module ?
A:
Here's a little example using leastsq:
import numpy as np
import scipy.optimize as optimize
import collections
x = np.array([821,576,473,377,326,300])
y = np.array([255,235,208,166,157,140])
d... | How to get RMSE from scipy.optimize.leastsq module | Can I get the vaule of RMSE from scipy.optimize.leastsq module ?
| [
"Here's a little example using leastsq:\nimport numpy as np\nimport scipy.optimize as optimize\nimport collections\n\nx = np.array([821,576,473,377,326,300])\ny = np.array([255,235,208,166,157,140])\n\ndef sigmoid(p,x):\n x0,y0,c,k=p\n y = c / (1 + np.exp(-k*(x-x0))) + y0\n return y\n\ndef residuals(p,x,y)... | [
5
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0004520785_numpy_python_scipy.txt |
Q:
wxPython Whole Window Focus Event
With wxPython, how does one trigger an event whenever the whole window goes into/out of focus?
To elaborate, I'm building a serial terminal GUI and would like to close down the connection whenever the user doesn't have my application selected, and re-open the connection whenever... | wxPython Whole Window Focus Event | With wxPython, how does one trigger an event whenever the whole window goes into/out of focus?
To elaborate, I'm building a serial terminal GUI and would like to close down the connection whenever the user doesn't have my application selected, and re-open the connection whenever the user brings my app back into the f... | [
"The correct answer for this case is to use an EVT_ACTIVATE handler bound to the frame. There will be an event whenever the frame is activated (brought into the foreground relative to other windows currently open) or deactivated. You can use the event object's GetActive method to tell which just happened.\n",
"... | [
5,
2,
2,
2
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0004505097_python_wxpython_wxwidgets.txt |
Q:
Serializing python object to python source code
I have a python dictionary that I'd like to serialize into python source code required to initialize that dictionary's keys and values.
I'm looking for something like json.dumps(), but the output format should be Python not JSON.
My object is very simple: it's a di... | Serializing python object to python source code | I have a python dictionary that I'd like to serialize into python source code required to initialize that dictionary's keys and values.
I'm looking for something like json.dumps(), but the output format should be Python not JSON.
My object is very simple: it's a dictionary whose values are one of the following:
bu... | [
"In the most general case, it's not possible to dump an arbitrary Python object into Python source code. E.g. if the object is a socket, recreating the very same socket in a new object cannot work.\nAs aix explains, for the simple case, repr is explicitly designed to make reproducable source representations. As a s... | [
3,
2,
0
] | [] | [] | [
"code_generation",
"json",
"python",
"serialization"
] | stackoverflow_0004521798_code_generation_json_python_serialization.txt |
Q:
How do I change the choices in a Django model?
I have a Django model that uses the choices attribute.
COLOR_CHOICES = (
('R', 'Red'),
('B', 'Blue'),
)
class Toy(models.Model):
color = models.CharField(max_length=1, choices=COLOR_CHOICES)
My code is in production and now I'd like to add additional choi... | How do I change the choices in a Django model? | I have a Django model that uses the choices attribute.
COLOR_CHOICES = (
('R', 'Red'),
('B', 'Blue'),
)
class Toy(models.Model):
color = models.CharField(max_length=1, choices=COLOR_CHOICES)
My code is in production and now I'd like to add additional choices.
COLOR_CHOICES = (
('R', 'Red'),
... | [
"Django doesn't enforce choices on a database level, it only uses them for the presentation of the widgets and in validation. If you want them a bit more 'dynamic', for example to have different ones on different servers you could define them via settings.py:\nfrom django.conf import settings\n\nCOLOR_CHOICES = get... | [
13,
1
] | [] | [] | [
"django",
"django_models",
"django_south",
"migration",
"python"
] | stackoverflow_0004521821_django_django_models_django_south_migration_python.txt |
Q:
LCARS GUI where to start
Hey so I'm looking to build a star trek GUI (LCARS). To do this, essentially I need to be able to create images (PNGs) and have them act as a button - I would have a "shade" method/function for events such as mouseOver clicked...etc.
What toolkit? or GTK/wxPython would be easiest for this?... | LCARS GUI where to start | Hey so I'm looking to build a star trek GUI (LCARS). To do this, essentially I need to be able to create images (PNGs) and have them act as a button - I would have a "shade" method/function for events such as mouseOver clicked...etc.
What toolkit? or GTK/wxPython would be easiest for this? I would prefer to have a buil... | [
"You could use wxPython's BitmapButton. You can provide images for focused, disabled, selected, and mouse hover states. There are also fancy button controls that are documented in the wxPython demo.\n"
] | [
0
] | [] | [] | [
"gtk",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0004522559_gtk_python_user_interface_wxpython.txt |
Q:
Does any webhosting service that supports python also supports django?
I'm trying to learn python/django, these are installed on my desktop computer and all the examples run fine. My question is: If a webhosting service supports python (2.4), does the webhosting service supports django by default?
Thanks guys.
A... | Does any webhosting service that supports python also supports django? | I'm trying to learn python/django, these are installed on my desktop computer and all the examples run fine. My question is: If a webhosting service supports python (2.4), does the webhosting service supports django by default?
Thanks guys.
| [
"You can use Google App Engine, which is free and includes Django.\n",
"Yes, but if they only support Python via CGI then your application will be very, very slow. Best is WSGI, then FastCGI, then mod_python.\n",
"Not necessarily.Many web hosting companies(shared) claim to offer django but this is a big lie.Cas... | [
2,
1,
0,
0
] | [] | [] | [
"django",
"python",
"web_hosting"
] | stackoverflow_0004521460_django_python_web_hosting.txt |
Q:
Python/Django is importing the wrong module (relative when it should be absolute)
I'm using Django 1.2 pre-alpha and Python 2.4. Yeah, I know, but I'm stuck with it. We can't upgrade at the moment and I doubt that's the answer anyway.
I've got two template tag libraries, foo and bar. However, foo is also the name ... | Python/Django is importing the wrong module (relative when it should be absolute) | I'm using Django 1.2 pre-alpha and Python 2.4. Yeah, I know, but I'm stuck with it. We can't upgrade at the moment and I doubt that's the answer anyway.
I've got two template tag libraries, foo and bar. However, foo is also the name of a top-level package, and it happens to be the package of bar:
foo-1.2.3/
foo/
... | [
"After a few more hours of hacking, this did the trick.\nOriginal code:\nfrom foo.conf import settings\n\nNew code:\nfoo = __import__('foo')\nconf = __import__('foo.conf').conf\nsettings = __import__('foo.conf.settings').conf.settings\n\n(I probably don't need the second line.)\nEwww.\n"
] | [
1
] | [] | [] | [
"django",
"django_templates",
"python",
"python_import"
] | stackoverflow_0004521416_django_django_templates_python_python_import.txt |
Q:
Is there a high-level profiling module for Python?
I want to profile my Python code. I am well-aware of cProfile, and I use it, but it's too low-level. (For example, there isn't even a straightforward way to catch the return value from the function you're profiling.)
One of the things I would like to do: I want to... | Is there a high-level profiling module for Python? | I want to profile my Python code. I am well-aware of cProfile, and I use it, but it's too low-level. (For example, there isn't even a straightforward way to catch the return value from the function you're profiling.)
One of the things I would like to do: I want to take a function in my program and set it to be profiled... | [
"It may be a little mind-bending, but this technique should help you find the \"bottlenecks\", it that's what you want to do.\nYou're pretty sure of what routine you want to focus on.\nIf that's the routine you need to focus on, it will prove you right.\nIf the real problem(s) are somewhere else, it will show you w... | [
1,
0
] | [] | [] | [
"cprofile",
"introspection",
"profiling",
"python"
] | stackoverflow_0003773909_cprofile_introspection_profiling_python.txt |
Q:
python library to compare a .wav with mic input?
I need a python library or module or whatever that can compare a .wav file to microphone input without too too much code. Sample code would be cool too. TY!
A:
I don't know if there's a library already for that, but if you have the microphone input as a WAV file a... | python library to compare a .wav with mic input? | I need a python library or module or whatever that can compare a .wav file to microphone input without too too much code. Sample code would be cool too. TY!
| [
"I don't know if there's a library already for that, but if you have the microphone input as a WAV file as well, you can use the wave and audioop modules and write it yourself.\n",
"If you're trying to compare something like, what words people are saying, this would have to be a fairly complex piece of code. You ... | [
0,
0
] | [] | [] | [
"audio",
"comparison",
"python",
"wav"
] | stackoverflow_0004522964_audio_comparison_python_wav.txt |
Q:
Populating namespace within a module before loading it
I designed a configuration mechanism in Python, where certain objects can operate in special ways to define problems in our domain.
The user specifies the problem by using this objects in a "config-file" manner. For instance:
# run configuration
CASES = [
('C... | Populating namespace within a module before loading it | I designed a configuration mechanism in Python, where certain objects can operate in special ways to define problems in our domain.
The user specifies the problem by using this objects in a "config-file" manner. For instance:
# run configuration
CASES = [
('Case 1', Item('item1') + Item('item2') + Item('item3')),
('C... | [
"From the eval help:\n>>> help(eval)\nHelp on built-in function eval in module __builtin__:\n\neval(...)\n eval(source[, globals[, locals]]) -> value\n\n Evaluate the source in the context of globals and locals.\n The source may be a string representing a Python expression\n or a code object as returned... | [
1,
0
] | [] | [] | [
"import",
"namespaces",
"python"
] | stackoverflow_0004522869_import_namespaces_python.txt |
Q:
Modifying a global variable inside a function
I have defined the following function:
def GMM(s1, s2, s3, s4, s5, a):
"""The GMM objective function.
Arguments
---------
si: float
standard deviations of preference distribution
a: float
marginal utility of residut... | Modifying a global variable inside a function | I have defined the following function:
def GMM(s1, s2, s3, s4, s5, a):
"""The GMM objective function.
Arguments
---------
si: float
standard deviations of preference distribution
a: float
marginal utility of residutal income
Paramters
---------
Px: ... | [
"There are multiple ways to achieve what you want. delta is saved across function calls in the following examples.\n1- Class\nclass Example:\n def __init__(self, value):\n self.delta = value\n def gmm(self):\n self.delta += 1\n return self.delta\n\ne = Example(0)\nprint e.gmm()\n\n2- Generator\ndef gmm()... | [
25,
13,
4
] | [] | [] | [
"python"
] | stackoverflow_0004522786_python.txt |
Q:
Splice arrays in NumPy?
I'd like to perform a splice of sorts in NumPy. Let's say I have two arrays, a and b:
>>> a
array([[ 1, 10],
[ 2, 20],
[ 5, 30]])
>>> b
array([[ 1, 11],
[ 3, 31],
[ 4, 41]])
which I want to splice together into the following array, c:
>>> c
array([[ 1., 10.],
... | Splice arrays in NumPy? | I'd like to perform a splice of sorts in NumPy. Let's say I have two arrays, a and b:
>>> a
array([[ 1, 10],
[ 2, 20],
[ 5, 30]])
>>> b
array([[ 1, 11],
[ 3, 31],
[ 4, 41]])
which I want to splice together into the following array, c:
>>> c
array([[ 1., 10.],
[ 2., 20.],
[... | [
"I don't think there is anything in NumPy to do that. Do you need exactly that result (in order, second column with undefined value)? Maybe there is something close that would still be useful for the end goal.\n",
"You could stack the two together and then sort. However, this doesn't take care of the fact that y... | [
1,
1,
1
] | [] | [] | [
"array_splice",
"numpy",
"python"
] | stackoverflow_0004506271_array_splice_numpy_python.txt |
Q:
Python ASCII to binary
Is there a builtin function that converts ASCII to binary?
For example. converts 'P' to 01010000.
I'm using Python 2.6.6
A:
How about two together?
bin(ord('P'))
# 0b1010000
A:
Do you want to convert bytes or characters? There's a difference.
If you want bytes, then you can use
# Python... | Python ASCII to binary | Is there a builtin function that converts ASCII to binary?
For example. converts 'P' to 01010000.
I'm using Python 2.6.6
| [
"How about two together?\nbin(ord('P'))\n# 0b1010000\n\n",
"Do you want to convert bytes or characters? There's a difference.\nIf you want bytes, then you can use\n# Python 2.x\n' '.join(bin(ord(x))[2:].zfill(8) for x in u'שלום, עולם!'.encode('UTF-8'))\n\n# Python 3.x\n' '.join(bin(x)[2:].zfill(8) for x in 'שלום... | [
17,
8,
0
] | [] | [] | [
"ascii",
"binary",
"python"
] | stackoverflow_0004523551_ascii_binary_python.txt |
Q:
Transfer Text File in Web Server to Client
I try to use the following script to transfer a text file located in web server, to client (The text file is in UTF-16).
import cgi
print "Content-Type: text/plain"
print "Content-Disposition: attachment; filename=TEST.txt"
print
filename = "C:\\TEST.TXT"
f = open(filen... | Transfer Text File in Web Server to Client | I try to use the following script to transfer a text file located in web server, to client (The text file is in UTF-16).
import cgi
print "Content-Type: text/plain"
print "Content-Disposition: attachment; filename=TEST.txt"
print
filename = "C:\\TEST.TXT"
f = open(filename, 'r')
for line in f:
print line
However... | [
"First, you should specify the file encoding in your Content-Type header:\nprint \"Content-Type: text/plain; charset=UTF-16\"\nprint \"Content-Disposition: attachment; filename=TEST.txt\"\nprint\n\nThen, you have to actually encode the lines in UTF-16 when sending them to the client:\nprint \"\\xff\\xfe\", # send ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004516503_python.txt |
Q:
Python GTK "Getting started" tutorial problem
I have a problem with compiling a basic and really simple example of PyGTK usage listed on pygtk's website.
This is the first example from this site:
http://www.pygtk.org/pygtk2tutorial/ch-GettingStarted.html
My code looks like this:
#!/usr/bin/env python
# example gt... | Python GTK "Getting started" tutorial problem | I have a problem with compiling a basic and really simple example of PyGTK usage listed on pygtk's website.
This is the first example from this site:
http://www.pygtk.org/pygtk2tutorial/ch-GettingStarted.html
My code looks like this:
#!/usr/bin/env python
# example gtk.py
import pygtk
pygtk.require('2.0')
import gtk
... | [
"Yep, it seems like you might have named your script \"gtk.py\".\nWhich is a bad idea for what should be fairly obvious reasons!\n"
] | [
8
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004523790_gtk_pygtk_python.txt |
Q:
Creating python c module independent of python version?
In Tcl, there is a concept of stubs, where you can have a C extension that works with any compatible version of Tcl. Is there a comparable concept for Python?
I'd like to distribute a binary module that would run on Ubuntu 8.04 (python 2.5), Ubuntu 10.04 (py... | Creating python c module independent of python version? | In Tcl, there is a concept of stubs, where you can have a C extension that works with any compatible version of Tcl. Is there a comparable concept for Python?
I'd like to distribute a binary module that would run on Ubuntu 8.04 (python 2.5), Ubuntu 10.04 (python 2.6), and Centos 5 (python 2.4). I'd like to only have ... | [
"If you distribute your module as source, it can be compiled as necessary.\nThis problem occurs a lot with Windows, for which modules are normally distributed as binaries. PEP 384 proposes a solution (a limited interface which is guaranteed to exist for all Python 3 versions) and is implemented in Python 3.2. Until... | [
4
] | [] | [] | [
"module",
"python",
"tcl"
] | stackoverflow_0004522767_module_python_tcl.txt |
Q:
NumPy Under Xen Client System
I am working on a project built on NumPy, and I would like to take advantage of some of NumPy's optional architecture-specific optimizations. If I install NumPy on a paravirtualized Xen client OS (Ubuntu, in this case - a Linode), can I take advantage of those optimizations?
A:
Yes... | NumPy Under Xen Client System | I am working on a project built on NumPy, and I would like to take advantage of some of NumPy's optional architecture-specific optimizations. If I install NumPy on a paravirtualized Xen client OS (Ubuntu, in this case - a Linode), can I take advantage of those optimizations?
| [
"Yes. The optimizations run in userland and so shouldn't cause any PV traps.\n"
] | [
1
] | [] | [] | [
"numpy",
"python",
"ubuntu",
"virtualization",
"xen"
] | stackoverflow_0004523267_numpy_python_ubuntu_virtualization_xen.txt |
Q:
Is my code a correct implementation of this homework?
The problem is to write the python that calculates the interest due on a loan and prints a payment schedule. The interest due on a loan can be calculated according to the simple formula:
I = P × R × T
where I is the interest paid, P is the amount borrowed (pr... | Is my code a correct implementation of this homework? | The problem is to write the python that calculates the interest due on a loan and prints a payment schedule. The interest due on a loan can be calculated according to the simple formula:
I = P × R × T
where I is the interest paid, P is the amount borrowed (principal), R is the interest rate, and T is the length of th... | [
"The use of Decimal(input()) is wrong:\n>>> decimal.getcontext().prec=3\n>>> decimal.Decimal(input('enter the number: '))\nenter the number: 0.1\nDecimal('0.1000000000000000055511151231257827021181583404541015625')\n\nUsing input causes Python to evaluate the input, which creates a floating-point value. Fix this by... | [
2,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004520739_python.txt |
Q:
sending instant messages through python (msn)
ok I am well aware there are many other questions about this, but I have been searching and have yet to find a solid proper answer that doesnt revolve around jabber or something worse. (no offense to jabber users, just I don't want all the extras that come with it)
I c... | sending instant messages through python (msn) | ok I am well aware there are many other questions about this, but I have been searching and have yet to find a solid proper answer that doesnt revolve around jabber or something worse. (no offense to jabber users, just I don't want all the extras that come with it)
I currently have msnp and twisted.words, I simply want... | [
"You are using a library abandoned in 2004 so i'm not sure if msnp could still be used to talk on MSN.\nAnyway i would try with:\nwhile True:\n msn.process(chats = True)\n time.sleep(1)\n\nusing the contact id and not the email address.\ncontacts = msn.friend_list.get_friends()\ncontact_id = contacts.get_pa... | [
0,
0,
0
] | [] | [] | [
"msn",
"python",
"twisted"
] | stackoverflow_0003186129_msn_python_twisted.txt |
Q:
Symlink Exploits in Python
While reading about shell scripts and temporary file handling, I came across Symlink Exploits. http://www.linuxsecurity.com/content/view/115462/151/ is the basic idea. I wondered if Python open() checks the file it is about to open to see if it is a symbolic link and tried to open a symb... | Symlink Exploits in Python | While reading about shell scripts and temporary file handling, I came across Symlink Exploits. http://www.linuxsecurity.com/content/view/115462/151/ is the basic idea. I wondered if Python open() checks the file it is about to open to see if it is a symbolic link and tried to open a symbolic link file in 'w' mode. To m... | [
"If your program is running with elevated privileges (such as root), then you can prevent this type of attack by not writing to files in a directory where lower privilege users have the ability to create symlinks.\nThis problem cannot be solved by the language or runtime library, but must be addressed in the enviro... | [
2,
1,
1
] | [] | [] | [
"python",
"python_2.4",
"symlink"
] | stackoverflow_0004524293_python_python_2.4_symlink.txt |
Q:
I can see the directory in the python sys.path yet I get an error when I try to import the library?
My guess is I am missing something very basic and obvious which some one can point out to me.
The below screen capture of a short command-line session shows the following:
I can see the pysal directory exists in the... | I can see the directory in the python sys.path yet I get an error when I try to import the library? | My guess is I am missing something very basic and obvious which some one can point out to me.
The below screen capture of a short command-line session shows the following:
I can see the pysal directory exists in the sys.path yet I get an ImportError when I try to import pysal?
| [
"Python imports packages and modules within the entries in sys.path, not the entries themselves. This means that either C:\\Users\\Max\\Documents\\pysal\\pysal.py or C:\\Users\\Max\\Documents\\pysal\\pysal\\__init__.py would have to exist in order to be imported.\n"
] | [
2
] | [] | [] | [
"import",
"path",
"python",
"windows"
] | stackoverflow_0004524308_import_path_python_windows.txt |
Q:
how do I return all memcached values in Google App Engine?
I want to use all the data in my python app engine memcache. I do not know the keys in advance.
How do I go about getting all data?
A:
The only read functions available on memcache are:
get(key, namespace=None)
get_multi(keys, key_prefix='', namespace=... | how do I return all memcached values in Google App Engine? | I want to use all the data in my python app engine memcache. I do not know the keys in advance.
How do I go about getting all data?
| [
"The only read functions available on memcache are:\nget(key, namespace=None)\n\nget_multi(keys, key_prefix='', namespace=None)\n\nAs you can see, to get data from memcache you must provide one or more keys.\n",
"I am using a 'well known key' called \"config\" where I store a list of all other keys and use that t... | [
4,
1,
0
] | [] | [] | [
"google_app_engine",
"memcached",
"python",
"python_memcached"
] | stackoverflow_0003611830_google_app_engine_memcached_python_python_memcached.txt |
Q:
Writing docstrings - specifying functions arguments and returns
Suppose I have a function, say:
>>> def foo(a):
return a+1
I want to write a documentation string for it.
what is the convention in specifying in the docstring that it takes a and returns a+1?
A:
The idea of a docstring is to give the user ... | Writing docstrings - specifying functions arguments and returns | Suppose I have a function, say:
>>> def foo(a):
return a+1
I want to write a documentation string for it.
what is the convention in specifying in the docstring that it takes a and returns a+1?
| [
"The idea of a docstring is to give the user a basic overview of what's going in and coming out without telling them too much about how that happens. In this case:\ndef foo(a):\n \"\"\"Take a number a and return its value incremented by 1.\"\"\"\n return a + 1\n\nFor a less trivial example, I like the one in ... | [
5,
3,
2,
1
] | [] | [] | [
"docstring",
"python"
] | stackoverflow_0004524450_docstring_python.txt |
Q:
Django save method
So I have a model with a FileField for excel spreadsheet. What I need to do this add another column in this spreadsheet, in each row let user pick from a drop-down list then save it and display it in html. All the picking and uploading will happen through the admin interface. So I have figured o... | Django save method | So I have a model with a FileField for excel spreadsheet. What I need to do this add another column in this spreadsheet, in each row let user pick from a drop-down list then save it and display it in html. All the picking and uploading will happen through the admin interface. So I have figured out way how to display a ... | [
"I've found the xlwt package useful when I needed to produce excel files in python. It looks like there are some advances to python excel manipulation technology since I used it though. http://www.python-excel.org/ has lots of alternatives, plus a detailed tutorial.\nAs for the Django save method, I came up with a... | [
0
] | [] | [] | [
"django",
"django_admin",
"excel",
"html",
"python"
] | stackoverflow_0004523318_django_django_admin_excel_html_python.txt |
Q:
global applied stylesheet link on debian box
Having some trouble identifying what is wrong with my link to an external CSS stylesheet...
I am using a debian box to host some things... including a file i am accessing page.py which is located in /var/www/cgi-bin. I need this page to link to a css file which currentl... | global applied stylesheet link on debian box | Having some trouble identifying what is wrong with my link to an external CSS stylesheet...
I am using a debian box to host some things... including a file i am accessing page.py which is located in /var/www/cgi-bin. I need this page to link to a css file which currently has the pathname /var/www/styles.css.
Now I know... | [
"<link rel=\"stylesheet\" href=\"/styles.css\" type=\"text/css\">\n\n"
] | [
0
] | [] | [] | [
"css",
"html",
"hyperlink",
"python"
] | stackoverflow_0004524947_css_html_hyperlink_python.txt |
Q:
Every day,week,month,year in AppEngine cron (python)
I'm trying to set an appengine task to be repeated at midnight of every day, week, month, and year, for clearing a high score list for a game.
My cron.yaml looks like this:
- description: daily clear
url: /delete?off=10
schedule: every day 00:00
- descriptio... | Every day,week,month,year in AppEngine cron (python) | I'm trying to set an appengine task to be repeated at midnight of every day, week, month, and year, for clearing a high score list for a game.
My cron.yaml looks like this:
- description: daily clear
url: /delete?off=10
schedule: every day 00:00
- description: weekly clear
url: /delete?off=20
schedule: every mo... | [
"The docs you link to give examples of how you could achieve all of the results you want.\n# Daily:\nevery day 00:00\n\n# Weekly:\nevery monday 00:00\n\n# Monthly:\n1 of month 00:00\n\n# Yearly:\n1 of jan 00:00\n\n",
"I would go with something like this:\n- description: daily clear\n url: /delete/daily\n schedu... | [
35,
3
] | [] | [] | [
"cron",
"google_app_engine",
"python"
] | stackoverflow_0004521385_cron_google_app_engine_python.txt |
Q:
Python Loop for mysql statement
I have a project that i need to compile number of cities in each state and make an insert statement for mysql database.
I think the easiest way to do it is via python but since i m a complete noob i would like to reach out all the python gurus here.
Here is what the input looks like... | Python Loop for mysql statement | I have a project that i need to compile number of cities in each state and make an insert statement for mysql database.
I think the easiest way to do it is via python but since i m a complete noob i would like to reach out all the python gurus here.
Here is what the input looks like. Example below is for Florida.
citie... | [
"If you want idLocation to auto increment make it a primary key of the table. I would also look into foreign keys instead of putting the states and cities into the same table.\nHere is some code that will get you close to what you're asking for:\ncities.sort()\nfor i in range(len(cities)):\n print \"(%d, '%s', 0... | [
1,
1
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0004524091_loops_python.txt |
Q:
django using columns from other models without inheritance
am not entirely sure if what am about to do is programmically possible. Although if this works, It will help me a lot organize my code.
class AuditColumns(models.Model):
created_at=models.DateField("Created at")
created_by=models.ForeignKey(User, d... | django using columns from other models without inheritance | am not entirely sure if what am about to do is programmically possible. Although if this works, It will help me a lot organize my code.
class AuditColumns(models.Model):
created_at=models.DateField("Created at")
created_by=models.ForeignKey(User, db_column="created_by", related_name="%(app_label)s_%(class)s_y+"... | [
"The usual way to do this is with content types. You create a model similar to AuditColumns, but you also include another field, a GenericForeignKey, which can point to any model within the project's database.\n",
"Python will let you do multiple inheritance so you can inherit the attributes of multiple base clas... | [
4,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004525147_django_python.txt |
Q:
what is the simplest way to get element content by XPath with Python?
I need to get content for this XPath:
/html/body/div/table[2]/tbody/tr/td[2]
It's copied from FireBug. How can I do this? I have a very large HTML document, so I don't want (and don't know how:) ) to grep it. Thanks.
A:
lxml can handle html (... | what is the simplest way to get element content by XPath with Python? | I need to get content for this XPath:
/html/body/div/table[2]/tbody/tr/td[2]
It's copied from FireBug. How can I do this? I have a very large HTML document, so I don't want (and don't know how:) ) to grep it. Thanks.
| [
"lxml can handle html (and provides pretty good xpath support):\n>>> import lxml.html\n>>> tree = lxml.html.parse('test.html')\n>>> for node in tree.xpath('/html/body/div/table[2]/tbody/tr/td[2]'):\n... print node.text\n... \nfirst row, second column\nsecond row, second column\n\nJust make sure that yo... | [
1,
0
] | [] | [] | [
"python",
"xpath"
] | stackoverflow_0004525133_python_xpath.txt |
Q:
Python 2.3 on Leopard
Is anybody using Python 2.3 for Leopard? If so, could you please tell me what you did to get it to work.
Thanks.
Edit: I'm trying to run this (http://sourceforge.net/projects/decompyle/) and it appears that it needs Python 2.3 (doesn't install on 2.4, 2.5, or 2.6). If somebody can advise on... | Python 2.3 on Leopard | Is anybody using Python 2.3 for Leopard? If so, could you please tell me what you did to get it to work.
Thanks.
Edit: I'm trying to run this (http://sourceforge.net/projects/decompyle/) and it appears that it needs Python 2.3 (doesn't install on 2.4, 2.5, or 2.6). If somebody can advise on how to do that without Pyt... | [
"First of all: DONT.\nIf you absolutely have to do so here is how to compile it on Tiger, it'll work on Leopard too. But beware that some stdlib features might not work, so you are on your own here.\n"
] | [
1
] | [] | [] | [
"macos",
"osx_leopard",
"python"
] | stackoverflow_0004525320_macos_osx_leopard_python.txt |
Q:
wxPython - resizing a MatPlotLib FigureCanvas in a ScrolledPanel
I have a figure canvas in a ScrolledPanel in a Panel. I want to change the size of the figure canvas. E.g.
mplFigure.set_figheight(1.0)
someobject.soSomethingThatResizeItAll
How can I do this?
Thanks
David
Here's my construction code.
panel = w... | wxPython - resizing a MatPlotLib FigureCanvas in a ScrolledPanel | I have a figure canvas in a ScrolledPanel in a Panel. I want to change the size of the figure canvas. E.g.
mplFigure.set_figheight(1.0)
someobject.soSomethingThatResizeItAll
How can I do this?
Thanks
David
Here's my construction code.
panel = wx.Panel(self) # we put the scrollablePanel in the panel so later ... | [
"Well I've found part of the answer.\nmplFigureCanvas.SetSize(...) does it initially but as soon as I resize the frame it goes back to the original size.\n-- DB\n",
"Well I now have some horrible code that gets the result but it's not pretty.\n mplFigure.set_size_inches(sizeInInches)\n l,b,w,h = mplFigure.b... | [
0,
0,
0
] | [] | [] | [
"matplotlib",
"python",
"wxpython"
] | stackoverflow_0004156908_matplotlib_python_wxpython.txt |
Q:
how can I improve this python script?
Backup Script
Please check the link above, I wrote this small script in python. It backup files from one directory to the other depends upon the user input. I want to know what are the limitations of this script and all the improvements that can be done to it. So that I can le... | how can I improve this python script? | Backup Script
Please check the link above, I wrote this small script in python. It backup files from one directory to the other depends upon the user input. I want to know what are the limitations of this script and all the improvements that can be done to it. So that I can learn from my mistakes, I am total beginner t... | [
"First of all, you can replace all os.system (either mk_d, or tar) by pythonic commands os.mkdir() (mkdir) and tarfile\n",
"Don't use raw_input, use command-line parameters.\nTo do this use the optparse module (or argparse for Python 2.7+). Also the use of os.system is not recommented, see Replacing Older Functi... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004525535_python.txt |
Q:
how can I use python to build dynamic web sites?
I'm PHP/MySQL developper
I studied python well as a desktop programming two years ago but I don't use it on the web how can I use python to build dynamic web sites and easily uploads these sites to any hosting providers
A:
there are many web frameworks such as Dj... | how can I use python to build dynamic web sites? | I'm PHP/MySQL developper
I studied python well as a desktop programming two years ago but I don't use it on the web how can I use python to build dynamic web sites and easily uploads these sites to any hosting providers
| [
"there are many web frameworks such as Django & web2py , you should check them out\n",
"You cant' upload python files and use it on any webhosting.\nYou can use them if the host allows it.\nSome frameworks are Django or Pylons.\n",
"Have a look at Django project and web2py and also web frameworks for python\n"
... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004525562_python.txt |
Q:
Is it possible for a python function to return more than 1 value?
I am learning the use of functions in python and want to know if it is possible to return more than 1 value.
A:
You can return the values you want to return as a tuple.
Example:
>>> def f():
... return 1, 2, 3
...
>>> a, b, c = f()
>>> a
1
>>... | Is it possible for a python function to return more than 1 value? | I am learning the use of functions in python and want to know if it is possible to return more than 1 value.
| [
"You can return the values you want to return as a tuple.\nExample:\n>>> def f():\n... return 1, 2, 3\n... \n>>> a, b, c = f()\n>>> a\n1\n>>> b\n2\n>>> c\n3\n>>>\n\n",
"Python has some parameter unpacking which is cool. So although you can only return one value, if it is a tuple, you can unpack it automatical... | [
7,
7,
1,
1
] | [] | [] | [
"function",
"python",
"return_value"
] | stackoverflow_0004525433_function_python_return_value.txt |
Q:
Python: Pickling a dict with some unpicklable items
I have an object gui_project which has an attribute .namespace, which is a namespace dict. (i.e. a dict from strings to objects.)
(This is used in an IDE-like program to let the user define his own object in a Python shell.)
I want to pickle this gui_project, alo... | Python: Pickling a dict with some unpicklable items | I have an object gui_project which has an attribute .namespace, which is a namespace dict. (i.e. a dict from strings to objects.)
(This is used in an IDE-like program to let the user define his own object in a Python shell.)
I want to pickle this gui_project, along with the namespace. Problem is, some objects in the na... | [
"I would use the pickler's documented support for persistent object references. Persistent object references are objects that are referenced by the pickle but not stored in the pickle.\nhttp://docs.python.org/library/pickle.html#pickling-and-unpickling-external-objects\nZODB has used this API for years, so it's ve... | [
7,
1,
1,
0,
0
] | [] | [] | [
"graceful_degradation",
"pickle",
"python"
] | stackoverflow_0004080688_graceful_degradation_pickle_python.txt |
Q:
Opinions about Dabo
Has anyone used Dabo lately? How does it rate vs Boa Constructor, etc? I'm writing a new Python database app and Dabo looks promising, but what's the real-world scoop on it?
Is it used by many developers? It's not talked about very much here on SO, or anywhere, as far as I can tell. I'm just a ... | Opinions about Dabo | Has anyone used Dabo lately? How does it rate vs Boa Constructor, etc? I'm writing a new Python database app and Dabo looks promising, but what's the real-world scoop on it?
Is it used by many developers? It's not talked about very much here on SO, or anywhere, as far as I can tell. I'm just a little concerned that the... | [
"One of the authors of Dabo recently wrote some information about Dabos userbase at SO.\nBut for the rest of your question I am not of great help. \n",
"All I can give you are some videos made by the author on pycon 2007 (I fell in love with the framework with his presentation(but I don't have any experience yet(... | [
1,
1
] | [] | [] | [
"dabo",
"python"
] | stackoverflow_0002781996_dabo_python.txt |
Q:
Python and classes
How i can call first.TQ in Second ? Without creating object First in Second.
class First:
def __init__(self):
self.str = ""
def TQ(self):
pass
def main(self):
T = Second(self.str) # Called here
class Second():
def __init__(self):
list = {u"RANDINT... | Python and classes | How i can call first.TQ in Second ? Without creating object First in Second.
class First:
def __init__(self):
self.str = ""
def TQ(self):
pass
def main(self):
T = Second(self.str) # Called here
class Second():
def __init__(self):
list = {u"RANDINT":first.TQ} # List of fu... | [
"You need to make the TQ-metod static. After a fast checkup on Google (I am not too familiar with Python) I found this: http://code.activestate.com/recipes/52304-static-methods-aka-class-methods-in-python/\nIt seems to answer your question.\n",
"If you want to call a method without creating a object of a class, y... | [
1,
1,
1,
1
] | [] | [] | [
"class",
"oop",
"python"
] | stackoverflow_0004526417_class_oop_python.txt |
Q:
What's the simplest python lib for edit mp3's album and artist?
What's the simplest python lib for edit mp3 album and artist?
I mean, just get and set the strings.
A:
I don't know if it's the simplest, but one Python-centric audio tagging library I've heard about many times is Mutagen.
A:
Good review at http:/... | What's the simplest python lib for edit mp3's album and artist? | What's the simplest python lib for edit mp3 album and artist?
I mean, just get and set the strings.
| [
"I don't know if it's the simplest, but one Python-centric audio tagging library I've heard about many times is Mutagen.\n",
"Good review at http://www.blog.pythonlibrary.org/2010/04/22/parsing-id3-tags-from-mp3s-using-python/\nGist of it: eyeD3 (with a quick hack to install on Windows) or mutagen (without much d... | [
3,
1
] | [] | [] | [
"mp3",
"python"
] | stackoverflow_0004526370_mp3_python.txt |
Q:
pyparsing: getting results from parsed data
I am trying to parse some SQL statements (CREATE TABLE exactly) using pyparsing. For both database name and table table I have created identifiers:
identifier = (Combine(Optional('"') + Word(alphanums) +
ZeroOrMore('_' + Word(alphanums)) +
... | pyparsing: getting results from parsed data | I am trying to parse some SQL statements (CREATE TABLE exactly) using pyparsing. For both database name and table table I have created identifiers:
identifier = (Combine(Optional('"') + Word(alphanums) +
ZeroOrMore('_' + Word(alphanums)) +
Optional('"')) & ~keywords_set)
d... | [
"There is a difference between print a, b and print (a,b):\n>>> a, b = \"ab\"\n>>> a\n'a'\n>>> b\n'b'\n>>> print a, b\na b\n>>> print (a, b)\n('a', 'b')\n\nprint a, b prints two objects a and b. print (a, b) prints a single object the tuple a, b:\n>>> w = sys.stdout.write\n>>> _ = w(str(a)), w(' '), w(str(b)), w('\... | [
1
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0004526026_pyparsing_python.txt |
Q:
Query syntax to select exactly one item for each category
class Category(models.Model):
pass
class Item(models.Model):
cat = models.ForeignKey(Category)
I want to select exactly one item for each category, which is the query syntax for do this?
A:
Your question isn't entirely clear: since you didn't sa... | Query syntax to select exactly one item for each category | class Category(models.Model):
pass
class Item(models.Model):
cat = models.ForeignKey(Category)
I want to select exactly one item for each category, which is the query syntax for do this?
| [
"Your question isn't entirely clear: since you didn't say otherwise, I'm going to assume that you don't care which item is selected for each category, just that you need any one. If that isn't the case, please update the question to clarify.\n\ntl;dr version: there is no documented\n way to explicitly use GROUP BY... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004524445_django_python.txt |
Q:
Python urllib2. URLError:
I'm making multiple connection to API. Making delete query. I got that error on a 3000'th query.
Something like this:
def delete_request(self,path):
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('%s%s'%(self.endpoint,path))
signature = self._g... | Python urllib2. URLError: | I'm making multiple connection to API. Making delete query. I got that error on a 3000'th query.
Something like this:
def delete_request(self,path):
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('%s%s'%(self.endpoint,path))
signature = self._gen_auth('DELETE', path, '')
... | [
"The error comes from Windows itself, see Avoiding TCP/IP Port Exhaustion. To fix the error close your connection, you are not calling opener.close() hence leaking sockets.\n"
] | [
9
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004526933_python_urllib2.txt |
Q:
How do I serve a large file using Pylons?
I am writing a Pylons-based download gateway. The gateway's client will address files by ID:
/file_gw/download/1
Internally, the file itself is accessed via HTTP from an internal file server:
http://internal-srv/path/to/file_1.content
The files may be quite large, so I w... | How do I serve a large file using Pylons? | I am writing a Pylons-based download gateway. The gateway's client will address files by ID:
/file_gw/download/1
Internally, the file itself is accessed via HTTP from an internal file server:
http://internal-srv/path/to/file_1.content
The files may be quite large, so I want to stream the content. I store metadata abo... | [
"One thing you'll want to avoid is loading the entire file into memory before returning the first byte to the client. In wsgi you can return an iterator for the body of the response. The webob documentation has an example of this that you should be able to work into your controller. After all, pylons uses webob.\nT... | [
2,
1,
0
] | [] | [] | [
"download",
"pylons",
"python",
"web_services"
] | stackoverflow_0004521123_download_pylons_python_web_services.txt |
Q:
Which is the best django library that user can login my site use their facebook account
i find three ways to do this :
1.django-facebookconnect
2.django-socialregistration
3.pyfacebook
which is better ,
thanks
A:
This link can be useful: http://djangopackages.com/grids/g/facebook-authentication/
I personally f... | Which is the best django library that user can login my site use their facebook account | i find three ways to do this :
1.django-facebookconnect
2.django-socialregistration
3.pyfacebook
which is better ,
thanks
| [
"This link can be useful: http://djangopackages.com/grids/g/facebook-authentication/\nI personally found existing apps bloated and inflexible (or just can't wrap my head around them) so I forked the most simple and well-written among them ( https://github.com/policus/django-registration-facebook-backend ) and imple... | [
0
] | [] | [] | [
"django",
"facebook",
"python"
] | stackoverflow_0004505329_django_facebook_python.txt |
Q:
How do I set a decorator for every one of my Django views?
Suppose I have 20 views inside views.py
How do I set a decorator on top of each function? Without manually pasting one on top?
A:
I found a discussion regarding this here: http://groups.google.com/group/django-users/browse_thread/thread/2cff3374d365998d/... | How do I set a decorator for every one of my Django views? | Suppose I have 20 views inside views.py
How do I set a decorator on top of each function? Without manually pasting one on top?
| [
"I found a discussion regarding this here: http://groups.google.com/group/django-users/browse_thread/thread/2cff3374d365998d/24cd8b86b73d3832?lnk=raot&pli=1\nThe general conclusion is that you could write some code to auto-apply your decorator to all views, but that in general it is not worth the trouble and later ... | [
0,
0
] | [] | [] | [
"decorator",
"django",
"oop",
"python"
] | stackoverflow_0004505499_decorator_django_oop_python.txt |
Q:
represent a file as an object with python
Questions: How do you represent a file in python as an object, entirely in memory, making no calls to the hard drive?
Info:
I'm working on a project that has files distributed across many computers at once, these files are all stored in a SQLite3 database with identifier... | represent a file as an object with python | Questions: How do you represent a file in python as an object, entirely in memory, making no calls to the hard drive?
Info:
I'm working on a project that has files distributed across many computers at once, these files are all stored in a SQLite3 database with identifiers so that the files can be keep in sync and I o... | [
"Take a look at the StringIO (and cStringIO) module: http://docs.python.org/library/stringio.html\n"
] | [
4
] | [] | [] | [
"file",
"memory",
"object",
"python"
] | stackoverflow_0004527539_file_memory_object_python.txt |
Q:
How could I embed Lua into Python 3.x?
Is it possible to embed Lua into Python 3.x? If so how could I run and execute Lua scripts within my Python program? How good would the interaction be between the Languages for instance would Lua have access to all of Python's variables and classes and would Python have acc... | How could I embed Lua into Python 3.x? | Is it possible to embed Lua into Python 3.x? If so how could I run and execute Lua scripts within my Python program? How good would the interaction be between the Languages for instance would Lua have access to all of Python's variables and classes and would Python have access to all of Lua's information?
| [
"Try Lunatic Python, a two-way bridge between Python and Lua.\n",
"In addition to Lunatic Python, there is Lupa, powered by LuaJIT: \nhttp://pypi.python.org/pypi/lupa/0.9\nSee the link about advantages and reasons to use it.\n"
] | [
7,
5
] | [] | [] | [
"embedding",
"lua",
"python",
"python_3.x",
"scripting"
] | stackoverflow_0004527261_embedding_lua_python_python_3.x_scripting.txt |
Q:
Non-generated script with SetupTools/Distribute in setup.py
I'm trying to get a non-generated script when I run setup.py install for a Python Package that I am building.
I have read the distutils documentation but couldn't find clear examples on how to accomplish this.
Mercurial does this in some part by importing... | Non-generated script with SetupTools/Distribute in setup.py | I'm trying to get a non-generated script when I run setup.py install for a Python Package that I am building.
I have read the distutils documentation but couldn't find clear examples on how to accomplish this.
Mercurial does this in some part by importing the install_scripts :
from distutils.command.install_scripts imp... | [
"After days of digging around... it turns out that Mercurial is not doing anything special. \nEven though their setup.py does a lot of things it actually does not do anything to interfere with installing a script correctly without pkg_resources linking to it.\nWhat is the difference then?\nThe difference is that I ... | [
1,
0
] | [] | [] | [
"distutils",
"easy_install",
"python"
] | stackoverflow_0004495785_distutils_easy_install_python.txt |
Q:
How to parse json data in jquery ajax success?
info = {
'phone_number': '123456',
'personal_detail': {'foo': foo, 'bar': bar},
'is_active': 1,
'document_detail': {'baz': baz, 'saz': saz},
'is_admin': 1,
'email': 'foo@bar.com'
}
return HttpResponse(
simplejson.dumps({'success':'True', '... | How to parse json data in jquery ajax success? | info = {
'phone_number': '123456',
'personal_detail': {'foo': foo, 'bar': bar},
'is_active': 1,
'document_detail': {'baz': baz, 'saz': saz},
'is_admin': 1,
'email': 'foo@bar.com'
}
return HttpResponse(
simplejson.dumps({'success':'True', 'result':info}),
mimetype='application/javascript... | [
"May be you are looking for jquery parse json, if I understand the question properly.\n",
"$.getJSON('/ajax_url/',\n {\n 'some_data': 'Some Value'\n },\n function(result){\n alert(result.personal_detail.foo);\n }\n);\n\n$.getJSON sends a GET request to the provided url (first argument) w... | [
0,
0
] | [] | [] | [
"ajax",
"jquery",
"python"
] | stackoverflow_0004524210_ajax_jquery_python.txt |
Q:
parse unformatted string into dictionary with python
I have following string.
DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO
I need to create dictionary so it would be like
{
"DATE": "12242010",
"Key Type": "Nod32 Anti-Vir (30d trial)",
"Key": "a5B2s-sH12B-... | parse unformatted string into dictionary with python | I have following string.
DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO
I need to create dictionary so it would be like
{
"DATE": "12242010",
"Key Type": "Nod32 Anti-Vir (30d trial)",
"Key": "a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO"
}
The problem is that string is ... | [
">>> import re\n>>> regex = re.compile(r\"DATE: (\\d+)Key Type: (.*?) Key: ((?:\\w{5}-){5}\\w{5})\")\n>>> match = regex.match(\"DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO\")\n>>> mydict = {\"DATE\": match.group(1),\n... \"Key Type\": match.group(2),\n... ... | [
1,
1,
1
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0004525632_parsing_python_regex.txt |
Q:
Converting legacy string dates to dates
We have some legacy string dates that I need to convert to actual dates that can be used to perform some date logic. Converting to a date object isn't a problem if I knew what the format were! That is, some people wrote 'dd month yy', othes 'mon d, yyyy', etc.
So, I was won... | Converting legacy string dates to dates | We have some legacy string dates that I need to convert to actual dates that can be used to perform some date logic. Converting to a date object isn't a problem if I knew what the format were! That is, some people wrote 'dd month yy', othes 'mon d, yyyy', etc.
So, I was wondering if anybody knew of a py module that at... | [
"Using dateutil:\nIn [25]: import dateutil.parser as parser\n\nIn [26]: parser.parse('25 December 2010')\nOut[26]: datetime.datetime(2010, 12, 25, 0, 0)\n\nIn [27]: parser.parse('Dec 25, 2010')\nOut[27]: datetime.datetime(2010, 12, 25, 0, 0)\n\n",
"The typical approach is to define a list of formats (strptime for... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004528194_python.txt |
Q:
repeated phrases in the text Python
I have a problem and I have no idea how to solve it. Please, give a piece of advice.
I have a text. Big, big text. The task is to find all the repeated phrases which lenght is 3(contain of three words) in the text.
A:
You have, it seems to me, two problems.
The first is coming... | repeated phrases in the text Python | I have a problem and I have no idea how to solve it. Please, give a piece of advice.
I have a text. Big, big text. The task is to find all the repeated phrases which lenght is 3(contain of three words) in the text.
| [
"You have, it seems to me, two problems.\nThe first is coming up with an efficient way of normalizing the input. You say you want to find all of the three-word phrases in the input, but what constitutes a phrase? For instance, are the black dog and The black, dog? the same phrase?\nA way of doing this, as marcog... | [
7,
2,
1,
0
] | [] | [] | [
"python",
"repeat",
"text"
] | stackoverflow_0004526762_python_repeat_text.txt |
Q:
Wait until a webpage finished loading to load the next one in a list
I'm using PyQT webView to visit some webpages I have stored on a dictionary the code is something like this:
def loadLink(self, url):
manager = QNetworkAccessManager()
request = QNetworkRequest(QUrl(url))
self.ui.we... | Wait until a webpage finished loading to load the next one in a list | I'm using PyQT webView to visit some webpages I have stored on a dictionary the code is something like this:
def loadLink(self, url):
manager = QNetworkAccessManager()
request = QNetworkRequest(QUrl(url))
self.ui.webView.load(QUrl(visitar))
def readUnreadLinks(self):
print "Lin... | [
"you might want to use loadFinished signal of yout QWebView control to detect when page loading was finished and trigger loading of the new one. Pls, see if an example below would work for you:\nimport sys\nfrom PyQt4 import QtGui, QtCore, QtWebKit \n\nclass MainForm(QtGui.QMainWindow):\n def __init__(self, pare... | [
3
] | [] | [] | [
"pyqt",
"python",
"webview"
] | stackoverflow_0004506245_pyqt_python_webview.txt |
Q:
In Python, is use of `del` statement a code smell?
I tend to use it whenever I am working on a prototype script, and:
Use a somewhat common variable (such as fileCount), and
Have a large method (20+ lines), and
Do not use classes or namespaces yet.
In this situation, in order to avoid potential variable clash, I... | In Python, is use of `del` statement a code smell? | I tend to use it whenever I am working on a prototype script, and:
Use a somewhat common variable (such as fileCount), and
Have a large method (20+ lines), and
Do not use classes or namespaces yet.
In this situation, in order to avoid potential variable clash, I delete the bugger as soon as I am done with it. I know,... | [
"I don't think that del by itself is a code smell.\nReusing a variable name in the same namespace is definitely a code smell as is not using classes and other namespaces where appropriate. So using del to facilitate that sort of thing is a code smell.\nThe only really appropriate use of del that I can think of off ... | [
26,
9
] | [] | [] | [
"del",
"python"
] | stackoverflow_0004528403_del_python.txt |
Q:
What's wrong with this Python file-read test?
What's wrong with this Python file-read test?
import os
import sys
fileList = os.listdir(sys.argv[1])
count = 0
for file in fileList:
try:
count += 1
print os.path.isfile(file)
if os.path.isfile(file)
print "File >> " + file
... | What's wrong with this Python file-read test? | What's wrong with this Python file-read test?
import os
import sys
fileList = os.listdir(sys.argv[1])
count = 0
for file in fileList:
try:
count += 1
print os.path.isfile(file)
if os.path.isfile(file)
print "File >> " + file
else
print "Dir >> " + file
ex... | [
"missing colon on if and else lines\nif (something): #note the : at the end\n ...\nelse:\n ...\n\n"
] | [
5
] | [] | [] | [
"file",
"file_io",
"python"
] | stackoverflow_0004528445_file_file_io_python.txt |
Q:
Python file-io code listing current folder path instead of the specified
I have the code:
import os
import sys
fileList = os.listdir(sys.argv[1])
for file in fileList:
if os.path.isfile(file):
print "File >> " + os.path.abspath(file)
else:
print "Dir >> " + os.path.abspath(file)
Located i... | Python file-io code listing current folder path instead of the specified | I have the code:
import os
import sys
fileList = os.listdir(sys.argv[1])
for file in fileList:
if os.path.isfile(file):
print "File >> " + os.path.abspath(file)
else:
print "Dir >> " + os.path.abspath(file)
Located in my music folder ("/home/tom/Music")
When I call it with:
python test.py "/tm... | [
"You need to include the full path to the file when you check for existence and print the path:\ndir = sys.argv[1]\n\nfileList = os.listdir(dir)\nfor file in fileList:\n file = os.path.join(dir, file) # Get the full path to the file.\n # etc...\n\n"
] | [
0
] | [] | [] | [
"file",
"file_io",
"python"
] | stackoverflow_0004528531_file_file_io_python.txt |
Q:
Database Compression in Python
I have hourly logs like
user1:joined
user2:log out
user1:added pic
user1:added comment
user3:joined
I want to compress all the flat files down to one file. There are around 30 million users in the logs and I just want the latest user log for all the logs.
My end result is I want to ... | Database Compression in Python | I have hourly logs like
user1:joined
user2:log out
user1:added pic
user1:added comment
user3:joined
I want to compress all the flat files down to one file. There are around 30 million users in the logs and I just want the latest user log for all the logs.
My end result is I want to have a log look like
user1:added com... | [
"If you intern() each log entry then you'll use only one string for each similar log entry regardless of the number of times it shows up, thereby lowering memory usage a lot.\n>>> a = 'foo'\n>>> b = 'foo'\n>>> a is b\nTrue\n>>> b = 'f' + ('oo',)[0]\n>>> a is b\nFalse\n>>> a = intern('foo')\n>>> b = intern('f' + ('o... | [
1,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004528192_python.txt |
Q:
Passing 1 argument, and it's saying I'm passing 2
import os
import sys
class Corrector:
def correctAll(dir):
print "ok"
c = Corrector()
c.correctAll(os.getcwd())
This code is printing:
TypeError: correctAll() takes exactly
1 argument (2 given)
but AFAIK os.getcwd() returns a single string.. wha... | Passing 1 argument, and it's saying I'm passing 2 | import os
import sys
class Corrector:
def correctAll(dir):
print "ok"
c = Corrector()
c.correctAll(os.getcwd())
This code is printing:
TypeError: correctAll() takes exactly
1 argument (2 given)
but AFAIK os.getcwd() returns a single string.. what's wrong here?
| [
"You need to accept self as an argument or use the staticmethod decorator.\nclass Corrector:\n\n def correctAll(self, dir):\n print \"ok\"\n\nor\nclass Corrector:\n\n @staticmethod\n def correctAll(dir):\n print \"ok\"\n\nThe distinction between the two is if you want the method to have acce... | [
4,
1,
1,
0
] | [] | [] | [
"parameter_passing",
"python"
] | stackoverflow_0004528642_parameter_passing_python.txt |
Q:
Number of entities returned from a GQL Query
I'm new to Python and currently working on my first Google App Engine application. In my program I have an 'Inbox' database model which contains string proporties like to_user, from_user, title, content, etc. When a user logs in to my app I want to be able to count th... | Number of entities returned from a GQL Query | I'm new to Python and currently working on my first Google App Engine application. In my program I have an 'Inbox' database model which contains string proporties like to_user, from_user, title, content, etc. When a user logs in to my app I want to be able to count the number of messages that were sent to him/her, th... | [
"In your specific case, where the number of New Messages will probably be small, I would not bother to create a counter upfront as suggested here.\nI would go with a simpler solution using count() function:\nuser = users.get_current_user()\ninbox = Inbox.gql('WHERE to_user = :to_user', to_user=user.nickname())\ncou... | [
2
] | [] | [] | [
"google_app_engine",
"gqlquery",
"python"
] | stackoverflow_0004528434_google_app_engine_gqlquery_python.txt |
Q:
Transforming characters in Python
mir = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'x', 'y']
keq = ['.', 'c', 'z', 's', 'e', 'd', 'f', 'g', 'i', 'h', 'j', 'k', 'b', 'v', 'o', 'p', 'q', 'r', 't', 'u', 'x', ''\'', 'y']
I want to know if any of the cha... | Transforming characters in Python | mir = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'x', 'y']
keq = ['.', 'c', 'z', 's', 'e', 'd', 'f', 'g', 'i', 'h', 'j', 'k', 'b', 'v', 'o', 'p', 'q', 'r', 't', 'u', 'x', ''\'', 'y']
I want to know if any of the characters in keq are pressed in raw_input... | [
"1. You could built a translation table for characters using the maketrans and translate methods, e.g.\n>>> import string\n>>> tb = string.maketrans('abc', '123')\n>>> 'cyan banana'.translate(tb)\n'3y1n 21n1n1'\n\n2. You could concatenate all strings in an array using the ''.join method, e.g.\n>>> arr = ['a', 'b', ... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004528189_python.txt |
Q:
django one click deploy to dreamhost
I have a python/django application that im running on my dreamhost account. Excuse me for the novice question, but I'm a Java programmer by day and relatively new to python.
Ideally what I'd like to do is set something up where I can take the code I have locally, upload it to ... | django one click deploy to dreamhost | I have a python/django application that im running on my dreamhost account. Excuse me for the novice question, but I'm a Java programmer by day and relatively new to python.
Ideally what I'd like to do is set something up where I can take the code I have locally, upload it to my server and then touch the restart.txt f... | [
"All the cool guys are using fabric nowadays. It's exactly what you looking for.\n"
] | [
2
] | [] | [] | [
"django",
"dreamhost",
"mercurial",
"python"
] | stackoverflow_0004528676_django_dreamhost_mercurial_python.txt |
Q:
How do I make sure a message gets to its destination using WebSockets?
I'm still trying to figure out WebSockets.
I'm sending over data from the javascript client to the python server as JSON strings, but they arrive fragmented.
How can I make sure I've received the entire message before I start to parse it?
A:
... | How do I make sure a message gets to its destination using WebSockets? | I'm still trying to figure out WebSockets.
I'm sending over data from the javascript client to the python server as JSON strings, but they arrive fragmented.
How can I make sure I've received the entire message before I start to parse it?
| [
"You need to read up on socket programming in general.\nReading some data from a websocket does not mean you've received everything the other side wanted to send.\nIdeally you'd prefix your messages with a header that contains the size of the payload. Then after you read the header (say, terminated with LF, or bein... | [
1
] | [] | [] | [
"javascript",
"python",
"websocket"
] | stackoverflow_0004529042_javascript_python_websocket.txt |
Q:
Parsing emails as soon as they are received
I have users sending emails with some text I need to extract. Each user's email is mapped to a single mailbox. I'm currently using a cron job that polls the mailbox (postfix) every 5 minutes, checks for new messages, and sends it to a queue where I have workers parse th... | Parsing emails as soon as they are received | I have users sending emails with some text I need to extract. Each user's email is mapped to a single mailbox. I'm currently using a cron job that polls the mailbox (postfix) every 5 minutes, checks for new messages, and sends it to a queue where I have workers parse them. I have two main questions:
Is there a way I... | [
"Use a pipe alias to catch the email, then use celery to dump it into a MQ for processing.\n",
"Yes, this can be done quite easily. All you need to do is configure the postfix to forward email to a script instead of to a mailbox. It does not really have to be a catch-all, you can configure postfix to forward spec... | [
2,
1,
0
] | [] | [] | [
"postfix_mta",
"python"
] | stackoverflow_0004529075_postfix_mta_python.txt |
Q:
Django queries Especial Characters
I Working on location from google maps and using django to. My question is:
I have a String in request.GET['descricao'] lets say it contains "Via rapida".
In my database i have store = "Via Rápida" i'm doing :
local = Local.objects.filter(name__icontains=request.GET['descricao... | Django queries Especial Characters | I Working on location from google maps and using django to. My question is:
I have a String in request.GET['descricao'] lets say it contains "Via rapida".
In my database i have store = "Via Rápida" i'm doing :
local = Local.objects.filter(name__icontains=request.GET['descricao'])
with that i can get everthing fine ... | [
"I think the better way is to use a Full Text search engine , Here is a list of Full Text search engine that can be used with django :\n\nSphinx\nwhoosh\nDjapian (Xapian)\n\nAnd wee shouldn't forget Haystack which is a proxy that can use different search engine like solr, whoosh ...;\nYou can also use your database... | [
2,
1
] | [] | [] | [
"django",
"mysql",
"python",
"sql",
"sqlite"
] | stackoverflow_0004527983_django_mysql_python_sql_sqlite.txt |
Q:
In Django how display all of the values after the for loop is finished instead of displaying them one by one
In my django project in the view I call the last 6 values in the column and send them to the template. I then would like to pass into google charts api those 6 values and have a graph. At the moment for som... | In Django how display all of the values after the for loop is finished instead of displaying them one by one | In my django project in the view I call the last 6 values in the column and send them to the template. I then would like to pass into google charts api those 6 values and have a graph. At the moment for some reason I get 6 different graphs.
{% for foodbag in foodbags %}
<img src="http://chart.apis.google.com/chart?chxl... | [
"Do the join in the view, and then pass the joined string into the template.\nj = u':'.join(unicode(x[12]) for x in foodbags)\n\n"
] | [
0
] | [] | [] | [
"django_views",
"python"
] | stackoverflow_0004529222_django_views_python.txt |
Q:
how to remove these '"' in django template
this is my code in homepage.html:
<script type="text/javascript">
var jstree_jsondata={{json1}};
alert(typeof jstree_jsondata)
</script>
and it show this in the source code :
var jstree_jsondata=
[
{ "data" : "kkkqq node",
"attr"... | how to remove these '"' in django template | this is my code in homepage.html:
<script type="text/javascript">
var jstree_jsondata={{json1}};
alert(typeof jstree_jsondata)
</script>
and it show this in the source code :
var jstree_jsondata=
[
{ "data" : "kkkqq node",
"attr" : { "id" : "ooo" ,"tim... | [
"Change the line:\nvar jstree_jsondata={{json1}}\n\nto\nvar jstree_jsondata={{ json1|safe }}\n\nThis uses the safe filter to tell Django that the contents should be output literally without changing characters to html entities. The reason for the name 'safe' is that you are declaring that the data to be output is s... | [
34
] | [] | [] | [
"django",
"javascript",
"python"
] | stackoverflow_0004529484_django_javascript_python.txt |
Q:
python object typecasting
Ive been trying search how to pass object reference in python and type cast it similar to Java but no to avail. I duno if this topic exists somewhere here.
My trouble is i have to pass the object reference to a class constructor. But i duno how to typecast the reference to an object. In ... | python object typecasting | Ive been trying search how to pass object reference in python and type cast it similar to Java but no to avail. I duno if this topic exists somewhere here.
My trouble is i have to pass the object reference to a class constructor. But i duno how to typecast the reference to an object. In java though I have accomplish t... | [
"Python is a dynamically typed language and as such, it doesn't make much sense to cast something unless you specifically need it in that type.\nIn Python you should use Duck Typing instead: http://en.wikipedia.org/wiki/Duck_typing\nSo instead of trying to convert parent_rectangle to a SearchRectangle() you should ... | [
7,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004529070_python.txt |
Q:
How to get a object database?
Can anyone recommend a module or tell me way to get a object database for Python?
One of the reason I´m interested in databases to save objects is because I suppose a database can provide a simpler piece of code than use pickle.
In my question Saving an Object (Data persistence) some... | How to get a object database? | Can anyone recommend a module or tell me way to get a object database for Python?
One of the reason I´m interested in databases to save objects is because I suppose a database can provide a simpler piece of code than use pickle.
In my question Saving an Object (Data persistence) someone gave me a piece of code using p... | [
"If the simplicity of the code is your main concern, pickle is hard to beat.\nBasically, all you have to do in order to save an object data is:\nwith open('data.pickle', 'w') as pickle_file:\n pickle.dump(data, pickle_file)\n\nYou can then get it back with:\nwith open('data.pickle') as pickle_file:\n data = p... | [
4,
3,
3,
2
] | [] | [] | [
"database",
"object",
"python"
] | stackoverflow_0004529914_database_object_python.txt |
Q:
Using the open function. How can I specify the path?
I'm trying to open a file I created and I don´t get it. I suspect that the open function is not using the proper path... How can I put the path?
>>> filehandler = open(fruits.obj,'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameErr... | Using the open function. How can I specify the path? | I'm trying to open a file I created and I don´t get it. I suspect that the open function is not using the proper path... How can I put the path?
>>> filehandler = open(fruits.obj,'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fruits' is not defined
| [
"The open function takes a string containing the path to your file as its first argument. In your case, you didn't use a string, but you told Python to use the obj property of the fruits object. As there is no fruits object, you get a NameError exception.\nYou should probably change your program to :\n>>> filehandl... | [
3,
1
] | [] | [] | [
"file_io",
"function",
"path",
"python"
] | stackoverflow_0004530230_file_io_function_path_python.txt |
Q:
Python Eggs on Google App Engine
Usually I would use virtualenv and pip for deployment of web applications. With Google App Engine this doesn't work, because all import statement are relative to directory of the application.
The most common approach I saw was to simply copy the packages from site-packages to the d... | Python Eggs on Google App Engine | Usually I would use virtualenv and pip for deployment of web applications. With Google App Engine this doesn't work, because all import statement are relative to directory of the application.
The most common approach I saw was to simply copy the packages from site-packages to the directory of the application. This invo... | [
"It seems manually adding the virtualenv to sys.path solves the problem for me at the moment:\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dev.env/lib/python2.5/site-packages/'))\n\n",
"If you use easy_install instead of pip you can run it with the --install-dir argument to specify ... | [
2,
0
] | [] | [] | [
"google_app_engine",
"pip",
"python",
"virtualenv"
] | stackoverflow_0004530183_google_app_engine_pip_python_virtualenv.txt |
Q:
Python test "framework" for testing input files and their outputs
I'm writing end-to-end tests for my tool, which is written in Python. The tool reads a file as input. I want to test its exit code, and its output.
This is a fairly common idiom, and I've seen it done in several ways. In the PHP project, each test i... | Python test "framework" for testing input files and their outputs | I'm writing end-to-end tests for my tool, which is written in Python. The tool reads a file as input. I want to test its exit code, and its output.
This is a fairly common idiom, and I've seen it done in several ways. In the PHP project, each test is a file, and has lines like: INPUT:, EXPECTED:, EXPECTED_REGEX:, etc. ... | [
"The robot framework might be helpful. It is a keyword driven functional testing tool implemented in python and can be extended with pythion or java. \nsee: http://robotframework.googlecode.com/svn/tags/robotframework-2.5.4/doc/userguide/RobotFrameworkUserGuide.html\nThere are a number of built in libraries that yo... | [
3,
1,
0
] | [] | [] | [
"end_to_end",
"python",
"testing"
] | stackoverflow_0004120960_end_to_end_python_testing.txt |
Q:
Python: saving objects and using pickle. Error using pickle.dump
Hello I have an Error and I don´t the reason:
>>> class Fruits:pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> import pickle
>>> filehandler = open("Fruits.obj",'w')
>>> pickle.dump(banana,filehandler)
Traceback (... | Python: saving objects and using pickle. Error using pickle.dump | Hello I have an Error and I don´t the reason:
>>> class Fruits:pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> import pickle
>>> filehandler = open("Fruits.obj",'w')
>>> pickle.dump(banana,filehandler)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\P... | [
"You have to open your filehandler in binary mode, use wb instead of w:\nfilehandler = open(b\"fruits.obj\",\"wb\")\n\n"
] | [
1
] | [] | [] | [
"object",
"pickle",
"python",
"save"
] | stackoverflow_0004530310_object_pickle_python_save.txt |
Q:
Building PyGTK- and poppler-based binaries under Windows
For quite some time now, I've been fighting in vain to get a software I'm working on to work under Windows. It's written in Python (the 2.x series), and although all Linux users can benefit from its GUI when they use the source package, it seems that many pe... | Building PyGTK- and poppler-based binaries under Windows | For quite some time now, I've been fighting in vain to get a software I'm working on to work under Windows. It's written in Python (the 2.x series), and although all Linux users can benefit from its GUI when they use the source package, it seems that many people who download it go for the Windows package, for which I'v... | [
"There is a window installer here: http://download.gnome.org/binaries/win32/pygtk/2.22/\n"
] | [
2
] | [] | [] | [
"gtk",
"poppler",
"pygtk",
"python",
"windows"
] | stackoverflow_0004468531_gtk_poppler_pygtk_python_windows.txt |
Q:
Python Twisted Client
I have this simple Twisted Client which connects to a Twisted server & queries an index.
If you see fn. connectionMade() in class SpellClient, the query is hard-coded. Did that for testing purposes. How would one pass this query from outside to this class?
The code -
from twisted.internet i... | Python Twisted Client | I have this simple Twisted Client which connects to a Twisted server & queries an index.
If you see fn. connectionMade() in class SpellClient, the query is hard-coded. Did that for testing purposes. How would one pass this query from outside to this class?
The code -
from twisted.internet import reactor
from twisted.... | [
"Protocols, like SpellClient, have access to their factory as self.factory.\n...so there would be a number of ways to do this, but one way would be to create another method on SpellFactory, such as setQuery, and then access that from the client...\n#...in SpellFactory: \ndef setQuery(self, query):\n self.query ... | [
5
] | [] | [] | [
"python",
"twisted",
"twisted.client",
"twisted.internet"
] | stackoverflow_0004529945_python_twisted_twisted.client_twisted.internet.txt |
Q:
How to determine if two Pygame subsurfaces reference the same area?
I have 2 pygame surfaces (technically subsurfaces) and I need to test for their equality.
Here's my code:
actor.display(mockSurface, Rect((0, 0, 640, 640)))
assert actor.image == actor.spriteSheet.subsurface(Rect((0, 30, 30, 30)))
And here's th... | How to determine if two Pygame subsurfaces reference the same area? | I have 2 pygame surfaces (technically subsurfaces) and I need to test for their equality.
Here's my code:
actor.display(mockSurface, Rect((0, 0, 640, 640)))
assert actor.image == actor.spriteSheet.subsurface(Rect((0, 30, 30, 30)))
And here's the code behind actor.display:
def display(self, screen, camera_location):
... | [
"Use Surface.get_offset() and Surface.get_parent() to determine whether both subsurfaces point to the same area of their parent surface.\n>>> parent = pygame.image.load(\"token1.png\")\n>>> parent\n<Surface(128x128x32 SW)>\n>>> s1 = parent.subsurface(pygame.Rect(0, 0, 2, 2))\n>>> s2 = parent.subsurface(pygame.Rect(... | [
2
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0004529685_pygame_python.txt |
Q:
Installing package as a submodule
I have a package 3rd party open source package "foo"; that is in beta phase and I want to tweak it to my requirements. So I don't want to get it installed in /usr/local/lib/python or anywhere in current sys.path as I can't make frequent changes in top level packages.
foo/
__ini... | Installing package as a submodule | I have a package 3rd party open source package "foo"; that is in beta phase and I want to tweak it to my requirements. So I don't want to get it installed in /usr/local/lib/python or anywhere in current sys.path as I can't make frequent changes in top level packages.
foo/
__init__.py
fmod1.py
import foo.mo... | [
"So I don't want to get it installed in /usr/local/lib/python or anywhere in current sys.path as I can't make frequent changes in top level packages.\n\nWhat is wrong with:\npython setup.py develop\n\n",
"Use explicit relative imports to allow relocatable subpackages to refer to themselves. eg in fmod1.py:\nfrom ... | [
2,
0
] | [] | [] | [
"import",
"package",
"python"
] | stackoverflow_0004530671_import_package_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.