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:
Matplotlib: Additional axis when replotting 3D figure using canvas.draw()
I have what is probably a very simple problem replotting some 3D data using Matplotlib. Initially, I have an figure with a 3D projection on a canvas:
self.fig = plt.figure()
self.canvas = FigCanvas(self.mainPanel, -1, self.fig)
self.axes = s... | Matplotlib: Additional axis when replotting 3D figure using canvas.draw() | I have what is probably a very simple problem replotting some 3D data using Matplotlib. Initially, I have an figure with a 3D projection on a canvas:
self.fig = plt.figure()
self.canvas = FigCanvas(self.mainPanel, -1, self.fig)
self.axes = self.fig.add_subplot(111, projection='3d')
I then add some data and use canvas... | [
"Instead of axes.clear() + fig.add_subplot, use the remove method of the mpl_toolkits.mplot3d.art3d.Patch3DCollection object:\nIn [31]: fig = plt.figure()\n\nIn [32]: ax = fig.add_subplot(111, projection='3d')\n\nIn [33]: xs = np.random.random_sample(100)\n\nIn [34]: ys = np.random.random_sample(100)\n\nIn [35]: zs... | [
3,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007947816_matplotlib_python.txt |
Q:
Are there any risks in Python if the module name and class name from inside had identical names?
I would like to know if there any risks to use the exact same name for module and a class from inside the module.
A:
The PEP 8 says that modules should have short, all-lowercase names, while class names use the CapWo... | Are there any risks in Python if the module name and class name from inside had identical names? | I would like to know if there any risks to use the exact same name for module and a class from inside the module.
| [
"The PEP 8 says that modules should have short, all-lowercase names, while class names use the CapWords convention. So, if you have the same name for a module and a class, you're not following those style conventions.\nTechnically, there's no risk at all.\n",
"Apart from potentially confusing yourself (or other d... | [
5,
1,
0,
0
] | [] | [] | [
"naming_conventions",
"python"
] | stackoverflow_0007952526_naming_conventions_python.txt |
Q:
matplotlib and PyQt plotting a surface
I created a 3D plot using matplotlib as this:
fig = pylab.figure()
ax = Axes3D( fig )
surf = ax.plot_surface( X, Y, Z, cmap=cm.gray_r, linewidth=0, antialiased=True )
fig.canvas.set_window_title( "Distance" )
pylab.show()
It's fantastic: I see the surface in grays-cale and I... | matplotlib and PyQt plotting a surface | I created a 3D plot using matplotlib as this:
fig = pylab.figure()
ax = Axes3D( fig )
surf = ax.plot_surface( X, Y, Z, cmap=cm.gray_r, linewidth=0, antialiased=True )
fig.canvas.set_window_title( "Distance" )
pylab.show()
It's fantastic: I see the surface in grays-cale and I can interact with it ( turn the surface, mo... | [
"I think you need to register a callback function for the mouse clicks, like in this cookbook example: http://www.scipy.org/Cookbook/Matplotlib/Interactive_Plotting\n",
"I had this before and it confused me a lot. Zhenya is right about the mouse clicking.\nBy default, control of the plot by mouse is turned off wh... | [
1,
1
] | [] | [] | [
"geometry_surface",
"matplotlib",
"pyqt",
"python"
] | stackoverflow_0007904306_geometry_surface_matplotlib_pyqt_python.txt |
Q:
Workaround for bugs in Python packages
I recently had the following problem: I'm developing a numerical library in Python (called spuq) that needs scipy at its core. Now one of the functions in scipy, its called btdtri, had a bug for a certain tuple of input parameters. This bug, however, is now fixed in scipy ver... | Workaround for bugs in Python packages | I recently had the following problem: I'm developing a numerical library in Python (called spuq) that needs scipy at its core. Now one of the functions in scipy, its called btdtri, had a bug for a certain tuple of input parameters. This bug, however, is now fixed in scipy version 0.9 according to the developers of scip... | [
"You could \"monkey patch\" the scipy module. Somewhere in your initialization code, do\nimport scipy.special\nif scipy.version.version < \"0.9.0\":\n scipy.special.btdtri = my_btdtri\n\nSince modules are imported only once, there will be only one module scipy.special, and all other modules will only see the mo... | [
5,
1
] | [] | [] | [
"package",
"python"
] | stackoverflow_0007952802_package_python.txt |
Q:
Should I stop using a deprecated module?
I am using django-registration v0.7 and django 1.2.4. Everything works fine but I am wondering why I'm getting this warning message each time I run the server:
C:\Python26\lib\site-packages\registration\models.py:4: DeprecationWarning: the sha module is deprec
ated; us... | Should I stop using a deprecated module? | I am using django-registration v0.7 and django 1.2.4. Everything works fine but I am wondering why I'm getting this warning message each time I run the server:
C:\Python26\lib\site-packages\registration\models.py:4: DeprecationWarning: the sha module is deprec
ated; use the hashlib module instead
import sha
... | [
"No, if it works, leave it. You can consider this something to think about when you upgrade to a new version of Python which actually removes this module.\nDeprecated means that you are encouraged not to use it in new code, it doesn't mean you need to modify (and hence break) existing code which uses it.\n",
"you... | [
3,
3,
1,
0
] | [] | [] | [
"deprecated",
"module",
"python",
"warnings"
] | stackoverflow_0007902973_deprecated_module_python_warnings.txt |
Q:
Group related objects in Django
I'm building an app where you can search for objects in a database (let's assume the objects you search for are persons). What I want to do is to group related objects, for example married couples. In other words, if two people share the same last name, we assume that they are marri... | Group related objects in Django | I'm building an app where you can search for objects in a database (let's assume the objects you search for are persons). What I want to do is to group related objects, for example married couples. In other words, if two people share the same last name, we assume that they are married (not a great example, but you get ... | [
"First get your objects sorted by last name:\ndef keyfun(p):\n return p.name.split()[-1]\n\npersons = sorted(Person.objects.all(), key = keyfun)\n\nThen use groupby:\nfrom itertools import groupby\nfor lname, persons in groupby(persons, keyfun):\n print ' - '.join(p.name for p in persons)\n\nUpdate Yes, this ... | [
2
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0007953031_django_django_views_python.txt |
Q:
Django ORM query for a messaging system
I have the following models for an internal messaging app:
class MessageThread(models.Model):
subject = models.CharField(max_length=256, blank=False)
class Message(models.Model):
thread = models.ForeignKey(MessageThread)
content = models.CharField(max_length=500... | Django ORM query for a messaging system | I have the following models for an internal messaging app:
class MessageThread(models.Model):
subject = models.CharField(max_length=256, blank=False)
class Message(models.Model):
thread = models.ForeignKey(MessageThread)
content = models.CharField(max_length=5000, blank=False)
timestamp = models.DateTi... | [
"I added a method in a model manager for this:\n def get_active_threads(self, user):\n all_threads = MessageRecipient.objects.filter(recipient=user).order_by('-message__timestamp')\n\n deleted_threads = []\n final_threads = []\n\n for thread in all_threads:\n if thread.thre... | [
1,
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007948733_django_django_models_python.txt |
Q:
python - matplotlib - disable plot to screen - set to Agg only
I'm getting this problem (asked about before), and can't see how to fix it:
import matplotlib
print dir()
matplotlib.use('Agg')
from scipy import ndimage
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
gives
This call to matplotl... | python - matplotlib - disable plot to screen - set to Agg only | I'm getting this problem (asked about before), and can't see how to fix it:
import matplotlib
print dir()
matplotlib.use('Agg')
from scipy import ndimage
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
gives
This call to matplotlib.use has no effect because the the backend has already been chosen... | [
"Are you maybe looking for this?\nAlternatively, you might want to change your matplotlibrc file.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007953333_python.txt |
Q:
How to do custom ordering of a Django queryset?
A little background about our specific problem ->
We are trying to build a Q & A site, much like Stackoverflow.
People can come and ask questions and other people reply.
So like SO (https://stackoverflow.com/questions) we have a questions page. Now the problem we're ... | How to do custom ordering of a Django queryset? | A little background about our specific problem ->
We are trying to build a Q & A site, much like Stackoverflow.
People can come and ask questions and other people reply.
So like SO (https://stackoverflow.com/questions) we have a questions page. Now the problem we're having is that we have this model :
class Questions(m... | [
"One way of doing it is by defining a custom manager ->\nhttps://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance.\nYou can display the objects in any order you like. You can even return lists and self-defined dictionaries using the custom manager methods.\n",
"Each of your ... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007644168_django_python.txt |
Q:
Which Python user interface library can I use for 2D games?
I want to create a 2D game on Python with heavy user interface: windows, buttons, text input, etc. So far I've been using PyGame for a few simple games.
The game is a 2D MUD, with the standard rendering loop to draw stuff on the screen. I need the user in... | Which Python user interface library can I use for 2D games? | I want to create a 2D game on Python with heavy user interface: windows, buttons, text input, etc. So far I've been using PyGame for a few simple games.
The game is a 2D MUD, with the standard rendering loop to draw stuff on the screen. I need the user interface to interact with the game entities like sales, blacksmith... | [
"I would take PyQT with QGraphicsView or QGraphicsScene.\nSadly there isn´t a Clanlib python binding like for perl and ruby. That would be, probably, the ideal choice.\n",
"You can use the popular Pyglet game library along with wxPython, the cross platform GUI library. An example of how to do this:\nhttp://pyglet... | [
6,
6,
1,
1,
1,
0
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0007869589_python_user_interface.txt |
Q:
What is the best way to store big vector to database with python?
I want to classify some text. So I have to compare it with other texts. After representing texts as vectors how can I store them (very big lists of float values) to SQL database for using them later?
My idea is using pickle module:
vector=text_to_ve... | What is the best way to store big vector to database with python? | I want to classify some text. So I have to compare it with other texts. After representing texts as vectors how can I store them (very big lists of float values) to SQL database for using them later?
My idea is using pickle module:
vector=text_to_vector(text)
present=pickle.dumps(big_list)
some_db.save(text_id,present)... | [
"You may find that pickle and databases don't work too well together.\nPython's pickle is for serializing Python objects to a format, that can then be read back in to Python objects by Python. Although it's very easy to serialize with pickle, you can't* query this serialized format, you can't* read it into a progr... | [
2
] | [] | [] | [
"database",
"python",
"sql"
] | stackoverflow_0007939858_database_python_sql.txt |
Q:
Why do I get a runtime error with two linked gtk toggle buttons?
I have two toggle buttons that I want to link together so that pressing one releases the other one. So my signals look like this
def on_btn1_tgl_clicked(self, widget, data=None):
toggled = not self.btn2_toggle.get_active()
self.btn2_toggle.se... | Why do I get a runtime error with two linked gtk toggle buttons? | I have two toggle buttons that I want to link together so that pressing one releases the other one. So my signals look like this
def on_btn1_tgl_clicked(self, widget, data=None):
toggled = not self.btn2_toggle.get_active()
self.btn2_toggle.set_active(toggled)
def on_btn2_tgl_clicked(self, widget, data=None):
... | [
"When I run your code, I get this exception :\nRuntimeError: maximum recursion depth exceeded and the buttons doesn't work.\nMy explication is :\n\nWhen you click on button 1, it emit the toggled signal and execute your on_btn1_tgl_clicked() method.\n\nIn this method, you use gtk.ToggleButton.set_active() which emi... | [
2,
1,
0,
0
] | [] | [] | [
"gtk",
"pygtk",
"python",
"signals",
"togglebutton"
] | stackoverflow_0007941341_gtk_pygtk_python_signals_togglebutton.txt |
Q:
wxpython, basic UI Error, Button and listbox conflict?
I am having problems with wxpython. When I run the following code, it will show the listbox in a small form (it will only show the listbox in about 10x10). I do not know why this is happening and there is not much resources online to help me with this. The lis... | wxpython, basic UI Error, Button and listbox conflict? | I am having problems with wxpython. When I run the following code, it will show the listbox in a small form (it will only show the listbox in about 10x10). I do not know why this is happening and there is not much resources online to help me with this. The listbox will show correctly if i do not add any buttons. Pardon... | [
"The problem involves the parents. Your buttons' parent is the frame while the listbox's parent is the panel. Give the panel to the buttons as their parent too and the issue will go away. By the way, it's usually not a good idea to assign your own ID numbers, especially such low ones since those might be used. But ... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007947382_python_wxpython.txt |
Q:
Send commands to an interactive shell from Python
Is there a way to send command to another interactive shell ? Let's take the example of the meterpreter shell used in metasploit. Could it be a way to say command to this shell from python code, as soon as I get control of a computer and have a meterpreter shell to... | Send commands to an interactive shell from Python | Is there a way to send command to another interactive shell ? Let's take the example of the meterpreter shell used in metasploit. Could it be a way to say command to this shell from python code, as soon as I get control of a computer and have a meterpreter shell to play with ?
I mean All this from python code.
| [
"pexpect may be useful: http://pypi.python.org/pypi/pexpect/2.4\n",
"It will not be easy at all.\nYou will have to know if meterpreter has any means for other programs to communicate with it.\nIf it doesn't, you might want to go through hacking through it, e.g using OS pipes, etc to be able to get it to work.\nIn... | [
3,
0
] | [] | [] | [
"interactive",
"python",
"shell"
] | stackoverflow_0007953996_interactive_python_shell.txt |
Q:
Using python and xlrd, what is the best way to read 2 columns from a spreadsheet
I have an excel spreadsheet that has 2 columns. Something like this
|ColA | ColB |
|Key | Value |
|1 | test |
|2 | test2 |
|3 | test4 |
and I want to read these two columns into a dictionary. I currently have this worki... | Using python and xlrd, what is the best way to read 2 columns from a spreadsheet | I have an excel spreadsheet that has 2 columns. Something like this
|ColA | ColB |
|Key | Value |
|1 | test |
|2 | test2 |
|3 | test4 |
and I want to read these two columns into a dictionary. I currently have this working but can't figure out how to extract out each key value pair
sh = wb.sheet_by_inde... | [
"You're very close. If you want to build a dictionary from the a sheet that only contains keys and values, in the first two columns, you can simply do\nprint dict(sh.row_values(rownum) for rownum in range(sh.nrows))\n\nAs John Y mentioned, if you need to extract two specific columns with indexes i (keys) and j (va... | [
4
] | [] | [] | [
"dictionary",
"excel",
"python",
"xlrd"
] | stackoverflow_0007954338_dictionary_excel_python_xlrd.txt |
Q:
python multiprocess caller (as well as callee) invoked multiple times on windows XP
Possible Duplicate:
Multiprocessing launching too many instances of Python VM
I'm trying to use python multiprocess to parallelize web fetching, but I'm finding that the application calling the multiprocessing gets instantiated m... | python multiprocess caller (as well as callee) invoked multiple times on windows XP |
Possible Duplicate:
Multiprocessing launching too many instances of Python VM
I'm trying to use python multiprocess to parallelize web fetching, but I'm finding that the application calling the multiprocessing gets instantiated multiple times, not just the function I want called (which is a problem for me as the cal... | [
"Python multiprocessing module for Windows behaves slightly differently because Python doesn't implement os.fork() on this platform. In particular:\n\nSafe importing of main module\nMake sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a star... | [
1,
0
] | [] | [] | [
"multiprocess",
"python",
"windows_xp"
] | stackoverflow_0007953904_multiprocess_python_windows_xp.txt |
Q:
Why are my two django objects of the same type behaving differently?
Help!
I have two objects that i have created using different techniques in django;
>>> from django.contrib.contenttypes.models import ContentType
>>> from myproject.models import Building
Method A
>>> content_type = ContentType.objects.get(app_l... | Why are my two django objects of the same type behaving differently? | Help!
I have two objects that i have created using different techniques in django;
>>> from django.contrib.contenttypes.models import ContentType
>>> from myproject.models import Building
Method A
>>> content_type = ContentType.objects.get(app_label='myproject', model='Building')
>>> content_class = content_type.mode... | [
"The SQL query is only executed when you call content_query[0], so the query will fail at that point if something is wrong with content_class for example. At least I noticed that you forgot the objects from the first line:\ncontent_type = ContentType.objects.get(app_label='myproject', model='Building')\n\nEDIT: I g... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007954474_django_python.txt |
Q:
Python: Auto refresh local PHP file
I am trying to execute a basic script on my server to automatically run a PHP script every 45 seconds through Python:
import os
import time
while(1):
os.spawnl(os.P_NOWAIT, "twitter_clean.php")
print "checked twitter"
ti... | Python: Auto refresh local PHP file | I am trying to execute a basic script on my server to automatically run a PHP script every 45 seconds through Python:
import os
import time
while(1):
os.spawnl(os.P_NOWAIT, "twitter_clean.php")
print "checked twitter"
time.sleep(45)
The PHP is checking twitter... | [
"You should call PHP-Cli passing that file as parameter\nimport os\nimport time\n\nwhile(1): \n os.spawnl(os.P_NOWAIT, \"/path/to/php-cli twitter_clean.php\")\n print \"checked twitter\"\n time.sleep(45)\n\nAnd to keep it running, try to make it an Daemon: How d... | [
2,
1,
1,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0007954425_php_python.txt |
Q:
Sqlalchemy delete subquery
I am trying to delete some child rows using a filtered query without result:
sl = DBSession.query(Puesto.id).filter(Puesto.locales_id == id).subquery()
DBSession.query(Servicio).filter(Servicio.puestos_id.in_(sl)).delete()
I am getting InvalidRequestError: Could not evaluate current cri... | Sqlalchemy delete subquery | I am trying to delete some child rows using a filtered query without result:
sl = DBSession.query(Puesto.id).filter(Puesto.locales_id == id).subquery()
DBSession.query(Servicio).filter(Servicio.puestos_id.in_(sl)).delete()
I am getting InvalidRequestError: Could not evaluate current criteria in Python. Specify 'fetch... | [
"After looking in the source where your exception occurs I suggest trying this:\nsl = DBSession.query(Puesto.id).filter(Puesto.locales_id == id).subquery()\nDBSession.query(Servicio).filter(Servicio.puestos_id.in_(sl)) \\\n.delete(synchronize_session='fetch')\n\nSee the documentation of the delete method for what t... | [
98
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007892618_python_sqlalchemy.txt |
Q:
Using cx_freeze to combine 3 .py files into a standalone application?
I am building a PyQt GUI, and it has 3 files: one for the pictures, another that is the actual GUI, and another that actually starts the application.
I have tried py2exe, but since it is all written in Python 3.2 it didn't work. I am not at all ... | Using cx_freeze to combine 3 .py files into a standalone application? | I am building a PyQt GUI, and it has 3 files: one for the pictures, another that is the actual GUI, and another that actually starts the application.
I have tried py2exe, but since it is all written in Python 3.2 it didn't work. I am not at all familiar with cx_freeze and this project is already a week overdue, so if a... | [
"Might I advise that you use PyInstaller? I have found it way better than py2exe and cx_freeze when building exe packages. It even handles egg files. \n"
] | [
0
] | [] | [] | [
"cx_freeze",
"pyqt",
"python"
] | stackoverflow_0007954874_cx_freeze_pyqt_python.txt |
Q:
Reliably terminating subprocess on Python 2.5
I have a script that repeatedly runs an Ant buildfile and scrapes output into a parsable format. When I create the subprocess using Popen, there is a small time window where hitting Ctrl+C will kill the script, but will not kill the subprocess running Ant, leaving a z... | Reliably terminating subprocess on Python 2.5 | I have a script that repeatedly runs an Ant buildfile and scrapes output into a parsable format. When I create the subprocess using Popen, there is a small time window where hitting Ctrl+C will kill the script, but will not kill the subprocess running Ant, leaving a zombie that is printing output to the console that c... | [
"Call p.terminate() in your SIGTERM handler:\n if p.poll() is None: # Child still around?\n p.terminate() # kill it\n\n[EDIT] Since you're stuck with Python 2.5, use os.kill(p.pid, signal.SIGTERM) instead of p.terminate(). The check should make sure you don't get an exception (or reduce the number of times you... | [
2
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0007954870_python_subprocess.txt |
Q:
Python C API unicode arguments
I have a simple python script
import _tph
str = u'Привет, <b>мир!</b>' # Some unicode string with a russian characters
_tph.strip_tags(str)
and C library, which is compiled into _tph.so. This is a strip_tags function from it:
PyObject *strip_tags(PyObject *self, PyObject *args) {
... | Python C API unicode arguments | I have a simple python script
import _tph
str = u'Привет, <b>мир!</b>' # Some unicode string with a russian characters
_tph.strip_tags(str)
and C library, which is compiled into _tph.so. This is a strip_tags function from it:
PyObject *strip_tags(PyObject *self, PyObject *args) {
PyUnicodeObject *string;
Py_ss... | [
"The \"string\" argument here isn't well named. It is a pointer to a Python Unicode object, so your printf is seeing a lot of binary data (the object type, GC headers, the ref count, and the encoded unicode code points) until it happens to find a zero byte which printf interprets as the end of the string.\nThe sim... | [
6
] | [] | [] | [
"c",
"python",
"python_c_api",
"unicode"
] | stackoverflow_0007955250_c_python_python_c_api_unicode.txt |
Q:
How to loop through a list of strings to use them in a condition?
source = open("file1")
out = open("file2", "w")
days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
for line in source:
out.write(line)
if line.startswith('HERE IS WHERE I WOULD LIKE THE DAYS TO BE LOOPED'):
break
out.close(... | How to loop through a list of strings to use them in a condition? | source = open("file1")
out = open("file2", "w")
days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
for line in source:
out.write(line)
if line.startswith('HERE IS WHERE I WOULD LIKE THE DAYS TO BE LOOPED'):
break
out.close()
| [
"Since all your strings are the same length, you could do this:\nif line[:3] in days:\n break\n\nIf that's too much of an assumption:\nif any(line.startswith(day) for day in days):\n break\n\nAnother tip (assuming you're on Python 2.7 or 3.2:\nwith open(\"file1\") as source, open(\"file2\", \"w\") as out:\n ... | [
4,
4,
3,
1
] | [
"#Hackish, but works\nif min([line.find(x) for x in days]) == 0:\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0007955213_python.txt |
Q:
Vim with python support enviromental variables
If i type in the vim command line
:python import os;print os.getenv('PYTHONPATH')
I get a path
If i close vim and on the same terminal do
echo $PYTHONPATH
I get another completly different path
Why is this, where is vim getting this path?
This is relevant because th... | Vim with python support enviromental variables | If i type in the vim command line
:python import os;print os.getenv('PYTHONPATH')
I get a path
If i close vim and on the same terminal do
echo $PYTHONPATH
I get another completly different path
Why is this, where is vim getting this path?
This is relevant because the autocompletion can't find the modules thus it does... | [
"PYTHONPATH is a red herring: that's not what the virtualenv uses to configure itself. The virtualenv works by adding a prefix to PATH that points to the location of an alternate python executable, overriding the system python.\nThe problem with Vim is that the Python embedding does not look at the Python executabl... | [
4
] | [] | [] | [
"autocomplete",
"omnicomplete",
"python",
"vim"
] | stackoverflow_0007494285_autocomplete_omnicomplete_python_vim.txt |
Q:
Python 2.6.7 not initialing in windows
I am trying to get Python to run to use with Blender. I have 64 bit Vista SP2. 2.6.7 Python. When I start python the command prompt tells me this
'imprt site' failed; use -v for traceback
Traceback <most recent call last>:
File "c:\Python26\Scripts\pypm-script.py", line 5, in... | Python 2.6.7 not initialing in windows | I am trying to get Python to run to use with Blender. I have 64 bit Vista SP2. 2.6.7 Python. When I start python the command prompt tells me this
'imprt site' failed; use -v for traceback
Traceback <most recent call last>:
File "c:\Python26\Scripts\pypm-script.py", line 5, in <module>
Import Error: No module named pkg_... | [
"The file pypm-script.py (and pkg_resources) come from ActivePython. You probably must have installed a different Python on top of ActivePython. I can think of two ways to fix this problem:\n\nUninstall Python, remove C:\\Python26 and install ActivePython 2.6 (or 2.7), or\nRemove C:\\Python26\\Scripts\\pypm* and C:... | [
0
] | [] | [] | [
"activepython",
"pypm",
"python",
"setuptools"
] | stackoverflow_0007868215_activepython_pypm_python_setuptools.txt |
Q:
How do I intercept operations via subclassing?
I'm working through Learning Python 4th Edition and I'm currently working on the exercises for part VI of the book. The exercise I'm currently on is kind of confusing me and I was hoping I could get a little guidance as to how I can solve it.
Here's the prompt I'm wor... | How do I intercept operations via subclassing? | I'm working through Learning Python 4th Edition and I'm currently working on the exercises for part VI of the book. The exercise I'm currently on is kind of confusing me and I was hoping I could get a little guidance as to how I can solve it.
Here's the prompt I'm working with.
Subclassing. Make a subclass of MyList f... | [
"Hint:\ndef count(cls):\n for attr in (attr for attr in dir(cls) if not attr.startswith('_')):\n method = getattr(cls,attr)\n if callable(method):\n setattr(cls,attr,func_count(method,attr))\n return cls\n\n",
"Are your overloaded methods doing anything else besides counting the cal... | [
1,
1
] | [] | [] | [
"class",
"dry",
"oop",
"python"
] | stackoverflow_0007954864_class_dry_oop_python.txt |
Q:
How do the Selenium bindings work, and how do I use them?
Note: This may be more of a "meta" issue of how to understand documentation rather than a specific issue with the Selenium bindings themselves.
I'm looking at the Selenium Python bindings, and I'm a bit confused.
Most examples of how to start a simple insta... | How do the Selenium bindings work, and how do I use them? | Note: This may be more of a "meta" issue of how to understand documentation rather than a specific issue with the Selenium bindings themselves.
I'm looking at the Selenium Python bindings, and I'm a bit confused.
Most examples of how to start a simple instance of the browser require something like this:
from selenium i... | [
"webdriver.Firefox() is in fact webdriver.firefox.WebDriver.\nJust have a look on the code in selenium/webdriver/__init__.py and selenium/webdriver/firefox/webdriver.py, which inherits a lot from the RemoteWebDriver class.\nThere is a short introduction to the selenium python bindings, too. Have fun!\n"
] | [
2
] | [] | [] | [
"python",
"selenium",
"webdriver"
] | stackoverflow_0007952845_python_selenium_webdriver.txt |
Q:
python(scipy)-- setting an array element with a sequence error
i want to create a program which calculates the average of N random numbers taken from a uniform random number distribution.The program must run for
Ν=10,100,1000,10000,100000,1000000 random numbers.Then,i have to plot the mean value as
a function of N... | python(scipy)-- setting an array element with a sequence error | i want to create a program which calculates the average of N random numbers taken from a uniform random number distribution.The program must run for
Ν=10,100,1000,10000,100000,1000000 random numbers.Then,i have to plot the mean value as
a function of N.
I did this:
from scitools.std import *
import matplotlib.pyplot a... | [
"Compute the mean() before adding the random numbers to the distribution list. Then you have a simple plot of an n-element list. The problem is that you needed a list of scalars, not a list of arrays:\ndistribution=[]\nfor i in range(1,7): \n N*=10\n random_numbers=[random.uniform(0,1,size=N)] \n dis... | [
1,
1,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0007956251_python_scipy.txt |
Q:
How to test python library wrapping an external REST service (without hitting the service)
I'm writing a Python library to access Ubuntu One's REST API. (Yes, I know one already exists; this is a scratch-my-itch-and-learn-while-doing-it project.)
The library will be a relatively thin wrapper around the REST calls.... | How to test python library wrapping an external REST service (without hitting the service) | I'm writing a Python library to access Ubuntu One's REST API. (Yes, I know one already exists; this is a scratch-my-itch-and-learn-while-doing-it project.)
The library will be a relatively thin wrapper around the REST calls. I would like to be able to unit-test my library, without hitting U1 at all. What's the best pra... | [
"Your cutting point is the HTTP requests.\nWrite a mock library which intercepts the sending of the HTTP requests. Instead of sending them, convert them into a String and analyze them to test sending code.\nFor receiving code, mock the response handler. Save a good response from the REST server in a String and crea... | [
1
] | [] | [] | [
"mocking",
"python",
"unit_testing"
] | stackoverflow_0007955695_mocking_python_unit_testing.txt |
Q:
Using Visual Studio for Python Files
I have multiple python files for a school project that I want to open and edit in visual studio but to make it simple I want to have them all be a solution or project in visual studio, the code provided to me though was from my professor and he just used emacs to create all the... | Using Visual Studio for Python Files | I have multiple python files for a school project that I want to open and edit in visual studio but to make it simple I want to have them all be a solution or project in visual studio, the code provided to me though was from my professor and he just used emacs to create all the files. Is there a way I can have the dire... | [
"I haven't tried this myself yet, but did you look into Python Tools for Visual Studio? \nYou didn't specify which version of Visual Studio you are using. pytools is for VS 2010.\n"
] | [
5
] | [] | [] | [
"python",
"solution",
"visual_studio"
] | stackoverflow_0007956851_python_solution_visual_studio.txt |
Q:
Order by Count of OneToMany Elixir Relationship
I am using Elixir for ORM but I have a problem trying to Order by a Relationship.
What I am trying to do is to get a list of users sorted by the number of posts they have. I have tried ways such as
User.query.join(User.posts).order_by(func.count(User.posts)).all()
... | Order by Count of OneToMany Elixir Relationship | I am using Elixir for ORM but I have a problem trying to Order by a Relationship.
What I am trying to do is to get a list of users sorted by the number of posts they have. I have tried ways such as
User.query.join(User.posts).order_by(func.count(User.posts)).all()
without any success.
Here are my Elixir entities:
cla... | [
"this is a common question and an example query is in the ORM tutorial at: http://www.sqlalchemy.org/docs/orm/tutorial.html#using-subqueries . Just change where it says order_by(User.id) to say order_by(stmt.c.address_count):\n>>> from sqlalchemy.sql import func\n>>> stmt = session.query(Address.user_id, func.coun... | [
5
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0007954696_python_python_elixir_sqlalchemy.txt |
Q:
Python Subprocess Grep
I am trying to use the grep command in a python script using the subprocess module.
Here's what I have:
userid = 'foo12'
p = subprocess.Popen(['grep', "%s *.log"%userid], stdout=subprocess.PIPE)
And it returns nothing.
I am not entirely sure what I am doing wrong so can someone please expla... | Python Subprocess Grep | I am trying to use the grep command in a python script using the subprocess module.
Here's what I have:
userid = 'foo12'
p = subprocess.Popen(['grep', "%s *.log"%userid], stdout=subprocess.PIPE)
And it returns nothing.
I am not entirely sure what I am doing wrong so can someone please explain. The current method that ... | [
"I think you're running up against two problems:\n\nThis call:\np = subprocess.Popen(['grep', \"%s *.log\"%userid]...\n\nwill not work as expected without shell=True because the list of arguments are being passed directly to os.execvp, which requires each item to be a single string representing an argument. You've... | [
12,
11,
6
] | [] | [] | [
"grep",
"popen",
"python",
"subprocess"
] | stackoverflow_0007956865_grep_popen_python_subprocess.txt |
Q:
Getting all visible text from a webpage using Selenium
I've been googling this all day with out finding the answer, so apologies in advance if this is already answered.
I'm trying to get all visible text from a large number of different websites. The reason is that I want to process the text to eventually categor... | Getting all visible text from a webpage using Selenium | I've been googling this all day with out finding the answer, so apologies in advance if this is already answered.
I'm trying to get all visible text from a large number of different websites. The reason is that I want to process the text to eventually categorize the websites.
After a couple of days of research, I dec... | [
"Using lxml, you might try something like this:\nimport contextlib\nimport selenium.webdriver as webdriver\nimport lxml.html as LH\nimport lxml.html.clean as clean\n\nurl=\"http://www.yahoo.com\"\nignore_tags=('script','noscript','style')\nwith contextlib.closing(webdriver.Firefox()) as browser:\n browser.get(ur... | [
10,
5
] | [] | [] | [
"python",
"selenium_webdriver",
"webpage",
"xpath"
] | stackoverflow_0007947579_python_selenium_webdriver_webpage_xpath.txt |
Q:
OpenCV color identification
Hi I'm trying to built simple color identifying program. I have taken a image (yellow & pink) with and convert it in HSV color space. Then used threshold to identify yellow color region. I getting the output (black image). I want yellow region to be filled with while color and rest wit... | OpenCV color identification | Hi I'm trying to built simple color identifying program. I have taken a image (yellow & pink) with and convert it in HSV color space. Then used threshold to identify yellow color region. I getting the output (black image). I want yellow region to be filled with while color and rest with black.
IplImage *imgRead= c... | [
"I think the problem you are having is due to the scaling of the HSV data to fit in 8-bits. Normally, as I'm sure you noticed from using GIMP that HSV scales are as follows:\n\nH -> [0, 360]\nS -> [0, 100]\nV -> [0, 100]\n\n\nBut, OpenCV remaps these values as follows:\n\n(H / 2) -> [0, 180] (so that the H values c... | [
4,
2
] | [] | [] | [
"c",
"colors",
"opencv",
"python"
] | stackoverflow_0007950744_c_colors_opencv_python.txt |
Q:
Efficient string to hex function
I'm using an old version of python on an embedded platform ( Python 1.5.2+ on Telit platform ). The problem that I have is my function for converting a string to hex. It is very slow. Here is the function:
def StringToHexString(s):
strHex=''
for c in s:
strHex = st... | Efficient string to hex function | I'm using an old version of python on an embedded platform ( Python 1.5.2+ on Telit platform ). The problem that I have is my function for converting a string to hex. It is very slow. Here is the function:
def StringToHexString(s):
strHex=''
for c in s:
strHex = strHex + hexLoookup[ord(c)]
return ... | [
"Make your hexLoookup a dictionary indexed by the characters themselves, so you don't have to call ord each time.\nAlso, don't concatenate to build strings – that used to be slow. Use join on a list instead.\nfrom string import join\ndef StringToHexString(s):\n strHex = []\n\n for c in s:\n strHex.appe... | [
5,
2,
1,
1,
0
] | [] | [] | [
"hex",
"python"
] | stackoverflow_0007943919_hex_python.txt |
Q:
Enforce the use of 32-bit python
I am having some trouble triggering the 32-bit python for my macports python2.7
calvins-MacBook ttys003 Tue Nov 01 01:04:23 |~|
calvin$ arch -arch x86_64 python
Python 2.7.2 (default, Oct 31 2011, 20:10:35)
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.10.1)] on darw... | Enforce the use of 32-bit python | I am having some trouble triggering the 32-bit python for my macports python2.7
calvins-MacBook ttys003 Tue Nov 01 01:04:23 |~|
calvin$ arch -arch x86_64 python
Python 2.7.2 (default, Oct 31 2011, 20:10:35)
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.10.1)] on darwin
Type "help", "copyright", "credits"... | [
"arch -i386 python\n\nWill run the binary in 32-bit mode (which is what you did).\nIf you installed Python via MacPorts, check that it was actually built with 32-bit and 64-bit (universal binary).\nfile `which python`\n\nThis is output on mine:\nλ > file /usr/local/bin/python\n/usr/local/bin/python: Mach-O universa... | [
3
] | [] | [] | [
"macos",
"macports",
"python",
"python_2.7"
] | stackoverflow_0007957143_macos_macports_python_python_2.7.txt |
Q:
Clean Re-Install of Python on OSX & Linux
My various Python upgrades, both Ubuntu and OSX, are so gnarled that I can't escape with virtualenv 'cause virtualenv itself doesn't work. I want to lift off and nuke the site from orbit, it's the only way to be sure.
What is the easiest way to uninstall any upgrades, ret... | Clean Re-Install of Python on OSX & Linux | My various Python upgrades, both Ubuntu and OSX, are so gnarled that I can't escape with virtualenv 'cause virtualenv itself doesn't work. I want to lift off and nuke the site from orbit, it's the only way to be sure.
What is the easiest way to uninstall any upgrades, returning the machines to installed defaults, and ... | [
"To remove python installed from source:\nFirst try \nsudo make uninstall\n\nLast time I checked, Python's source Makefile does not come with an uninstall target, but just in case things have changed, it does not hurt to try this.\nAssuming that does not work, install checkinstall:\nsudo apt-get install checkinstal... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007956380_python.txt |
Q:
How to define date range that spans years, months in Django?
I have a Django model that contains a date field:
class Event(models.Model):
event_date = models.DateField()
I'd like to have a manager on this model that shows only the events that occurred within a time period defined as July 1 (CURRENT YEAR) to J... | How to define date range that spans years, months in Django? | I have a Django model that contains a date field:
class Event(models.Model):
event_date = models.DateField()
I'd like to have a manager on this model that shows only the events that occurred within a time period defined as July 1 (CURRENT YEAR) to June 31 (FOLLOWING YEAR).
So for this year, I'd want to return even... | [
"Straight from the docs:\nstart_date = datetime.date(2005, 1, 1)\nend_date = datetime.date(2005, 3, 31)\nEvent.objects.filter(event_date__range=(start_date, end_date)\n\nhttps://docs.djangoproject.com/en/dev/ref/models/querysets/#range\nSo the only challenge is figuring out what the current year is and adjusting th... | [
3
] | [] | [] | [
"date",
"django",
"filtering",
"model",
"python"
] | stackoverflow_0007957376_date_django_filtering_model_python.txt |
Q:
How do I compare python functions in terms of performance?
I have written 2 functions doing the exact same thing, but I don't know which one is faster and better. How do I compare these 2 functions to see which one is better in terms of performance and everything?
A:
The timeit module will do ya.
A:
Once you'v... | How do I compare python functions in terms of performance? | I have written 2 functions doing the exact same thing, but I don't know which one is faster and better. How do I compare these 2 functions to see which one is better in terms of performance and everything?
| [
"The timeit module will do ya.\n",
"Once you've found out which function is faster using the timeit module, you can also get more precise details of where the differences are by using the profile module.\n"
] | [
11,
4
] | [] | [] | [
"compare",
"function",
"performance",
"python"
] | stackoverflow_0007956834_compare_function_performance_python.txt |
Q:
know GMT difference
I have following code
ktm = timezone('Asia/Katmandu')
If I want to know zone of ktm, I can do like
ktm.zone
I know, Kathmandu is GMP+5:45. Is there any way to get this difference in pytz.
Thanks
A:
import pytz
import datetime as dt
ktm = pytz.timezone('Asia/Katmandu')
utc = pytz.utc
now = d... | know GMT difference | I have following code
ktm = timezone('Asia/Katmandu')
If I want to know zone of ktm, I can do like
ktm.zone
I know, Kathmandu is GMP+5:45. Is there any way to get this difference in pytz.
Thanks
| [
"import pytz\nimport datetime as dt\nktm = pytz.timezone('Asia/Katmandu')\nutc = pytz.utc\nnow = dt.datetime.now()\n\nnow_utc = utc.localize(now)\nnow_ktm = now_utc.astimezone(ktm)\n\ndiff = now_ktm.replace(tzinfo=None) - now_utc.replace(tzinfo=None) \nprint(diff)\n5:45:00\n\nThere is also:\nprint(now_ktm.strftime(... | [
1
] | [] | [] | [
"python",
"pytz"
] | stackoverflow_0007957218_python_pytz.txt |
Q:
Cannot install pyenchant on OSX
I am trying to install python bindings for the enchant library (pyenchant), according to the readme, it should be as simple as running python setup.py install
But when I try that, I get this error:
OSError: [Errno 2] No such file or directory: './tools/pyenchant-bdist-osx-sources/bu... | Cannot install pyenchant on OSX | I am trying to install python bindings for the enchant library (pyenchant), according to the readme, it should be as simple as running python setup.py install
But when I try that, I get this error:
OSError: [Errno 2] No such file or directory: './tools/pyenchant-bdist-osx-sources/build/lib'
Can someone tell me what to... | [
"You need to install the enchant library first. On the download page pyenchant indicates that it is a prerequisite if you are building from source. (There are pre-build binaries listed for python 2.5 and 2.6 as well.)\nI just installed enchant via homebrew on OS X 10.7 and then pyenchant installed without a proble... | [
5,
0
] | [] | [] | [
"macos",
"pyenchant",
"python"
] | stackoverflow_0003683181_macos_pyenchant_python.txt |
Q:
Error exception must derive from BaseException even when it does (Python 2.7)
What's wrong with the following code (under Python 2.7.1):
class TestFailed(BaseException):
def __new__(self, m):
self.message = m
def __str__(self):
return self.message
try:
raise TestFailed('Oops')
except T... | Error exception must derive from BaseException even when it does (Python 2.7) | What's wrong with the following code (under Python 2.7.1):
class TestFailed(BaseException):
def __new__(self, m):
self.message = m
def __str__(self):
return self.message
try:
raise TestFailed('Oops')
except TestFailed as x:
print x
When I run it, I get:
Traceback (most recent call last... | [
"__new__ is a staticmethod that needs to return an instance.\nInstead, use the __init__ method:\nclass TestFailed(Exception):\n def __init__(self, m):\n self.message = m\n def __str__(self):\n return self.message\n\ntry:\n raise TestFailed('Oops')\nexcept TestFailed as x:\n print x\n\n",
... | [
31,
25,
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0007957436_python.txt |
Q:
Does writing a file to disk with Python open().write() ensure the data is available to other processes?
One Python process writes status updates to a file for other processes to read. In some circumstances, the status updates happen repeatedly and quickly in a loop. The easiest and fastest approach is to use to op... | Does writing a file to disk with Python open().write() ensure the data is available to other processes? | One Python process writes status updates to a file for other processes to read. In some circumstances, the status updates happen repeatedly and quickly in a loop. The easiest and fastest approach is to use to open().write() in one line:
open(statusfile,'w').write(status)
An alternate approach with four lines that for... | [
"No, the first approach does not guarantee that the data is written out, since it is not guaranteed that the file will be flushed and closed once the handle is no longer referenced by its write member. This is likely the case with CPython, but not necessarily with other Python interpreters; it's an implementation d... | [
13,
0
] | [] | [] | [
"file_io",
"operating_system",
"python"
] | stackoverflow_0007955704_file_io_operating_system_python.txt |
Q:
Making a calculation based on the time module with Python
I am trying to output an altered time based on the "time" module in Py. For instance. I gather raw_input for the script from a user and based on that input I want to get system time and subtract a number of days from it and use that time for another step.
T... | Making a calculation based on the time module with Python | I am trying to output an altered time based on the "time" module in Py. For instance. I gather raw_input for the script from a user and based on that input I want to get system time and subtract a number of days from it and use that time for another step.
Thanks,
| [
"There are examples of all these steps here.\n",
"The datetime module is likely what you want.\nHere is an example:\n>>> from datetime import datetime, timedelta\n>>> s = raw_input('Input year month day hour minute second: ')\nInput year month day hour minute second: 2011 10 31 14 30 00\n'2011 10 31 14 30 00'\n>>... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007958031_python.txt |
Q:
More wxPython frustration - toolbars
I'm trying to add a toolbar to a window that can hold 128-pix png's (code below). I can get everything showing, but I just don't seem to be able to change the size of the icons. I've come across a similar post and tried the approach it suggests to overcome the problem but to no... | More wxPython frustration - toolbars | I'm trying to add a toolbar to a window that can hold 128-pix png's (code below). I can get everything showing, but I just don't seem to be able to change the size of the icons. I've come across a similar post and tried the approach it suggests to overcome the problem but to no avail.
Interestingly deleting the line a... | [
"If it is a Mac thing, you might be able to work around it by creating your own toolbar using a panel, a sizer and a set of BitmapButtons. I would think that that would work for you.\n"
] | [
0
] | [] | [] | [
"macos",
"python",
"toolbar",
"wxpython"
] | stackoverflow_0007918302_macos_python_toolbar_wxpython.txt |
Q:
Python RegEx Meaning
I'm new to python regular expressions and was wondering if someone could help me out by walking me through what this means (I'll state what I think each bit means here as well).
Thanks!
RegExp:
r'(^.*def\W*)(\w+)\W*\((.*)\):'
r'...' = python definition of regular expression within the ''
(...... | Python RegEx Meaning | I'm new to python regular expressions and was wondering if someone could help me out by walking me through what this means (I'll state what I think each bit means here as well).
Thanks!
RegExp:
r'(^.*def\W*)(\w+)\W*\((.*)\):'
r'...' = python definition of regular expression within the ''
(...) = a regex term
(^. = mat... | [
"It seems like a failed attempt to match a Python function signature:\nimport re\n\nregex = re.compile(r\"\"\" # r'' means that \\n and the like is two chars\n # '\\\\','n' and not a single newline character\n\n ( # begin capturing group #1; you can get it: regex.match(text).group(1)\n ... | [
6,
3,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007957846_python_regex.txt |
Q:
Use of csv.DictReader in Python to create a dictionary in memory where heading are keys and colums are lists
What is an elegant way to use csv.DictReader to create a dictionary in memory where the headers of the csv file are keys, and the columns are lists. domething like:
So, if the csv file is as follows:
key1 ... | Use of csv.DictReader in Python to create a dictionary in memory where heading are keys and colums are lists | What is an elegant way to use csv.DictReader to create a dictionary in memory where the headers of the csv file are keys, and the columns are lists. domething like:
So, if the csv file is as follows:
key1 key2 key3
1 6 9
2 7 10
3 8 11
The resulting dictionary will be:
{'key1': [1,2,3]... | [
"Your data format is not one that is easily parsed by csv. You could, however, just split the lines yourself:\nwith open(filename,'r') as f:\n keys=next(f).split()\n data=[row.split() for row in f]\n columns=map(list,zip(*data))\n result=dict(zip(keys,columns))\n\n",
"from collections import defaultdi... | [
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0007958077_csv_python.txt |
Q:
Good site for python documentation like ruby-doc.org
I love python, but I am disappointed in it's offerings for online documentation. Ruby seems to have many more documentation sites:
http://ruby-doc.org/docs/ProgrammingRuby/
http://api.rubyonrails.org/ (I know, this is rails, not just
Ruby)
http://apidock.com/ru... | Good site for python documentation like ruby-doc.org | I love python, but I am disappointed in it's offerings for online documentation. Ruby seems to have many more documentation sites:
http://ruby-doc.org/docs/ProgrammingRuby/
http://api.rubyonrails.org/ (I know, this is rails, not just
Ruby)
http://apidock.com/ruby/
I am of course aware of the official docs: http://doc... | [
"This is not another website, but is a different way to access the docs (and may even qualify as an api to the docs if you're being generous). All you need is a python interpreter:\nimport csv\nprint csv.__doc__\ndir(csv)\nprint csv.reader.__doc__\n\nI've found that this is a great way to do a quick check on exactl... | [
2,
0
] | [] | [] | [
"documentation",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0007955256_documentation_python_ruby_ruby_on_rails.txt |
Q:
Finding a key in a dictionary without knowing its full name
I have a dictionary with a key called ev#### where #### is some number that I do not know ahead of time. There is only one of this type of key in the dictionary and no other key starts with ev.
What's the cleanest way to access that key without knowing w... | Finding a key in a dictionary without knowing its full name | I have a dictionary with a key called ev#### where #### is some number that I do not know ahead of time. There is only one of this type of key in the dictionary and no other key starts with ev.
What's the cleanest way to access that key without knowing what the #### is?
| [
"You can try this list comprehension: (ideone)\nresult = [v for k, v in d.iteritems() if k.startswith('ev')][0]\n\nOr this approach using a generator expression: (ideone)\nresult = next(v for k, v in d.iteritems() if k.startswith('ev'))\n\nNote that these will both require a linear scan of the items in the dictiona... | [
4,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007958327_dictionary_python.txt |
Q:
Pixbuf overlapping / merge
Is there a way to overlap (but not overwrite) two gtk.gdk.Pixbuf in a gtk.IconView ?
For example, I've a cell with this pixbuf image : http://www.pirates-caraibes.com/media/zone/AnimMer.gif
I want to add this image : http://www.pirates-caraibes.com/media/objet/plage-coin-test12.gif to th... | Pixbuf overlapping / merge | Is there a way to overlap (but not overwrite) two gtk.gdk.Pixbuf in a gtk.IconView ?
For example, I've a cell with this pixbuf image : http://www.pirates-caraibes.com/media/zone/AnimMer.gif
I want to add this image : http://www.pirates-caraibes.com/media/objet/plage-coin-test12.gif to the cell, on the previous image (i... | [
"You can do it with the old GDK drawing API, but it disappeared in GTK 3. What works in both GTK 2 and 3 is to use the cairo API for that.\nhttp://developer.gnome.org/gdk/stable/gdk-Cairo-Interaction.html\nhttp://cairographics.org/samples/\nWhat adds the transparency is called the \"alpha\" channel, which stands ne... | [
0,
0
] | [] | [] | [
"gtk",
"pixbuf",
"pygtk",
"python"
] | stackoverflow_0007545060_gtk_pixbuf_pygtk_python.txt |
Q:
Cross Group (XG) Transactions and Further Explanation of use
The most recent release of the GAE states the following changes:
Datastore
Cross Group (XG) Transactions: For those who need transactional writes
to entities in multiple entity groups (and that's everyone, right?),
XG Transactions are just the thing... | Cross Group (XG) Transactions and Further Explanation of use | The most recent release of the GAE states the following changes:
Datastore
Cross Group (XG) Transactions: For those who need transactional writes
to entities in multiple entity groups (and that's everyone, right?),
XG Transactions are just the thing. This feature uses two phase commit
to make cross group writes ... | [
"Have you read any of the docs? It sounds like you haven't (based on you saying \"I can't seem to find any additional information\"). In that case, check out the links below and see if still have any questions.\nConceptually, doing a cross group transaction is pretty similar to a typical GAE transaction, just slo... | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"transactions"
] | stackoverflow_0007958494_google_app_engine_google_cloud_datastore_python_transactions.txt |
Q:
Parsing a text file and outputting to new file
I am a complete beginner to Python. I am coming across text files that I need to format. I basically need to take field data that starts with a certain character and output the field data to a new file which will have all the fields delimited by character of my choosi... | Parsing a text file and outputting to new file | I am a complete beginner to Python. I am coming across text files that I need to format. I basically need to take field data that starts with a certain character and output the field data to a new file which will have all the fields delimited by character of my choosing.
Here is a short example.
; Record 1
@FULLTEXT PA... | [
"It is unclear how the records are delimited and what exactly you would like to do with your output, but here is a simple parser that should get you started:\ns = '''\\\n; Record 1\n@FULLTEXT PAGE\n@T R000358\n@C ENDDOC# R000358\n@C BEGATTACH R000358\n@C ENDATTACH R000358\n@C MAILSTORE No\n@C AUTHOR \n@C BCC \n@C C... | [
1,
0,
0,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0007956152_parsing_python.txt |
Q:
Best way to send string data using python UDP packets?
To preface I'm very new to python (about 7 days) but I'm an experienced software eng undergrad.
I would like to send data between machines running python scripts. The idea I had (in order to simplify things) was to concatenate the data (strings & ints) into a ... | Best way to send string data using python UDP packets? | To preface I'm very new to python (about 7 days) but I'm an experienced software eng undergrad.
I would like to send data between machines running python scripts. The idea I had (in order to simplify things) was to concatenate the data (strings & ints) into a string and do the parsing client-side.
The UDP packets send... | [
"I highly suggest using Google Protocol Buffers as implemented in Python as protobuf for this as it will handle the serialization on both ends of the line. It has Python bindings that will allow you to easily use it with your existing Python program.\nUsing your example code you would create a .proto file like so:\... | [
1,
1,
0
] | [] | [] | [
"python",
"sockets",
"string",
"udp"
] | stackoverflow_0007958957_python_sockets_string_udp.txt |
Q:
Web application to sign PDF documents with digital certificates released by CAs
Immagine a web application written in python/django in which users authenticate with digital certificates via apache+mod_ssl (and a custom django authentication backend), how can they sign files then? The certificates are released by g... | Web application to sign PDF documents with digital certificates released by CAs | Immagine a web application written in python/django in which users authenticate with digital certificates via apache+mod_ssl (and a custom django authentication backend), how can they sign files then? The certificates are released by government approved CAs.
If I'm not wrong, a file needs to be signed with the private ... | [
"You are correct in that the web application requires access to the private key on the user's local computer or PKI store. I developed such a solution for a web application on the USAF network.\nUsers logon to USAF computer with their CAC Card containing their PKI credentials and private key. In our solution, we ne... | [
2,
0,
0
] | [] | [] | [
"certificate",
"cryptography",
"digital_signature",
"django",
"python"
] | stackoverflow_0007955410_certificate_cryptography_digital_signature_django_python.txt |
Q:
django runserver error while loading shared libraries: libssl.so.0.9.8: cannot open shared object file: No such file or directory
So yesterday I did a fresh install of Ubuntu11.10 but keeping my home directory with my virtualenvs, I installed virtual env and was able to logon my previous virtual env, but now when ... | django runserver error while loading shared libraries: libssl.so.0.9.8: cannot open shared object file: No such file or directory | So yesterday I did a fresh install of Ubuntu11.10 but keeping my home directory with my virtualenvs, I installed virtual env and was able to logon my previous virtual env, but now when I try to run python manage.py runserver under the virtualenv I get the following error:
error while loading shared libraries: libssl.so... | [
"I had the same error installing OpenStack on Ubuntu 11.10.\nRunning locate showed I only had version 1.0.0 and not 0.9.8\n$ locate libssl.so \n/lib/x86_64-linux-gnu/libssl.so.1.0.0\n/usr/lib/x86_64-linux-gnu/libssl.so.1.0.0\nI fixed it using: \n$sudo apt-get install libssl0.9.8\n",
"I fixed it by creating a new ... | [
6,
2
] | [] | [] | [
"django",
"linux",
"python",
"ubuntu"
] | stackoverflow_0007937225_django_linux_python_ubuntu.txt |
Q:
String date to date object in python
Possible Duplicate:
Parsing Dates and Times from Strings using python
I'm reading a string
"2011-06-11"
How can I cast this to a date object?
thanks
A:
If you know it will be in that format, you can use the strptime function:
datetime.datetime.strptime(s, "%Y-%m-%d").date(... | String date to date object in python |
Possible Duplicate:
Parsing Dates and Times from Strings using python
I'm reading a string
"2011-06-11"
How can I cast this to a date object?
thanks
| [
"If you know it will be in that format, you can use the strptime function:\ndatetime.datetime.strptime(s, \"%Y-%m-%d\").date()\n\n(and it's not a cast, you're actually creating a new date out of the string)\nIf you don't know the format of the date, I suggest looking at the dateutil module which provides a powerful... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007959417_python.txt |
Q:
Python while loop is keeps repeating
I am having some problems with the while loop. I am running it on eclipse, and I typed in the source:
a = raw_input("Mom im hungry!!!!!! FEED MEEEEE" )
while a != "Feed yourself":
print("Thats gross")
The result is when I type the wrong answer it responds by going:
Thats g... | Python while loop is keeps repeating | I am having some problems with the while loop. I am running it on eclipse, and I typed in the source:
a = raw_input("Mom im hungry!!!!!! FEED MEEEEE" )
while a != "Feed yourself":
print("Thats gross")
The result is when I type the wrong answer it responds by going:
Thats gross
thats gross
and so on.
| [
"What you really want is:\na = raw_input(\"Mom im hungry!!!!!! FEED MEEEEE\" )\nwhile a != \"Feed yourself\":\n print(\"Thats gross\")\n a = raw_input(\"Mom im hungry!!!!!! FEED MEEEEE\" ) # do something that may alter a !\n\nbecause without the 2nd line in the while loop...\n\nnothing alters the variable a, \... | [
5,
4,
2
] | [] | [] | [
"python",
"variables",
"while_loop"
] | stackoverflow_0007959494_python_variables_while_loop.txt |
Q:
completely abstract data source for an object?
I apologize in advance if this question is too general, or a solution exists that I haven't found via searching yet.
I was working on a simple REST server with web.py, and my backend was mysql, so I used sqlalchemy declarative objects. Everything works amazingly well... | completely abstract data source for an object? | I apologize in advance if this question is too general, or a solution exists that I haven't found via searching yet.
I was working on a simple REST server with web.py, and my backend was mysql, so I used sqlalchemy declarative objects. Everything works amazingly well, but I found myself tied pretty tightly to using a ... | [
"This might help you select an ORM for MongoDB:\nMongoDB ORM for Python?\nI find it hard to believe that any transition from a relational to a NoSQL database under the hood of an ORM would work seamlessly for any non-trivial project. However, if you actually need to migrate at some point there are some ORMs that ha... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007959166_python_sqlalchemy.txt |
Q:
Unicode with Pyramid, SQLAlchemy
I'm using Pyramid and SQLAlchemy, but the following simplified code:
u = u"\u201C"
m = M()
m.comment = u
m.user_id = 1
session.add( m )
session.commit()
gives me a
UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 0: ordinal not in range(256)
what... | Unicode with Pyramid, SQLAlchemy | I'm using Pyramid and SQLAlchemy, but the following simplified code:
u = u"\u201C"
m = M()
m.comment = u
m.user_id = 1
session.add( m )
session.commit()
gives me a
UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 0: ordinal not in range(256)
what do I need to fix this?
edit:
comment ... | [
"Most likely your comment column should be of type Unicode instead of String.\n",
"Check to see if your database's tables are encoded with an encoding other than unicode.\nAlso, if you want your comments be readable from phpMyAdmin (or whatever you are using to connect to your DB) you should append:\n?charset=utf... | [
4,
4
] | [] | [] | [
"pyramid",
"python",
"sqlalchemy"
] | stackoverflow_0007959105_pyramid_python_sqlalchemy.txt |
Q:
How to add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin
I created a Gedit 2 plugin which adds an item to a menu as described here. How could I bind a keyboard shortcut / accel key / accelerator key to this menu item?
A:
Following the given tutorial, your plugin have some lines ... | How to add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin | I created a Gedit 2 plugin which adds an item to a menu as described here. How could I bind a keyboard shortcut / accel key / accelerator key to this menu item?
| [
"Following the given tutorial, your plugin have some lines like the ones below somewhere:\nself._action_group = gtk.ActionGroup(\"ExamplePyPluginActions\")\nself._action_group.add_actions([(\"ExamplePy\", None, _(\"Clear document\"),\n None, _(\"Clear the document\"),\n self.on_clear_document_activa... | [
8
] | [] | [] | [
"gedit",
"gtk",
"keyboard_shortcuts",
"pygtk",
"python"
] | stackoverflow_0007959697_gedit_gtk_keyboard_shortcuts_pygtk_python.txt |
Q:
Django custom field - get model field from to_python method
Updated
I have the following custom field class:
class Binary(models.Field):
__metaclass__ = models.SubfieldBase
def get_prep_value(self, value):
return encryptAES(key, iv_random, str(value))
def to_python(self, value):
return va... | Django custom field - get model field from to_python method | Updated
I have the following custom field class:
class Binary(models.Field):
__metaclass__ = models.SubfieldBase
def get_prep_value(self, value):
return encryptAES(key, iv_random, str(value))
def to_python(self, value):
return value
def db_type(self, connection):
return 'VARBINARY(9... | [
"Based on the update to your question, what you're trying to do isn't really feasible. If you want the field to be able to encrypt/decrypt itself automatically, then all the information required to do so must be stored in the corresponding database field (see @DanielRoseman's answer). That essentially negates the u... | [
1,
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0007958452_django_django_admin_django_models_python.txt |
Q:
Application-specific PYTHONPATH
I have an application with a heirarchy of packages. There are a fair number of modules that reference other modules higher up in the package heirarchy. As exemplified below, I can use relative imports to solve this problem. However, running the module directly for testing fails w... | Application-specific PYTHONPATH | I have an application with a heirarchy of packages. There are a fair number of modules that reference other modules higher up in the package heirarchy. As exemplified below, I can use relative imports to solve this problem. However, running the module directly for testing fails with an Attempted relative import in n... | [
"You need to add __init__.py as empty files in folders that you'd want to do imports from. Doing this will cause python to treat the directories as packages, allowing you to use them in import statements:\n\\spam\n \\morespam\n __init__.py\n child.py\n __init__.py\n base.py\n\\eggs\n __ini... | [
1,
1
] | [] | [] | [
"python",
"pythonpath",
"sys.path"
] | stackoverflow_0006785496_python_pythonpath_sys.path.txt |
Q:
Tornado datetime
How would I create a datetime stamp from a clients offset? I have been messing around with this all day. The idea is to have a user login and based upon their timezone to create the cookie to expire after so long.
#!/usr/bin/env python
import tornado.auth
import tornado.database
import tornado.ht... | Tornado datetime | How would I create a datetime stamp from a clients offset? I have been messing around with this all day. The idea is to have a user login and based upon their timezone to create the cookie to expire after so long.
#!/usr/bin/env python
import tornado.auth
import tornado.database
import tornado.httpserver
import tornad... | [
"You could have a hidden datetime input pass the client's current time, including timezone, into the login form:\n<input type=\"hidden\" name=\"current_datetime\" />\n\nThat input's value can be populated with javascript.\nThen, in your post function, you can add hours or days to the value that current_datetime pas... | [
0
] | [] | [] | [
"datetime",
"offset",
"python",
"tornado"
] | stackoverflow_0007959730_datetime_offset_python_tornado.txt |
Q:
How do I avoid None as result of a query?
So I am trying to put the result of a query in a string. Let's say row by row (I don't need all the fields by the way), but that's not the point. I am using python against a sqlite db.
the problem is that when some of the fields are null, python will write None instead of ... | How do I avoid None as result of a query? | So I am trying to put the result of a query in a string. Let's say row by row (I don't need all the fields by the way), but that's not the point. I am using python against a sqlite db.
the problem is that when some of the fields are null, python will write None instead of "" or some blank neutral thing.
example:
t =... | [
"There is the str.replace option if \"None \" is unique to NULL fields:\n>>> \"string1 string2 None string4\".replace('None ', '')\n'string1 string2 string4'\n\nOr you can pre-filter the strings:\n>>> fields = ['string0', 'string1', 'string2', None, 'string4']\n>>> fields_out = filter(lambda f: f is not None, field... | [
0,
0,
0,
0
] | [] | [] | [
"null",
"python",
"sqlite",
"string"
] | stackoverflow_0007958213_null_python_sqlite_string.txt |
Q:
Is there a way to writing staticmethods to python classes outside of the classes without extending the class?
I would like to this in the use case of which I can keep my DB schema (of which are declared via classes) in SQLAlchemy. At the same time, I would like to various staticmethods or util methods to these obj... | Is there a way to writing staticmethods to python classes outside of the classes without extending the class? | I would like to this in the use case of which I can keep my DB schema (of which are declared via classes) in SQLAlchemy. At the same time, I would like to various staticmethods or util methods to these objects. But I would like to keep the schema clean and just be schema. Is there a way of writing these additional meth... | [
"Do you mean something like this (lol() is a static \"injected\" method)?\nclass Foo (object):\n pass\n\nFoo.lol = staticmethod (lambda: 1)\nprint Foo.lol ()\n\nYour question is not entirely clear.\n",
"As staticmethods in Python are nothing else than simple functions bound to a class, you can easily do it lik... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007959692_python.txt |
Q:
Playing with object creation
I have two classes with method foo:
Foo = type('Foo', (object,), {'foo': lambda s: 'Foo method'})
Bar = type('Bar', (object,), {'foo': lambda s: 'Bar method'})
And I have some other class which I need to be subclassed of one of the above classes according to the parameter.
My Solution... | Playing with object creation | I have two classes with method foo:
Foo = type('Foo', (object,), {'foo': lambda s: 'Foo method'})
Bar = type('Bar', (object,), {'foo': lambda s: 'Bar method'})
And I have some other class which I need to be subclassed of one of the above classes according to the parameter.
My Solution:
class Subject(object):
def _... | [
"I think most people would see the above code and recommend using composition rather than inheritance. Subject would define a foo method that dispatched to the correct class based on the boolean value.\nAlternatively, you could use a factory function to create either a Foo or Bar as needed.\ndef subject(selector):... | [
2,
1,
0
] | [] | [] | [
"factory",
"inheritance",
"oop",
"python",
"subclassing"
] | stackoverflow_0007959883_factory_inheritance_oop_python_subclassing.txt |
Q:
Controlling number of bytes read() at a time with Expat
I'm parsing some XML using Python's Expat (by calling parser = xml.parsers.expat.ParserCreate() and then setting the relevant callbacks to my methods).
It seems that when Expat calls read(nbytes) to return new data, nbytes is always 2,048. I have quite a lot ... | Controlling number of bytes read() at a time with Expat | I'm parsing some XML using Python's Expat (by calling parser = xml.parsers.expat.ParserCreate() and then setting the relevant callbacks to my methods).
It seems that when Expat calls read(nbytes) to return new data, nbytes is always 2,048. I have quite a lot of XML to process, and suspect that these small read()s are m... | [
"You're talking about the xmlparse.ParseFile method, right?\nUnfortunately, no, that value is hardcoded as BUF_SIZE = 2048 in pyexpat.c.\n"
] | [
2
] | [] | [] | [
"expat_parser",
"performance",
"python",
"xml"
] | stackoverflow_0007953708_expat_parser_performance_python_xml.txt |
Q:
Check if file is modified deleted or extended using python select.kqueue()
Hi I am having a hard time understanding how to use the BSD only python module classes select.kqueue and select.kevent to setup a watch for file write events.
I want to a python program to respond whenever a text file is written to by anoth... | Check if file is modified deleted or extended using python select.kqueue() | Hi I am having a hard time understanding how to use the BSD only python module classes select.kqueue and select.kevent to setup a watch for file write events.
I want to a python program to respond whenever a text file is written to by another process.
My test code goes as follows:
import os
myfd = os.open("/Use... | [
"Looking at the code for the watchdog module I came up with this . I dont know if the flags are necessary.\n#/usr/bin/env python\nimport select\nimport os\n\nkq = select.kqueue()\n# Use the OSX specific os.EVTONLY\n# http://code.google.com/p/python-watchdog/source/browse/src/watchdog/observers/kqueue.py\nfd = os.op... | [
0
] | [] | [] | [
"bsd",
"kqueue",
"polling",
"python"
] | stackoverflow_0007958397_bsd_kqueue_polling_python.txt |
Q:
How to import a class on the-fly-and Instantiate it as an object?
I know we could use exec to load a module ( from a string ) on-the-fly
e.g.
path = 'A.B'
class = 'C'
exec( "from %s import %s" %(path, class) )
but how I could instantiate it as an object c? btw, is above the best way to load a module from a stri... | How to import a class on the-fly-and Instantiate it as an object? | I know we could use exec to load a module ( from a string ) on-the-fly
e.g.
path = 'A.B'
class = 'C'
exec( "from %s import %s" %(path, class) )
but how I could instantiate it as an object c? btw, is above the best way to load a module from a string? it does not look very safe. thanks
regards,
John
| [
"For python<=2.6, you can use the built-in __import__ function:\nm = __import__('A.B', globals(), locals(), ['C'])\nC = getattr(m, 'C')\nc = C()\n\n",
"import importlib\nm = importlib.import_module('A.B')\nC = getattr(m, 'C')\nc = C()\n\nYou can get importlib from 2.7 standard library, if you're on a lower versio... | [
4,
1
] | [] | [] | [
"module",
"python"
] | stackoverflow_0007960321_module_python.txt |
Q:
What is efficient way to match words in string?
Example:
names = ['James John', 'Robert David', 'Paul' ... the list has 5K items]
text1 = 'I saw James today'
text2 = 'I saw James John today'
text3 = 'I met Paul'
is_name_in_text(text1,names) # this returns false 'James' in not in list
is_name_in_text(text2,name... | What is efficient way to match words in string? | Example:
names = ['James John', 'Robert David', 'Paul' ... the list has 5K items]
text1 = 'I saw James today'
text2 = 'I saw James John today'
text3 = 'I met Paul'
is_name_in_text(text1,names) # this returns false 'James' in not in list
is_name_in_text(text2,names) # this returns 'James John'
is_name_in_text(text... | [
"Make names into a set and use the in-operator for fast O(1) lookup.\nYou can use a regex to parse out the possible names in a sentence:\n>>> import re\n>>> findnames = re.compile(r'([A-Z]\\w*(?:\\s[A-Z]\\w*)?)')\n>>> def is_name_in_text(text, names):\n for possible_name in set(findnames.findall(text)):\n ... | [
5,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007960489_python.txt |
Q:
Setting date/time on a unix based server with Python (Paramiko module)
Okay, can someone tell what I'm doing wrong with this simple request to change the time? I'm on a win 7 machine, trying to change the time on a linux box. I can login, search logs and run other commands, of course adjusting my code below. But t... | Setting date/time on a unix based server with Python (Paramiko module) | Okay, can someone tell what I'm doing wrong with this simple request to change the time? I'm on a win 7 machine, trying to change the time on a linux box. I can login, search logs and run other commands, of course adjusting my code below. But this simple command is not changing the date/time. I must be overlooking some... | [
"Try changing this:\nrawcommand = 'date -s' + datetime_string\n\nTo this:\nrawcommand = 'date -s \"%s\"' % datetime_string\n\nAnd im not positive, but I dont think rawcommand.format(pattern=apattern) is necessary:\ndatetime_string = raw_input(\"Enter date and time in format 11/1/2011 1600\")\ncommand1 = 'date -s \"... | [
1,
1
] | [] | [] | [
"datetime",
"paramiko",
"python"
] | stackoverflow_0007960199_datetime_paramiko_python.txt |
Q:
numpy: can values not be assigned to a sub-array?
import numpy as np
a = np.zeros((3,2))
ind_row = np.array([0,1])
a[ind_row, 1]=3
now, a is, as expected:
[[ 0. 3.]
[ 0. 3.]
[ 0. 0.]]
I want to assign a value to a sub-array of a[ind_row, 1], and expect to be able to do this as follows:
a[ind_row, 1][1... | numpy: can values not be assigned to a sub-array? | import numpy as np
a = np.zeros((3,2))
ind_row = np.array([0,1])
a[ind_row, 1]=3
now, a is, as expected:
[[ 0. 3.]
[ 0. 3.]
[ 0. 0.]]
I want to assign a value to a sub-array of a[ind_row, 1], and expect to be able to do this as follows:
a[ind_row, 1][1] = 5
However, this leaves a unchanged! Why should I e... | [
"The problem here is that advanced indexing creates a copy of the array, and only the copy is modified. (This is in contrast to basic indexing, which results in a view into the original data.)\nWhen directly assigning to an advanced slice\na[ind_row, 1] = 3\n\nno copy is created, but when using\na[ind_row, 1][1] = ... | [
10
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0007960735_arrays_numpy_python.txt |
Q:
Creating writeable directory in Windows using Python os.makedirs
I need to create a subdirectory if it doesn't yet exist, then copy some files into it. However, whenever I try, I get a Permission denied error. I've tried chmod, with 777 as well as stat.S_IWRITE, I've tried os.system('attrib -r), but nothing works.... | Creating writeable directory in Windows using Python os.makedirs | I need to create a subdirectory if it doesn't yet exist, then copy some files into it. However, whenever I try, I get a Permission denied error. I've tried chmod, with 777 as well as stat.S_IWRITE, I've tried os.system('attrib -r), but nothing works. Can anyone help me work this one out? I know there is a similar quest... | [
"I think that shutil.copyfile needs the complete file name of the destination file, not just the directory.\nSo\nshutil.copyfile(oldfile, os.path.join(deleted, newpagename))\n\nshould do the trick.\n"
] | [
1
] | [] | [] | [
"chmod",
"permissions",
"python",
"windows"
] | stackoverflow_0007960982_chmod_permissions_python_windows.txt |
Q:
Getting a specific parent folder with Python
I already have this piece of functioning code, but after writing it I did feel the urge to scream "It's alive, it's alive!".
What I want to do is get the folder which has the folder "modules" as its parent folder, e.g. from /home/user/puppet/modules/impuls-test/template... | Getting a specific parent folder with Python | I already have this piece of functioning code, but after writing it I did feel the urge to scream "It's alive, it's alive!".
What I want to do is get the folder which has the folder "modules" as its parent folder, e.g. from /home/user/puppet/modules/impuls-test/templates/apache22/ I want /home/user/puppet/modules/impul... | [
"path = \"/home/user/puppet/modules/impuls-test/templates\"\ncomponents = path.split(os.sep)\nprint str.join(os.sep, components[:components.index(\"modules\")+2])\n\nprints\n/home/user/puppet/modules/impuls-test\n\n",
"Since os.path.normpath handles the \"..\" operator, you could just tack on a \"..\" and let nor... | [
8,
5,
1,
0
] | [] | [] | [
"directory",
"path",
"python"
] | stackoverflow_0006015721_directory_path_python.txt |
Q:
Python 3.2.1: Converting Entry to Number
I am, on my own, trying to create somewhat of a Python "The Price is Right". My problem is, I'm trying to convert the Entry to a number. See the code below:
...
Podium1Bid = Entry(Point(42.5, 35), 4)
Podium2Bid = Entry(Point(122.5, 35), 4)
Podium3Bid = Entry(Point(202.5,... | Python 3.2.1: Converting Entry to Number | I am, on my own, trying to create somewhat of a Python "The Price is Right". My problem is, I'm trying to convert the Entry to a number. See the code below:
...
Podium1Bid = Entry(Point(42.5, 35), 4)
Podium2Bid = Entry(Point(122.5, 35), 4)
Podium3Bid = Entry(Point(202.5, 35), 4)
Podium4Bid = Entry(Point(282.5, 35), ... | [
"I'm not sure exactly what's going on here with these PodiumBid objects, but the error:\nValueError: invalid literal for int() with base 10: ''\n\nsimply means python doesn't know how to convert an empty string to a number. int('') will raise the same exception.\nIf your intend for an empty string to be equal to 0... | [
3,
3
] | [] | [] | [
"graphics",
"numbers",
"python"
] | stackoverflow_0007961053_graphics_numbers_python.txt |
Q:
How to pop up download dialog box in browser from a Django project?
I am making a website using Django, and every time user clicks on the download button, I want download dialog box to appear in browser. I am using the following code for file download -
urllib.urlretrieve(filename)
In this case, although file is ... | How to pop up download dialog box in browser from a Django project? | I am making a website using Django, and every time user clicks on the download button, I want download dialog box to appear in browser. I am using the following code for file download -
urllib.urlretrieve(filename)
In this case, although file is getting downloaded, but the process happens in background. Moreover, file... | [
"Using django to return an attachment should serve this purpose. Here is an example of returning a csv file to the user. In the example at the top of the page here : https://docs.djangoproject.com/en/dev/howto/outputting-csv/?from=olddocs,\nYou can see that by setting \nresponse = HttpResponse(mimetype='text/csv')\... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007960577_django_python.txt |
Q:
Python query: how can I sort on a different variable than the filter
I have an event website with a query that should pick all the events that take place today or later. The problem is that some events take more than 1 day, so what I want the query to do is "pick all events with end date (until_date) equal to or l... | Python query: how can I sort on a different variable than the filter | I have an event website with a query that should pick all the events that take place today or later. The problem is that some events take more than 1 day, so what I want the query to do is "pick all events with end date (until_date) equal to or later than today, and sort them by start date (from_date)".
Unfortunately w... | [
"As the exception indicates, it's not possible to do this. You should either query for each day, sorted by start date (using a DateProperty so you can do an equality filter on end date), or do your query without the sort and sort the results in memory.\n"
] | [
0
] | [] | [] | [
"filter",
"google_app_engine",
"python"
] | stackoverflow_0007946296_filter_google_app_engine_python.txt |
Q:
Eclipse smart quotes - like in Textmate
Happy Friday — Does anyone know if eclipse has the notion of smart quotes like Textmate. The way it works is to select some words and quote them by simply hitting the " key? I'm a newbie here so be gentle. FWIW - I'm using pydev in Eclipse.
Thanks
Rephrase
What I am looki... | Eclipse smart quotes - like in Textmate | Happy Friday — Does anyone know if eclipse has the notion of smart quotes like Textmate. The way it works is to select some words and quote them by simply hitting the " key? I'm a newbie here so be gentle. FWIW - I'm using pydev in Eclipse.
Thanks
Rephrase
What I am looking for is given I have a word or phrase selec... | [
"For Java and XML files you can create a new template in Window / Preferences / Java / Editor / Templates. The template text could look something like this:\n\"${word_selection}${}\"${cursor}\n\nThen you can apply this template activate code completion using a standard Ctrl-Space (may have to hit it 2 or 3 times to... | [
2,
1,
0,
0,
0
] | [] | [] | [
"development_environment",
"eclipse",
"ide",
"pydev",
"python"
] | stackoverflow_0001730351_development_environment_eclipse_ide_pydev_python.txt |
Q:
GAE entity relationships: ancestor vs. reference prop. vs. list of keys
I'm working on a GAE Python app for running elections. I have an Election entity for each election. Each election will have around 2-20 candidates and I have a Candidate entity for each Candidate.
I'm considering three different options for ... | GAE entity relationships: ancestor vs. reference prop. vs. list of keys | I'm working on a GAE Python app for running elections. I have an Election entity for each election. Each election will have around 2-20 candidates and I have a Candidate entity for each Candidate.
I'm considering three different options for modeling the entity relationship:
Having the the Election be an ancestor of ... | [
"I assume a candidate may take part in more than one election and an election will have more than one candidates.\nThis is a M2M relationship, and the only efficient way to implement it is to use Listfields in App Engine. \nYou can try to use reference properties if you don't mind having multiple entities for a can... | [
2,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007949872_google_app_engine_python.txt |
Q:
bulkloader Listproperty utf8
I got a problem stuck me few days, tried several ways still can't figure it out.
it's about data upload using csv file in utf-8
here is main.Py
class hello(db.Model):
greeting = db.StringListProperty() (or Listproperty(unicode))
class dbLoader(bulkloader.Loader):
def __init... | bulkloader Listproperty utf8 | I got a problem stuck me few days, tried several ways still can't figure it out.
it's about data upload using csv file in utf-8
here is main.Py
class hello(db.Model):
greeting = db.StringListProperty() (or Listproperty(unicode))
class dbLoader(bulkloader.Loader):
def __init__(self):
bulkloader.Loade... | [
"Your data is being imported correctly. The stored entity is simply being displayed in Python's repr format, which represents unicode strings with characters outside the first 127 as unicode codepoints. Taking your second field, we get the same result with regular Python on the command line: \n$ echo 您好 | python -c... | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007949719_google_app_engine_python.txt |
Q:
Looking for something more pythonic
This looks really ugly, it there a way to make it look more pythonic?
if self.cleaned_data['string1_val'] == '' and latestSI.string1_val is None :
if self.cleaned_data['string2_val'] == '' and latestSI.string2_val is None :
return False
elif self.cleaned_data['st... | Looking for something more pythonic | This looks really ugly, it there a way to make it look more pythonic?
if self.cleaned_data['string1_val'] == '' and latestSI.string1_val is None :
if self.cleaned_data['string2_val'] == '' and latestSI.string2_val is None :
return False
elif self.cleaned_data['string2_val'] == latestSI.string2_val :
... | [
"def eq(x,y):\n return x == ('' if y is None else y)\n\nif eq(self.cleaned_data['string1_val'],latestSI.string1_val):\n return not eq(self.cleaned_data['string2_val'],latestSI.string2_val)\n\n\nHm. It looks like the question has changed. With the addition of the final else: True, the logic can be changed to\n... | [
2,
1,
1,
0
] | [] | [] | [
"django",
"python",
"refactoring"
] | stackoverflow_0007961216_django_python_refactoring.txt |
Q:
Python: Changing date format using regex
I am trying to change the date format in a text file so that it can be comma-delimited by Year, Month, and Day. Currently, it is in YYYY-MM-DD format and I am trying to replace the hyphens with commas without affecting the other hyphenated text in the file:
2011-1-1,59,44,2... | Python: Changing date format using regex | I am trying to change the date format in a text file so that it can be comma-delimited by Year, Month, and Day. Currently, it is in YYYY-MM-DD format and I am trying to replace the hyphens with commas without affecting the other hyphenated text in the file:
2011-1-1,59,44,29,55,42,26,93,80,66,30.15,30.05,29.96,10,8,4,1... | [
"Using fileinput is a convenient way to alter files \"in-place\":\nimport fileinput\nimport re\nimport sys\n\nfor line in fileinput.input(filename,inplace=True):\n sys.stdout.write(re.sub(r'(\\d{4})-(\\d{1,2})-(\\d{1,2})',r'\\1,\\2,\\3',line))\n\nre.sub was used to replace the hyphens with commas. The first rege... | [
2,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007961331_python_regex.txt |
Q:
in Python how do I print the result of a calculation and then save the result to a variable?
I am learning python and I am challenging myself to write a little program that asks the user the base price of a car, then saves the base price to a variable called base. It has two other variables called tax and license ... | in Python how do I print the result of a calculation and then save the result to a variable? | I am learning python and I am challenging myself to write a little program that asks the user the base price of a car, then saves the base price to a variable called base. It has two other variables called tax and license that are percentages. So it gets the base price, gets seven (7) percent of the base price, and add... | [
"In Python you can't do this in the same line. But what you can do is define the after_tax variable first, and then just print it out:\nafter_tax = base * tax / 100 + base\nprint \"\\nAfter taxes the price is: \", after_tax\n\n",
"you could do all your calculations up front. i recommend giving the variables (a, b... | [
3,
2
] | [] | [] | [
"command",
"printing",
"python",
"variables"
] | stackoverflow_0007961586_command_printing_python_variables.txt |
Q:
Sorting a list by frequency of letter in python (decreasing order)
Like the title says I need to write a function that will sort a list by frequency of letters. Normally I would supply my code with what I have so far but I have no idea where to get started. I'm sure its something simple but I just don't know wha... | Sorting a list by frequency of letter in python (decreasing order) | Like the title says I need to write a function that will sort a list by frequency of letters. Normally I would supply my code with what I have so far but I have no idea where to get started. I'm sure its something simple but I just don't know what to do. I need them sorted in decreasing order, any help is appreciate... | [
"in python 2.7 or higher you can use a counter:\nhttp://docs.python.org/dev/library/collections.html#collections.Counter\n>>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']\n>>> cnt = Counter(mywords)\n>>> cnt\nCounter({'blue': 3, 'red': 2, 'green': 1})\n\nas per Sorted Word frequency count using python\... | [
9,
4
] | [] | [] | [
"frequency",
"python"
] | stackoverflow_0007961629_frequency_python.txt |
Q:
Need help installing lxml on os x 10.7
I have been struggling to be able to do from lxml import etree (import lxml works fine by the way) The error is:
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/lxml/etree.so, 2): Symbol not found: _htmlParseChunk
... | Need help installing lxml on os x 10.7 | I have been struggling to be able to do from lxml import etree (import lxml works fine by the way) The error is:
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/lxml/etree.so, 2): Symbol not found: _htmlParseChunk
Referenced from: /Library/Frameworks/Python.... | [
"lxml is a bit fussy about what 3rd-party libraries it uses and it often needs newer versions than what are supplied by Apple. Suggest you read and follow the instructions here for building lxml from source on Mac OS X including building its own statically linked libs. That should work. (I'm a little surprised t... | [
12
] | [] | [] | [
"homebrew",
"libxml2",
"lxml",
"pip",
"python"
] | stackoverflow_0007961577_homebrew_libxml2_lxml_pip_python.txt |
Q:
Flask - WSGI process keeps crashing
I get strange errors when trying to deploy a Flask app (v0.8). I'm using apache's mod_wsgi, as suggested in the docs (almost to the letter). What's strange is that on some requests (simply accessing / via browser), the application loads fine, but very often I get a resource load... | Flask - WSGI process keeps crashing | I get strange errors when trying to deploy a Flask app (v0.8). I'm using apache's mod_wsgi, as suggested in the docs (almost to the letter). What's strange is that on some requests (simply accessing / via browser), the application loads fine, but very often I get a resource load errors (can't fetch some css or image), ... | [
"If you are getting Premature end of script headers, you are using daemon mode and the daemon process is crashing with a seg fault or similar.\nMake sure you aren't still loading mod_python.\nAlso try setting:\nWSGIApplicationGroup %{GLOBAL}\n\nto work around issues with Python C extension modules which aren't safe... | [
3
] | [] | [] | [
"flask",
"mod_wsgi",
"python"
] | stackoverflow_0007955891_flask_mod_wsgi_python.txt |
Q:
TemplateSyntaxError: 'if' statement improperly formatted
{% for frequency in patient_meds.frequency %}
{% if frequency == "7" %}
<td>Hellow</td>
{% endif %}
{% endfor%}
getting error
TemplateSyntaxError: 'if' statement improperly formatted
i don't know what i have to d... | TemplateSyntaxError: 'if' statement improperly formatted | {% for frequency in patient_meds.frequency %}
{% if frequency == "7" %}
<td>Hellow</td>
{% endif %}
{% endfor%}
getting error
TemplateSyntaxError: 'if' statement improperly formatted
i don't know what i have to do please help me...
| [
"If you're using the default version of Django included with app engine (v0.96), then try this syntax:\n{% for frequency in patient_meds.frequency %}\n {% ifequal frequency \"7\" %}\n <td>Hellow</td>\n {% endif %}\n{% endfor%}\n\n",
"In order to be able to use the == syntax in the {% if %... | [
6,
2,
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004898999_django_google_app_engine_python.txt |
Q:
what is the python(2.5.2)'s logging mechanism? is there log4j look a like library or standard class of python/geodjango will do?
I am planning to add logging mechanism in my python&geodjango web service.
Is there log4j look a like logging mechanism in python/geodjango?
I am looking for log4j's dailyrollingfileappe... | what is the python(2.5.2)'s logging mechanism? is there log4j look a like library or standard class of python/geodjango will do? | I am planning to add logging mechanism in my python&geodjango web service.
Is there log4j look a like logging mechanism in python/geodjango?
I am looking for log4j's dailyrollingfileappender equivalent. Then automatically delete all 1month old log files.
Any guidance is appreciated.
UPDATES1
I am thinking of the below ... | [
"Yes - Python 2.5 includes the 'logging' module. One of the handlers it supports is handlers.TimedRotatingFileHandler, this is what you're looking for. 'logging' is very easy to use:\nexample:\nimport logging\nimport logging.config\n\nlogging.fileConfig('mylog.conf')\nlogger = logging.getLogger('root')\n\nThe follo... | [
3
] | [] | [] | [
"geodjango",
"logging",
"python"
] | stackoverflow_0007961767_geodjango_logging_python.txt |
Q:
Using twill's builtin mechanize distribution throws AttributeError on _debug?
I use twill (0.9) and I want to also access its builtin mechanize distribution (on Python 2.6.6).
I read all the documentation and I'm not clear whether they even support or recommend that, if so they certainly don't publicize it.
It see... | Using twill's builtin mechanize distribution throws AttributeError on _debug? | I use twill (0.9) and I want to also access its builtin mechanize distribution (on Python 2.6.6).
I read all the documentation and I'm not clear whether they even support or recommend that, if so they certainly don't publicize it.
It seems you can do:
import _mechanize_dist as mechanize
br = mechanize.Browser()
br.open... | [
"The distribution of mechanize currently shipped with twill is ancient.\nRecently there has been activity on twill mailing list about upgrading it.\n"
] | [
0
] | [] | [] | [
"mechanize",
"python",
"twill"
] | stackoverflow_0007278103_mechanize_python_twill.txt |
Q:
Python curses - can't get TAB key
I need to catch TAB key in Python. For any other keys I do:
x = self.myscreen.getch()
if( x == curses.KEY_DOWN ):
# and so..
What's the constant for TAB key? I searched here (bottom of page) and tried every TAB contant.
I tried '\t' too. Is it possible? Thank you
A:
Try:
if (... | Python curses - can't get TAB key | I need to catch TAB key in Python. For any other keys I do:
x = self.myscreen.getch()
if( x == curses.KEY_DOWN ):
# and so..
What's the constant for TAB key? I searched here (bottom of page) and tried every TAB contant.
I tried '\t' too. Is it possible? Thank you
| [
"Try:\nif ( x == ord('\\t')):\n ...\n\nor \nif ( x == 9):\n ...\n\nYou need to be sure to convert the character to an integer with ord() before comparing to the value from getch \n"
] | [
7
] | [
"Try this it looks like what your asking For\n"
] | [
-3
] | [
"key",
"ncurses",
"python"
] | stackoverflow_0007924242_key_ncurses_python.txt |
Q:
List assignment out of index
I have the following program that assigns dictionary keys to an array ( addr[] ) and values to a corresponding array ( msg[] )
import smtplib
class item:
id = 0 # next available Item ID
def __init__(self,startBid,desc):
self.id = item.id
item.id += 1
... | List assignment out of index | I have the following program that assigns dictionary keys to an array ( addr[] ) and values to a corresponding array ( msg[] )
import smtplib
class item:
id = 0 # next available Item ID
def __init__(self,startBid,desc):
self.id = item.id
item.id += 1
self.highBid = startBid
se... | [
"In Python, you cannot assign to an index that does not already exist:\n>>> x = []\n>>> x[0] = True\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nIndexError: list assignment index out of range\n\nInstead of\naddr[j] = key\n\nTry\naddr.append(key)\n\nYou could do away with j altogethe... | [
4,
1,
0
] | [] | [] | [
"indexing",
"python"
] | stackoverflow_0007962094_indexing_python.txt |
Q:
filling in numpy array
I'm creating a numpy zero array of 10x5 and i wish to fill in each column with a shuffled list of numbers from 1-10. However I have a problem because it only fills in the first column and the list.pop() doesn't work plus i think my nested for loops even though i tried using the row and prefe... | filling in numpy array | I'm creating a numpy zero array of 10x5 and i wish to fill in each column with a shuffled list of numbers from 1-10. However I have a problem because it only fills in the first column and the list.pop() doesn't work plus i think my nested for loops even though i tried using the row and preferences in different order. A... | [
"Since you used pop in your example, I thought you may not want repeat within each column. numpy.random.shuffle shuffles elements in place.\n>>> M = N.repeat(N.arange(1,11), 5).reshape(10,-1)\n>>> M\narray([[ 1, 1, 1, 1, 1],\n [ 2, 2, 2, 2, 2],\n [ 3, 3, 3, 3, 3],\n [ 4, 4, 4, 4, ... | [
6,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007962033_numpy_python.txt |
Q:
I have a txt file. How can I take dictionary key values and print the line of text they appear in?
I have a txt file. I have written code that finds the unique words and the number of times each word appears in that file. I now need to figure out how to print the lines that those words apear in as well. How can... | I have a txt file. How can I take dictionary key values and print the line of text they appear in? | I have a txt file. I have written code that finds the unique words and the number of times each word appears in that file. I now need to figure out how to print the lines that those words apear in as well. How can I go about doing this?
Here is a sample output:
Analyze what file: itsy_bitsy_spider.txt
Concord... | [
"from collections import defaultdict\n\ntarget = 'itsy'\nword_summary = defaultdict(list)\nwith open('itsy.txt', 'r') as f:\n lines = f.readlines()\n\nfor idx, line in enumerate(lines):\n words = [w.strip().lower() for w in line.split()]\n for word in words:\n word_summary[word].append(idx)\n\nuniqu... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007961859_python.txt |
Q:
Example of implementation of Baum-Welch
I'm trying to learn about Baum-Welch algorithm(to be used with a hidden markov model). I understand the basic theory of forward-backward models, but it would be nice for someone to help explain it with some code(I find it easier to read code because I can play around to un... | Example of implementation of Baum-Welch | I'm trying to learn about Baum-Welch algorithm(to be used with a hidden markov model). I understand the basic theory of forward-backward models, but it would be nice for someone to help explain it with some code(I find it easier to read code because I can play around to understand it). I checked github and bitbucket ... | [
"Here's some code that I wrote several years ago for a class, based on the presentation in Jurafsky/Martin (2nd edition, chapter 6, if you have access to the book). It's really not very good code, doesn't use numpy which it absolutely should, and it does some crap to have the arrays be 1-indexed instead of just twe... | [
15
] | [] | [] | [
"algorithm",
"java",
"machine_learning",
"python",
"statistics"
] | stackoverflow_0007958738_algorithm_java_machine_learning_python_statistics.txt |
Q:
Python - Which data structure to use?
I have a large array of numerical data that I need to sort, insert, and move values backwards and forwards in the sorted order. I was previously using a simple array. Now each value has to be linked with an id (a unique int, just along for the ride).
Can I extend the array cla... | Python - Which data structure to use? | I have a large array of numerical data that I need to sort, insert, and move values backwards and forwards in the sorted order. I was previously using a simple array. Now each value has to be linked with an id (a unique int, just along for the ride).
Can I extend the array class, or do I need to use a list of tuples? W... | [
"You can just use a list for the sake of having a sorted - well - list. If you want to associate additional data, you could either use a tuple to store the data, or even create a custom object for it that stores the id in an additional field.\nYou shouldn’t need to extend the list for that, you can just put any obj... | [
3,
2,
1,
1
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0007961620_arrays_python.txt |
Q:
Google App Engine (python): Best way to determine if a query returns results or not
I'm using the webapp framework on GAE, and to show the results of a query, I'm doing a get() on the query object, then iterating on it if get() returned anything, for example:
query = Employee.all().filter("some_boolean_property = ... | Google App Engine (python): Best way to determine if a query returns results or not | I'm using the webapp framework on GAE, and to show the results of a query, I'm doing a get() on the query object, then iterating on it if get() returned anything, for example:
query = Employee.all().filter("some_boolean_property = ", True)
if query.get():
for employee in query:
# output employee.name etc.
... | [
"Just call fetch to get the number of results you need, then iterate over them. For example:\nquery = Employee.all().filter(\"some_boolean_property = \", True)\nresults = query.fetch(20)\nif results:\n for employee in results:\n # Do stuff\n\n",
"An alternative might be to set a flag inside the loop to ... | [
1,
0,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007931223_google_app_engine_python.txt |
Q:
pygtk: How to set the height of pop-up window in gtk.EntryCompletion
I use gtk.EntryCompletion to implement the autocomletion function.
But the list is so long that the pop-up window touches the bottom of screen.
And I cant find the method of set the height of pop-up window in doc of pygtk.
How to set the height o... | pygtk: How to set the height of pop-up window in gtk.EntryCompletion | I use gtk.EntryCompletion to implement the autocomletion function.
But the list is so long that the pop-up window touches the bottom of screen.
And I cant find the method of set the height of pop-up window in doc of pygtk.
How to set the height of pop-up window in gtk.EntryCompletion?
| [
"I don't know if this applies to gtk.EntryCompletion widgets, but for cell like widgets you can control their height with the cell.set_fixed_height_from_font(True) method. \nLook at the gtk.CellRendererText API for details. \n",
"Maybe you can solve the problem using gtk.EntryCompletion.set_minimum_key_length to ... | [
0,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0000961735_gtk_pygtk_python.txt |
Q:
React to key events while already reading from stdin in Python
Setup
I've been playing with a script to pipe tail -f into and highlight certain keywords. Not a big project but something I find useful.
Right now the main loop is basically:
...
line = True
while line:
line = sys.stdin.readline()
sys.stdout.w... | React to key events while already reading from stdin in Python | Setup
I've been playing with a script to pipe tail -f into and highlight certain keywords. Not a big project but something I find useful.
Right now the main loop is basically:
...
line = True
while line:
line = sys.stdin.readline()
sys.stdout.write(highlight(line))
...
I'd like to listen for certain keypresses... | [
"The simplest solution would be to avoid using a pipe from tail at all. Stick to using your stdin for user input, and instead write your tool so that it can open and follow the file you want to read from natively without using tail at all. tail's not a terribly complex tool if you just want to reimplement that part... | [
2
] | [] | [] | [
"keypress",
"pipe",
"python",
"stdin"
] | stackoverflow_0007963097_keypress_pipe_python_stdin.txt |
Q:
How can I call python program from VBA?
Just as the title goes.
I have a python program which processes some data file I downloaded from email.
I am writing a vba script which can download the email attachments and execute the python program to process the email attachments, such that I can automate my daily job.
... | How can I call python program from VBA? | Just as the title goes.
I have a python program which processes some data file I downloaded from email.
I am writing a vba script which can download the email attachments and execute the python program to process the email attachments, such that I can automate my daily job.
Any idea?
| [
"One way to do that is to turn your Python code into a COM Server and then access it like any other COM object. This chapter from Python Programming on Win32 shows how simple it can be. The rest of the chapter gets into a lot of technical details that are probably not necessary for your application. Just turn your ... | [
4,
1
] | [] | [] | [
"python",
"vba"
] | stackoverflow_0007963428_python_vba.txt |
Q:
Python sendmail error script
#!/usr/bin/python
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """From: From Person <from@fromdomain.com>
To: To Person <TEST@yahoo.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhos... | Python sendmail error script | #!/usr/bin/python
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """From: From Person <from@fromdomain.com>
To: To Person <TEST@yahoo.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, re... | [
"The only obvious thing that should not work is that SMTPException needs to be smtplib.SMTPException (or import it for unqualified use with from smtplib import SMTPException).\nOtherwise, after changing to my own (valid) addresses and my own SMTP server, your code works fine.\n"
] | [
7
] | [] | [] | [
"python",
"sendmail"
] | stackoverflow_0007961591_python_sendmail.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.