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:
QGraphicsView not displaying in QMainWindow
I'm not sure why this application is not displaying anything. I'll reproduce in a few lines to provide the gist of the issue. Using PyQt4
class SomeScene(QtGui.QGraphicsScene):
def __init__(self, parent = None):
QtGui.QGraphicsScene.__init__(self, parent)
pixmap = QtGui.QPixmap('someImage') # path is DEFINITELY valid
item = QGraphicsPixmapItem(pixmap)
self.addItem(item)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
... # code to set up window
scene = SomeScene()
view = QtGui.QGraphicsView(scene)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(view)
mainWidget = QtGui.QWidget()
mainWidget.setLayout(hbox)
self.setCentralWidget(mainWidget)
app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
This would just show a blank space.
A:
The view is blank because the scene has been destroyed. The scene is destroyed if it is not stored in a member variable. The view does not take ownership of the scene since a scene can have multiple views. With the example below, the tmpScene will be destroyed (causing a "tmpScene destroyed" message to be printed), but the self.scene will be used in the view and the pixmap item will be displayed.
import sys
from PyQt4 import QtGui
import sip
class SomeScene(QtGui.QGraphicsScene):
def __init__(self, parent = None):
QtGui.QGraphicsScene.__init__(self, parent)
pixmap = QtGui.QPixmap('someImage')
item = QtGui.QGraphicsPixmapItem(pixmap)
self.addItem(item)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
# This scene will be destroyed because it is local.
tmpScene = SomeScene()
tmpScene.destroyed.connect(self.onSceneDestroyed)
self.scene = SomeScene()
view = QtGui.QGraphicsView(self.scene)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(view)
mainWidget = QtGui.QWidget()
mainWidget.setLayout(hbox)
self.setCentralWidget(mainWidget)
def onSceneDestroyed(self, obj):
print 'tmpScene destroyed'
app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
| QGraphicsView not displaying in QMainWindow | I'm not sure why this application is not displaying anything. I'll reproduce in a few lines to provide the gist of the issue. Using PyQt4
class SomeScene(QtGui.QGraphicsScene):
def __init__(self, parent = None):
QtGui.QGraphicsScene.__init__(self, parent)
pixmap = QtGui.QPixmap('someImage') # path is DEFINITELY valid
item = QGraphicsPixmapItem(pixmap)
self.addItem(item)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
... # code to set up window
scene = SomeScene()
view = QtGui.QGraphicsView(scene)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(view)
mainWidget = QtGui.QWidget()
mainWidget.setLayout(hbox)
self.setCentralWidget(mainWidget)
app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
This would just show a blank space.
| [
"The view is blank because the scene has been destroyed. The scene is destroyed if it is not stored in a member variable. The view does not take ownership of the scene since a scene can have multiple views. With the example below, the tmpScene will be destroyed (causing a \"tmpScene destroyed\" message to be printe... | [
2
] | [] | [] | [
"frameworks",
"pyqt",
"python",
"qt",
"user_interface"
] | stackoverflow_0003664129_frameworks_pyqt_python_qt_user_interface.txt |
Q:
Publishing to a Facebook Page Wall - With Graph API?
I want to publish to the wall of a Facebook Fan Page, from a python/django web application.
The new Graph API looks nice and simple, so I'd like to use that. Unless there is a much easier way :-) I'm guessing the pyFacebook package would do want I want, but it appears to use the old rest interface. pyFacebook is probably a complete overkill for something that I should be able to do in just a few lines of code with the Graph API.
Looking at the new Graph API, it appears that this should be really simple. I've created an application, and I can publish to my applications wall with no problems. However, my application doesn't appear to have permissions to publish to my Fan Page. Any tips on how to enable this permission? Or is there a much better way to do this?
Do I even need my own application to do this, or is there one out there that I can already use?
A:
If your fan page allows wall posts from any user in its settings, your app should be able to just post to <page_id>/feed
If you are fan page admin and want to post on fan page's wall on behalf of the page itself (without showing your name), then read about it here or in more details here.
| Publishing to a Facebook Page Wall - With Graph API? | I want to publish to the wall of a Facebook Fan Page, from a python/django web application.
The new Graph API looks nice and simple, so I'd like to use that. Unless there is a much easier way :-) I'm guessing the pyFacebook package would do want I want, but it appears to use the old rest interface. pyFacebook is probably a complete overkill for something that I should be able to do in just a few lines of code with the Graph API.
Looking at the new Graph API, it appears that this should be really simple. I've created an application, and I can publish to my applications wall with no problems. However, my application doesn't appear to have permissions to publish to my Fan Page. Any tips on how to enable this permission? Or is there a much better way to do this?
Do I even need my own application to do this, or is there one out there that I can already use?
| [
"If your fan page allows wall posts from any user in its settings, your app should be able to just post to <page_id>/feed\nIf you are fan page admin and want to post on fan page's wall on behalf of the page itself (without showing your name), then read about it here or in more details here.\n"
] | [
6
] | [] | [] | [
"django",
"facebook",
"facebook_graph_api",
"python"
] | stackoverflow_0003664195_django_facebook_facebook_graph_api_python.txt |
Q:
What kind of python process to monitor a queueing system like kestrel or rabbitmq?
I'm fairly new to python, and I was wondering what kind of application would you create to constanstly monitor a queueing service like kestrel or rabbitmq?
How would it run, and under what context? Would it be a simple python script that would have a infinit while loop?
I'm looking for a long running, stable python service that would respond to incoming messages from either rabbitmq or kestrel. I want this to be as light weight as possible, but stable and something you can rely on to be running.
A:
Sounds like you're wanting to implement an event loop. The simplest of these are indeed implemented with what's basically a while True: (and then having some shutdown handler that can break out of the loop if it's time to exit by request or some such).
| What kind of python process to monitor a queueing system like kestrel or rabbitmq? | I'm fairly new to python, and I was wondering what kind of application would you create to constanstly monitor a queueing service like kestrel or rabbitmq?
How would it run, and under what context? Would it be a simple python script that would have a infinit while loop?
I'm looking for a long running, stable python service that would respond to incoming messages from either rabbitmq or kestrel. I want this to be as light weight as possible, but stable and something you can rely on to be running.
| [
"Sounds like you're wanting to implement an event loop. The simplest of these are indeed implemented with what's basically a while True: (and then having some shutdown handler that can break out of the loop if it's time to exit by request or some such).\n"
] | [
0
] | [] | [] | [
"python",
"queue"
] | stackoverflow_0003664536_python_queue.txt |
Q:
Django Permissions and Security for Basic Chat App
If I wanted to implement some sort of chat tool in my django webapp, implemented with basic ajax polling as opposed to comet, what should I do to secure it, besides running over SSL. Should I just use the permissions app for each chat session and generate a random token to be accessed in my urlconf? Are there better/different approaches to this sort of thing?
A:
I think I could just make a room model with a ManytoMany Field indicating users, a queue for the chat history, and as users leave, I'd just remove their username from that model. So, when submitting post requests, I could just use the cookie in django.contrib.auth for sessions to validate data transfer. I think that should be secure, so that illegal users can't generate their own post request for the data.
| Django Permissions and Security for Basic Chat App | If I wanted to implement some sort of chat tool in my django webapp, implemented with basic ajax polling as opposed to comet, what should I do to secure it, besides running over SSL. Should I just use the permissions app for each chat session and generate a random token to be accessed in my urlconf? Are there better/different approaches to this sort of thing?
| [
"I think I could just make a room model with a ManytoMany Field indicating users, a queue for the chat history, and as users leave, I'd just remove their username from that model. So, when submitting post requests, I could just use the cookie in django.contrib.auth for sessions to validate data transfer. I think th... | [
0
] | [] | [] | [
"chat",
"django",
"permissions",
"python",
"security"
] | stackoverflow_0003664519_chat_django_permissions_python_security.txt |
Q:
Sqlalchemy seems to commit changes when it's not supposed to
Consider the following snippet of Python code:
from sqlalchemy import *
from sqlalchemy.orm import *
db = create_engine('postgresql:///database', isolation_level='SERIALIZABLE')
Session = scoped_session(sessionmaker(bind=db, autocommit=False))
s = Session()
s.add(SomeInstance())
s.flush()
raw_input('Did it work? ')
It connects to the database, adds SomeInstance to the session, flushes, and then pauses. At this point, if I psql into my database, I would see that the instance has already been inserted -- even though autocommit is False and I haven't committed the session yet!
Any idea what I might be doing wrong?
Thanks!
A:
Nevermind, there was a bug in the psycopg2.py implementation in sqlalchemy 0.6.3; upgrading to 0.6.4 solved this problem.
| Sqlalchemy seems to commit changes when it's not supposed to | Consider the following snippet of Python code:
from sqlalchemy import *
from sqlalchemy.orm import *
db = create_engine('postgresql:///database', isolation_level='SERIALIZABLE')
Session = scoped_session(sessionmaker(bind=db, autocommit=False))
s = Session()
s.add(SomeInstance())
s.flush()
raw_input('Did it work? ')
It connects to the database, adds SomeInstance to the session, flushes, and then pauses. At this point, if I psql into my database, I would see that the instance has already been inserted -- even though autocommit is False and I haven't committed the session yet!
Any idea what I might be doing wrong?
Thanks!
| [
"Nevermind, there was a bug in the psycopg2.py implementation in sqlalchemy 0.6.3; upgrading to 0.6.4 solved this problem.\n"
] | [
2
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0003664624_postgresql_python_sqlalchemy.txt |
Q:
When using paster web server, does it service requests by creating a new thread?
Does paster create a new thread per request?
Can you set the maximum number of threads for paster to use i.e. a thread pool? How can you if this is possible?
A:
Per the docs, paster supports different server choices, depending on the configuration -- including wsgiutils, "the start of support for twisted.web2 ... patches welcome" (that would be an async server instad), and "SCGI, FastCGI and AJP protocols, for connection an external web server (like Apache) to your application. Both threaded and forking versions are available. This is based on flup."
You can configure maximum number of threads (and/or forked processes) on Apache, for example, and quite independently from paster, by working exclusively on the Apache configuration; clearly that is what you'll want to do if you've picked the flup/Apache/threaded combo.
At (roughly) the other extreme in the simplicity / functionality spectrum, I don't believe wsgiutils, out of the box, can be configured to use a thread pool (i.e., if I'm not mistaken, coding a new server kind around the minimal skeleton that wsgiutil provides would be needed to use a thread pool with it).
Clearly, if you need any kind of advanced configuration options, Apache's enormous power and flexibility are hard to beat:-).
| When using paster web server, does it service requests by creating a new thread? | Does paster create a new thread per request?
Can you set the maximum number of threads for paster to use i.e. a thread pool? How can you if this is possible?
| [
"Per the docs, paster supports different server choices, depending on the configuration -- including wsgiutils, \"the start of support for twisted.web2 ... patches welcome\" (that would be an async server instad), and \"SCGI, FastCGI and AJP protocols, for connection an external web server (like Apache) to your app... | [
1
] | [] | [] | [
"paster",
"python"
] | stackoverflow_0003664656_paster_python.txt |
Q:
What is the use of FieldStorage in Python
I want to know whats the difference between FieldStorage in Python and wsgi_input?
A:
FieldStorage is useful in CGI contexts and can help in some other cases in which you want to do your own parsing and handling of (e.g.) a form posted (or also sent by a GET;-) to your server, without necessarily involving WSGI in any way. It provided a nicely accessible, somewhat dict-like object for accessing the form data (whether in a POST or GET context).
I'm not sure what wsgi_input (with an underscore) is; if you mean wsgi.input (with a dot, and, normally, quotes around it;-), it's a key in a WSGI environment whose value must be, quoting from PEP 333:
An input stream (file-like object)
from which the HTTP request body can
be read.
So it only exists in a WSGI context and does not imply that any parsing of that request body has been done -- parsing of the request body (to receive POSTs, specifically), if any, must happen "using" that stream.
| What is the use of FieldStorage in Python | I want to know whats the difference between FieldStorage in Python and wsgi_input?
| [
"FieldStorage is useful in CGI contexts and can help in some other cases in which you want to do your own parsing and handling of (e.g.) a form posted (or also sent by a GET;-) to your server, without necessarily involving WSGI in any way. It provided a nicely accessible, somewhat dict-like object for accessing th... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003664742_python_python_3.x.txt |
Q:
Django profiling module error
I have an error from the following code. I am sure it is obviuous to someone with more Python experience. This is a snippet from http://djangosnippets.org/snippets/727/
import sys
import cProfile
from cStringIO import StringIO
from django.conf import settings
class ProfilerMiddleware(object):
def process_view(self, request, callback, callback_args, callback_kwargs):
if settings.DEBUG and 'prof' in request.GET:
self.profiler = cProfile.Profile()
args = (request,) + callback_args
return self.profiler.runcall(callback, *args, **callback_kwargs)
def process_response(self, request, response):
if settings.DEBUG and 'prof' in request.GET:
self.profiler.create_stats()
out = StringIO()
old_stdout, sys.stdout = sys.stdout, out
self.profiler.print_stats(1)
sys.stdout = old_stdout
response.content = '<pre>%s</pre>' % out.getvalue()
return response
I have implemented it as middleware and get the following error on pages.
Traceback (most recent call last):
File "c:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 280, in run
self.result = application(self.environ, self.start_response)
File "c:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 674, in __call__
return self.application(environ, start_response)
File "c:\Python26\lib\site-packages\django\core\handlers\wsgi.py", line 245, in __call__
response = middleware_method(request, response)
File "C:\Users\Richard\workspace\race\src\race\..\race\middleware\ProfilerMiddleware.py", line 15, in process_response
self.profiler.create_stats()
AttributeError: 'ProfilerMiddleware' object has no attribute 'profiler'
Any ideas?
A:
Thanks for your input Seth and Nick,
I fixed it. I don't understand what caused it but it is to do with the order my middleware is called in.
I debugged it based on Nick's comment that process_view hadn't been called to create the object. (I'm still not used to Python error messages to pick it up!) I got rid of process_response function and put a print statement in process_view and sure enough, the print statement was not output on the dev console proving process_view wasn't getting called. I suspected middleware settings order and got lucky.
I had settings as follows with these being the last 2 lines of my middleware setting:
Not working:
'firepython.middleware.FirePythonDjango',
'race.middleware.ProfilerMiddleware.ProfilerMiddleware',
Working:
'race.middleware.ProfilerMiddleware.ProfilerMiddleware',
'firepython.middleware.FirePythonDjango',
No idea why this is the case. I have some funny stuff going on with FirePython sometimes as well so maybe it's related. I have learned a bit so maybe stand a better chance of fixing FirePython as a result.
Thanks guys
Rich
| Django profiling module error | I have an error from the following code. I am sure it is obviuous to someone with more Python experience. This is a snippet from http://djangosnippets.org/snippets/727/
import sys
import cProfile
from cStringIO import StringIO
from django.conf import settings
class ProfilerMiddleware(object):
def process_view(self, request, callback, callback_args, callback_kwargs):
if settings.DEBUG and 'prof' in request.GET:
self.profiler = cProfile.Profile()
args = (request,) + callback_args
return self.profiler.runcall(callback, *args, **callback_kwargs)
def process_response(self, request, response):
if settings.DEBUG and 'prof' in request.GET:
self.profiler.create_stats()
out = StringIO()
old_stdout, sys.stdout = sys.stdout, out
self.profiler.print_stats(1)
sys.stdout = old_stdout
response.content = '<pre>%s</pre>' % out.getvalue()
return response
I have implemented it as middleware and get the following error on pages.
Traceback (most recent call last):
File "c:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 280, in run
self.result = application(self.environ, self.start_response)
File "c:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 674, in __call__
return self.application(environ, start_response)
File "c:\Python26\lib\site-packages\django\core\handlers\wsgi.py", line 245, in __call__
response = middleware_method(request, response)
File "C:\Users\Richard\workspace\race\src\race\..\race\middleware\ProfilerMiddleware.py", line 15, in process_response
self.profiler.create_stats()
AttributeError: 'ProfilerMiddleware' object has no attribute 'profiler'
Any ideas?
| [
"Thanks for your input Seth and Nick,\nI fixed it. I don't understand what caused it but it is to do with the order my middleware is called in. \nI debugged it based on Nick's comment that process_view hadn't been called to create the object. (I'm still not used to Python error messages to pick it up!) I got rid of... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003664817_django_python.txt |
Q:
Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx
Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx such filter, value_list or ...
A:
Probably most pythonic way:
myset = Customer.objects.filter(<something>).order_by(<something>)
first, last = myset[0], myset.reverse()[0]
A:
What's the best ,fastest way to get only first and last
Let us see.
customers = Customer.objects.filter(**conditions)
first = customers.order_by('id')[0]
last = customers.latest('id')
Of course if you can come up with an SQL query to do this it could be executed using the raw() method.
query = "<your query to get first and last>"
Customer.objects.raw(query)
A:
I am not totally familiar with the inner workings of django but I would assume the fastest way to do this would be:
elements = Customer.objects.filter(<something>)
first_element = elements[0]
last_element = elements[-1]
| Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx | Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx such filter, value_list or ...
| [
"Probably most pythonic way:\nmyset = Customer.objects.filter(<something>).order_by(<something>)\nfirst, last = myset[0], myset.reverse()[0]\n\n",
"\nWhat's the best ,fastest way to get only first and last \n\nLet us see. \ncustomers = Customer.objects.filter(**conditions)\nfirst = customers.order_by('id')[0]\nla... | [
10,
4,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003664708_django_django_models_python.txt |
Q:
Python 3 I think I have a type mismatch but can't find it
I'm using Python 3.1 to write a simple game involving naming state capitols. I think I have some kind of type mismatch but I don't know what it is.
I think it's when I compare the player's answer to the real answer, but don't know how to make it right.
from random import *
states = {}
print ("Guess State Capitols")
statefile = open("state capitols.csv")
for line in statefile:
(state,capitol) = line.split(",")
states[state] = capitol
statefile.close()
guessnum = randint(1,50)
names = list(states.keys())
guess = names[guessnum]
print("What is the capitol of " + guess)
playerguess = input()
if playerguess == str(states[guess]):
print("Yes You are right!")
print("No you are wrong")
print(str(states[guess]))
It's at
if playerguess == str(states[guess]):
but I don't know what I am doing wrong, in that even when I have the answer right, it says I'm wrong, but prints the same answer I typed in.
I know it's a newbie question, but would appreciate any help.
(I also know that the line "no you are wrong" would print in any case, but I'll fix that later).
A:
You can use two "prints" to debug it:
print(playerguess)
print(states[guess])
this should give you the hint.
I would say that when you got your capitol from your csv file you didnt take out the newline.
So maybe this will work:
for line in statefile:
(state, capitol) = line.strip().split(",")
states[state] = capitol
statefile.close()
A:
If you have a type mismatch then you will get a traceback with lots of useful information. I'll assume that since you haven't posted one you didn't get a traceback, so it isn't a type mismatch.
When you're trying to find a problem like this you should try printing the repr() of the string:
print(repr(playerguess))
print(repr(states[guess]))
That will show you exactly what is in each string, including any trailing whitespace or newlines.
| Python 3 I think I have a type mismatch but can't find it | I'm using Python 3.1 to write a simple game involving naming state capitols. I think I have some kind of type mismatch but I don't know what it is.
I think it's when I compare the player's answer to the real answer, but don't know how to make it right.
from random import *
states = {}
print ("Guess State Capitols")
statefile = open("state capitols.csv")
for line in statefile:
(state,capitol) = line.split(",")
states[state] = capitol
statefile.close()
guessnum = randint(1,50)
names = list(states.keys())
guess = names[guessnum]
print("What is the capitol of " + guess)
playerguess = input()
if playerguess == str(states[guess]):
print("Yes You are right!")
print("No you are wrong")
print(str(states[guess]))
It's at
if playerguess == str(states[guess]):
but I don't know what I am doing wrong, in that even when I have the answer right, it says I'm wrong, but prints the same answer I typed in.
I know it's a newbie question, but would appreciate any help.
(I also know that the line "no you are wrong" would print in any case, but I'll fix that later).
| [
"You can use two \"prints\" to debug it:\nprint(playerguess)\nprint(states[guess])\n\nthis should give you the hint. \nI would say that when you got your capitol from your csv file you didnt take out the newline.\nSo maybe this will work:\nfor line in statefile:\n (state, capitol) = line.strip().split(\",\")\n ... | [
2,
0
] | [] | [] | [
"file_io",
"python",
"string"
] | stackoverflow_0003665538_file_io_python_string.txt |
Q:
How is Ruby more object-oriented than Python?
Matz, who invented Ruby, said that he designed the language to be more object-oriented than Python. How is Ruby more object-oriented than Python?
A:
If you take the Python from 1993 and compare it with Ruby then the latter is more object oriented. However, after the overhaul in Python 2.2 this is no longer true. I'd say that modern Python is as object oriented as it gets.
A:
One example that's commonly given is len, which in Python is a built-in function. You may implement a special __len__ method in your objects which will be called by len, but len is still a function. In Ruby, objects just have the .length property/method so it appears more object oriented when you say obj.length rather than len(obj) although deep under the hood pretty much the same thing happens.
That said, over the years Python have moved towards more object-orientation. Currently all objects (and implicitly user-defined objects) inherit from the object class. Meta-classes have also been added, and many of the built-in and core library classes have been organized into hierarchies with the help of ABCs (Abstract Base Classes).
In my heavy usage of Python I have never found it lacking in the OO department. It can do everything I want it to do with objects. True, Ruby feels somewhat more purely OO, but at least in my experience this hasn't been a really practical concern.
A:
From WikiVS,
… where in Ruby all functions and most operators are in fact methods of an object, a number of Python functions are procedural functions rather than methods.
The following interview with Matz, the creator of Ruby, provides additional context to your question and the point above.
…
Stewart: Let's start with a little history. Why did you decide to write Ruby?
Matz: Back in 1993, I was talking with a colleague about scripting languages. I was pretty impressed by their power and their possibilities. I felt scripting was the way to go.
As a long time object-oriented programming fan, it seemed to me that OO programming was very suitable for scripting too. Then I looked around the Net. I found that Perl 5, which had not released yet, was going to implement OO features, but it was not really what I wanted. I gave up on Perl as an object-oriented scripting language.
Then I came across Python. It was an interpretive, object-oriented language. But I didn't feel like it was a "scripting" language. In addition, it was a hybrid language of procedural programming and object-oriented programming.
I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. That's why I decided to design my own language.
…
| How is Ruby more object-oriented than Python? | Matz, who invented Ruby, said that he designed the language to be more object-oriented than Python. How is Ruby more object-oriented than Python?
| [
"If you take the Python from 1993 and compare it with Ruby then the latter is more object oriented. However, after the overhaul in Python 2.2 this is no longer true. I'd say that modern Python is as object oriented as it gets.\n",
"One example that's commonly given is len, which in Python is a built-in function. ... | [
23,
17,
12
] | [
"It's simple, nearly everything in Ruby (including numbers) is an object; there are no scalar values. \n"
] | [
-2
] | [
"oop",
"python",
"ruby"
] | stackoverflow_0003665656_oop_python_ruby.txt |
Q:
How to create a simple mesh in Blender 2.50 via the Python API
I would like to create a simple mesh in Blender (2.50) via the Python API but the examples from the API documentation don't work yet.
I tried the following but it's from API 2.49
from Blender import *
import bpy
editmode = Window.EditMode() # are we in edit mode? If so ...
if editmode: Window.EditMode(0) # leave edit mode before getting the mesh
# define vertices and faces for a pyramid
coords=[ [-1,-1,-1], [1,-1,-1], [1,1,-1], [-1,1,-1], [0,0,1] ]
faces= [ [3,2,1,0], [0,1,4], [1,2,4], [2,3,4], [3,0,4] ]
me = bpy.data.meshes.new('myMesh') # create a new mesh
me.verts.extend(coords) # add vertices to mesh
me.faces.extend(faces) # add faces to the mesh (also adds edges)
me.vertexColors = 1 # enable vertex colors
me.faces[1].col[0].r = 255 # make each vertex a different color
me.faces[1].col[1].g = 255
me.faces[1].col[2].b = 255
scn = bpy.data.scenes.active # link object to current scene
ob = scn.objects.new(me, 'myObj')
if editmode: Window.EditMode(1) # optional, just being nice
This does not work because the mesh object doesn't have any faces or verts members.
Are there any options to do this?
A:
Try this documentation for the 2.5x API. I understand that despite the big warnings at the top, the most used sections are fairly stable now. I've not tried it yet.
EDIT:
I think the relevant bit is this section - it seems you create a list of vertices faces etc. and pass it to this. This seems to have changed from the most recent examples I can find. Try looking in your scripts folder - there might be an example there that you can look at.
EDIT 2: I have updated the link to point to the current live docs. The notes there suggest that there are probably better ways of doing this now but it is a long time since I have done any blender scripting so can't help more.
A:
Thanks to neil, I found the following section from the documentation:
Scripts for Blender 2.50 - Add Mesh Scripts
I will try the following script and report my results:
Add Solid Object Mesh
| How to create a simple mesh in Blender 2.50 via the Python API | I would like to create a simple mesh in Blender (2.50) via the Python API but the examples from the API documentation don't work yet.
I tried the following but it's from API 2.49
from Blender import *
import bpy
editmode = Window.EditMode() # are we in edit mode? If so ...
if editmode: Window.EditMode(0) # leave edit mode before getting the mesh
# define vertices and faces for a pyramid
coords=[ [-1,-1,-1], [1,-1,-1], [1,1,-1], [-1,1,-1], [0,0,1] ]
faces= [ [3,2,1,0], [0,1,4], [1,2,4], [2,3,4], [3,0,4] ]
me = bpy.data.meshes.new('myMesh') # create a new mesh
me.verts.extend(coords) # add vertices to mesh
me.faces.extend(faces) # add faces to the mesh (also adds edges)
me.vertexColors = 1 # enable vertex colors
me.faces[1].col[0].r = 255 # make each vertex a different color
me.faces[1].col[1].g = 255
me.faces[1].col[2].b = 255
scn = bpy.data.scenes.active # link object to current scene
ob = scn.objects.new(me, 'myObj')
if editmode: Window.EditMode(1) # optional, just being nice
This does not work because the mesh object doesn't have any faces or verts members.
Are there any options to do this?
| [
"Try this documentation for the 2.5x API. I understand that despite the big warnings at the top, the most used sections are fairly stable now. I've not tried it yet.\nEDIT:\nI think the relevant bit is this section - it seems you create a list of vertices faces etc. and pass it to this. This seems to have change... | [
3,
1
] | [] | [] | [
"blender",
"blender_2.50",
"python"
] | stackoverflow_0003657120_blender_blender_2.50_python.txt |
Q:
How to uniqufy the tuple element?
i have a result tuple of dictionaries.
result = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'yyy', 'score': 10L})
I want to uniqify it. After uniqify operation result = ({'name': 'xxx', 'score': 120L }, {'name': 'yyy', 'score': 10L})
The result contain only one dictionary of each name and the dict should have maximum score. The final result should be in the same format ie tuple of dictionary.
A:
from operator import itemgetter
names = set(d['name'] for d in result)
uniq = []
for name in names:
scores = [res for res in result if res['name'] == name]
uniq.append(max(scores, key=itemgetter('score')))
I'm sure there is a shorter solution, but you won't be able to avoid filtering the scores by name in some way first, then find the maximum for each name.
Storing scores in a dictionary with names as keys would definitely be preferable here.
A:
I would create an intermediate dictionary mapping each name to the maximum score for that name, then turn it back to a tuple of dicts afterwards:
>>> result = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'xxx', 'score': 10L}, {'name':'yyy', 'score':20})
>>> from collections import defaultdict
>>> max_scores = defaultdict(int)
>>> for d in result:
... max_scores[d['name']] = max(d['score'], max_scores[d['name']])
...
>>> max_scores
defaultdict(<type 'int'>, {'xxx': 120L, 'yyy': 20})
>>> tuple({name: score} for (name, score) in max_scores.iteritems())
({'xxx': 120L}, {'yyy': 20})
Notes:
1) I have added {'name': 'yyy', 'score': 20} to your example data to show it working with a tuple with more than one name.
2)I use a defaultdict that assumes the minimum value for score is zero. If the score can be negative you will need to change the int parameter of defaultdict(int) to a function that returns a number smaller than the minimum possible score.
Incidentally I suspect that having a tuple of dictionaries is not the best data structure for what you want to do. Have you considered alternatives, such as having a single dict, perhaps with a list of scores for each name?
A:
I would reconsider the data structure to fit your needs better (for example dict hashed with name with list of scores as value), but I would do like this:
import operator as op
import itertools as it
result = ({'name': 'xxx', 'score': 120L },
{'name': 'xxx', 'score': 100L},
{'name': 'xxx', 'score': 10L},
{'name':'yyy', 'score':20})
# groupby
highscores = tuple(max(namegroup, key=op.itemgetter('score'))
for name,namegroup in it.groupby(result,
key=op.itemgetter('name'))
)
print highscores
A:
How about...
inp = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'yyy', 'score': 10L})
temp = {}
for dct in inp:
if dct['score'] > temp.get(dct['name']): temp[dct['name']] = dct['score']
result = tuple({'name': name, 'score': score} for name, score in temp.iteritems())
| How to uniqufy the tuple element? | i have a result tuple of dictionaries.
result = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'yyy', 'score': 10L})
I want to uniqify it. After uniqify operation result = ({'name': 'xxx', 'score': 120L }, {'name': 'yyy', 'score': 10L})
The result contain only one dictionary of each name and the dict should have maximum score. The final result should be in the same format ie tuple of dictionary.
| [
"from operator import itemgetter\n\nnames = set(d['name'] for d in result)\nuniq = []\nfor name in names:\n scores = [res for res in result if res['name'] == name]\n uniq.append(max(scores, key=itemgetter('score')))\n\nI'm sure there is a shorter solution, but you won't be able to avoid filtering the scores b... | [
2,
2,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0003665414_algorithm_python.txt |
Q:
Separating URL from http request
I am studying Python language. I want to know about splitting HTTP request
GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1
Host: www.explainth.at
User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.explainth.at/en/misc/httpreq.shtml
I want to combine the part after GET and Host ( in bold letters) ..
GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1
Host: www.explainth.at
How it can be done?
A:
It's not clear why you want to do this, what the context or goal is, or how this data is arriving in your program. However, Python supports a number of useful string operations on its string type. So if you have a string containing all of this text, then you may find the splitlines method useful, along with some list slicing:
s = """\
... GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1
... Host: www.explainth.at
... User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
... Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,/;q=0.5
... """
s.splitlines()[:2]
['GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1', 'Host: www.explainth.at']
Of course, if you're writing any kind of real HTTP server software, this isn't likely to be the right approach (there's almost zero reason to operate at such a low level, and if you need to you almost certainly want to write or re-use a real HTTP parser instead). So you may want to ask a more precise question.
A:
You must split HTTP request by \r\n bytes. (newline marker on windows)
| Separating URL from http request | I am studying Python language. I want to know about splitting HTTP request
GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1
Host: www.explainth.at
User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.explainth.at/en/misc/httpreq.shtml
I want to combine the part after GET and Host ( in bold letters) ..
GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1
Host: www.explainth.at
How it can be done?
| [
"It's not clear why you want to do this, what the context or goal is, or how this data is arriving in your program. However, Python supports a number of useful string operations on its string type. So if you have a string containing all of this text, then you may find the splitlines method useful, along with some... | [
1,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003666610_python_twisted.txt |
Q:
What is the best way to implement web services in Python?
What is the best way to implement web services in Python?
A:
There are two main flavors of web services:
RESTful
SOAP based (old article)
I suggest you look into the RESTful stuff first. IMO, it is generally simpler to produce and/or consume a RESTful service, than it is to use SOAP.
| What is the best way to implement web services in Python? | What is the best way to implement web services in Python?
| [
"There are two main flavors of web services:\n\nRESTful\nSOAP based (old article)\n\nI suggest you look into the RESTful stuff first. IMO, it is generally simpler to produce and/or consume a RESTful service, than it is to use SOAP.\n"
] | [
1
] | [] | [] | [
"python",
"rest",
"soap",
"web_services"
] | stackoverflow_0003666854_python_rest_soap_web_services.txt |
Q:
Python: Testing if a value is present in a defaultdict list
I want test whether a string is present within any of the list values in a defaultdict.
For instance:
from collections import defaultdict
animals = defaultdict(list)
animals['farm']=['cow', 'pig', 'chicken']
animals['house']=['cat', 'rat']
I want to know if 'cow' occurs in any of the lists within animals.
'cow' in animals.values() #returns False
I want something that will return "True" for a case like this. Is there an equivalent of:
'cow' in animals.values()
for a defaultdict?
Thanks!
A:
defaultdict is no different from a regular dict in this case. You need to iterate over the values in the dictionary:
any('cow' in v for v in animals.values())
or more procedurally:
def in_values(s, d):
"""Does `s` appear in any of the values in `d`?"""
for v in d.values():
if s in v:
return True
return False
in_values('cow', animals)
A:
any("cow" in lst for lst in animals.itervalues())
| Python: Testing if a value is present in a defaultdict list | I want test whether a string is present within any of the list values in a defaultdict.
For instance:
from collections import defaultdict
animals = defaultdict(list)
animals['farm']=['cow', 'pig', 'chicken']
animals['house']=['cat', 'rat']
I want to know if 'cow' occurs in any of the lists within animals.
'cow' in animals.values() #returns False
I want something that will return "True" for a case like this. Is there an equivalent of:
'cow' in animals.values()
for a defaultdict?
Thanks!
| [
"defaultdict is no different from a regular dict in this case. You need to iterate over the values in the dictionary:\nany('cow' in v for v in animals.values())\n\nor more procedurally:\ndef in_values(s, d):\n \"\"\"Does `s` appear in any of the values in `d`?\"\"\"\n for v in d.values():\n if s in v:... | [
12,
0
] | [
"This example will flatten the list, checking each element and will return True or False as follows:\n>>> from collections import defaultdict \n>>> animals = defaultdict(list) \n>>> animals['farm']=['cow', 'pig', 'chicken'] \n>>> animals['house']=['cat', 'rat']\n\n>>> 'cow' in [x for y in animals.values() for x ... | [
-1
] | [
"collections",
"dictionary",
"list",
"python"
] | stackoverflow_0003667411_collections_dictionary_list_python.txt |
Q:
how to write regex starts and ends with particular string?
How to write regex for this paricular situation.
Here letters in [] is not fixed but letters without [] is fixed.
http://www.abc.com/fixed/[any small letters]/[anyletters]/fixed.html
A:
http://www.abc.com/fixed/[a-z]+/[a-zA-Z]+/fixed.html
Possibly change to a more forgiving:
http://www.abc.com/fixed/[a-z]+/[^/]+/fixed.html
A:
You can use lookarounds for that. One problem may be that they are not available in every language. For instance Javascript has only positive lookahead.
Oh, you mean something different... try this:
http://www.abc.com/fixed/[a-z]+/[\w\D^_]+/fixed.html
| how to write regex starts and ends with particular string? | How to write regex for this paricular situation.
Here letters in [] is not fixed but letters without [] is fixed.
http://www.abc.com/fixed/[any small letters]/[anyletters]/fixed.html
| [
"http://www.abc.com/fixed/[a-z]+/[a-zA-Z]+/fixed.html\n\nPossibly change to a more forgiving:\nhttp://www.abc.com/fixed/[a-z]+/[^/]+/fixed.html\n\n",
"You can use lookarounds for that. One problem may be that they are not available in every language. For instance Javascript has only positive lookahead.\nOh, you m... | [
4,
0
] | [] | [] | [
"mysql",
"python",
"regex"
] | stackoverflow_0003667599_mysql_python_regex.txt |
Q:
Appengine retrieve data related to user form submission
I had read the docs for Appengine to know how to retrieve data from Models.
But i´m missing something..
My models are user and student, where student is a reference property from user.
Users login, fill form with some values and save the data with put().
If you login with test@example.com you get your data or if you login with another email you get the data corresponding to your information sent to db.
Everythin is fine till here.
I´m trying to get a PDF and want to get the data from the user loged in.
Example:
class SavePDF(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
if user:
student= models.Student.all().get()
p = canvas.Canvas(self.response.out)
p.drawImage('ipca.jpg', 40, 700)
p.drawString(50,640, 'Student Info:' + '%s' % student.name)
p.drawString(50,620, 'Adress:' + '%s' % student.adress)
p.drawString(50,300, 'PDF updated:%s' % str(datetime.date.today()))
p.showPage()
self.response.headers['Content-Type'] = 'application/pdf'
self.response.headers['Content-Disposition'] = 'filename=mypdf.pdf'
p.save()
What i get here is a user that is not current user. Shows Info about other user.
I´ve tried different things but it throws errors.
If i try to iterate gives error.
I´m missing something.
A:
If your Student model looks like this:
class Student(db.Model):
user = db.UserProperty()
name = db.StringProperty()
address = db.StringProperty()
Then you probably want something like this:
user = users.get_current_user()
if user:
student = models.Student.all().filter('user =', user).get()
| Appengine retrieve data related to user form submission | I had read the docs for Appengine to know how to retrieve data from Models.
But i´m missing something..
My models are user and student, where student is a reference property from user.
Users login, fill form with some values and save the data with put().
If you login with test@example.com you get your data or if you login with another email you get the data corresponding to your information sent to db.
Everythin is fine till here.
I´m trying to get a PDF and want to get the data from the user loged in.
Example:
class SavePDF(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
if user:
student= models.Student.all().get()
p = canvas.Canvas(self.response.out)
p.drawImage('ipca.jpg', 40, 700)
p.drawString(50,640, 'Student Info:' + '%s' % student.name)
p.drawString(50,620, 'Adress:' + '%s' % student.adress)
p.drawString(50,300, 'PDF updated:%s' % str(datetime.date.today()))
p.showPage()
self.response.headers['Content-Type'] = 'application/pdf'
self.response.headers['Content-Disposition'] = 'filename=mypdf.pdf'
p.save()
What i get here is a user that is not current user. Shows Info about other user.
I´ve tried different things but it throws errors.
If i try to iterate gives error.
I´m missing something.
| [
"If your Student model looks like this:\nclass Student(db.Model):\n user = db.UserProperty()\n name = db.StringProperty()\n address = db.StringProperty()\n\nThen you probably want something like this:\nuser = users.get_current_user() \nif user: \n student = models.Student.all().filter('user =', user).ge... | [
3
] | [] | [] | [
"bigtable",
"google_app_engine",
"python",
"reportlab"
] | stackoverflow_0003667332_bigtable_google_app_engine_python_reportlab.txt |
Q:
Converting from list of tuples to list of lists of tuples
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I have list of tuples, each tuple has two items (the amount of tuples may vary).
[(a, b), (c, d)...)]
I want to convert the list to a nested list of tuples so that each nested list contains 4 tuples, if the original list of tuples has quantity not divisible by 4 e.g. 13 then the final list should contain the leftover amount in the case of 13, 1 tuple.
[[(a, b), (c, d), (e, f), (g, h)], [(a, b), (c, d), (e, f), (g, h)]...]
One of the things about python I love is the methods and constructs for converting between different data structures, I was hoping there might be such a method or construct for this problem that would be more pythonic then what Iv come up with.
image_thumb_pairs = [(a, b), (c, d), (e, f), (g, h), (i, j)]
row = []
rows = []
for i, image in enumerate(image_thumb_pairs):
row.append(image)
if(i+1) % 4 == 0:
rows.append(row)
row = []
if row:
rows.append(row)
A:
>>> lst = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12), (13, 14), (15, 16), (17, 18)]
>>> [lst[i:i+4] for i in xrange(0, len(lst), 4)]
[[(1, 2), (3, 4), (5, 6), (7, 8)], [(9, 10), (11, 12), (13, 14), (15, 16)], [(17, 18)]]
| Converting from list of tuples to list of lists of tuples |
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I have list of tuples, each tuple has two items (the amount of tuples may vary).
[(a, b), (c, d)...)]
I want to convert the list to a nested list of tuples so that each nested list contains 4 tuples, if the original list of tuples has quantity not divisible by 4 e.g. 13 then the final list should contain the leftover amount in the case of 13, 1 tuple.
[[(a, b), (c, d), (e, f), (g, h)], [(a, b), (c, d), (e, f), (g, h)]...]
One of the things about python I love is the methods and constructs for converting between different data structures, I was hoping there might be such a method or construct for this problem that would be more pythonic then what Iv come up with.
image_thumb_pairs = [(a, b), (c, d), (e, f), (g, h), (i, j)]
row = []
rows = []
for i, image in enumerate(image_thumb_pairs):
row.append(image)
if(i+1) % 4 == 0:
rows.append(row)
row = []
if row:
rows.append(row)
| [
">>> lst = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12), (13, 14), (15, 16), (17, 18)]\n>>> [lst[i:i+4] for i in xrange(0, len(lst), 4)]\n[[(1, 2), (3, 4), (5, 6), (7, 8)], [(9, 10), (11, 12), (13, 14), (15, 16)], [(17, 18)]]\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003667581_python.txt |
Q:
What's the correct way to store an object in a Model property?
I need to store a Django template object in a Model property.
My solution so far has been to pickle the object before assigning it to a BlobProperty :
entity.template_blob = pickle.dumps(template)
entity.put()
And then after a fetch from the datastore, I do :
template = pickle.loads(entity.template_blob)
Am I doing this wrong ? I couldn't find a property suited to the storage of any object.
A:
You've got it right. Pickling to a blob is the standard solution for this problem.
There isn't a built-in property that automatically handles the serialization / deserialization, but the PickleProperty in aetycoon will do this for you.
| What's the correct way to store an object in a Model property? | I need to store a Django template object in a Model property.
My solution so far has been to pickle the object before assigning it to a BlobProperty :
entity.template_blob = pickle.dumps(template)
entity.put()
And then after a fetch from the datastore, I do :
template = pickle.loads(entity.template_blob)
Am I doing this wrong ? I couldn't find a property suited to the storage of any object.
| [
"You've got it right. Pickling to a blob is the standard solution for this problem.\nThere isn't a built-in property that automatically handles the serialization / deserialization, but the PickleProperty in aetycoon will do this for you.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003666680_google_app_engine_google_cloud_datastore_python.txt |
Q:
Removing non-ascii characters from any given stringtype in Python
>>> teststring = 'aõ'
>>> type(teststring)
<type 'str'>
>>> teststring
'a\xf5'
>>> print teststring
aõ
>>> teststring.decode("ascii", "ignore")
u'a'
>>> teststring.decode("ascii", "ignore").encode("ascii")
'a'
which is what i really wanted it to store internally as i remove non-ascii characters. Why did the decode("ascii give out a unicode string ?
>>> teststringUni = u'aõ'
>>> type(teststringUni)
<type 'unicode'>
>>> print teststringUni
aõ
>>> teststringUni.decode("ascii" , "ignore")
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
teststringUni.decode("ascii" , "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf5' in position 1: ordinal not in range(128)
>>> teststringUni.decode("utf-8" , "ignore")
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
teststringUni.decode("utf-8" , "ignore")
File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf5' in position 1: ordinal not in range(128)
>>> teststringUni.encode("ascii" , "ignore")
'a'
Which is again what i wanted.
I don't understand this behavior. Can someone explain to me what is happening here?
edit: i thought this would me understand things so i could solve my real program problem that i state here:
Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python)
A:
Why did the decode("ascii") give out a unicode string?
Because that's what decode is for: it decodes byte strings like your ASCII one into unicode.
In your second example, you're trying to "decode" a string which is already unicode, which has no effect. To print it to your terminal, though, Python must encode it as your default encoding, which is ASCII - but because you haven't done that step explicitly and therefore haven't specified the 'ignore' parameter, it raises the error that it can't encode the non-ASCII characters.
The trick to all of this is remembering that decode takes an encoded bytestring and converts it to Unicode, and encode does the reverse. It might be easier if you understand that Unicode is not an encoding.
A:
It's simple: .encode converts Unicode objects into strings, and .decode converts strings into Unicode.
| Removing non-ascii characters from any given stringtype in Python | >>> teststring = 'aõ'
>>> type(teststring)
<type 'str'>
>>> teststring
'a\xf5'
>>> print teststring
aõ
>>> teststring.decode("ascii", "ignore")
u'a'
>>> teststring.decode("ascii", "ignore").encode("ascii")
'a'
which is what i really wanted it to store internally as i remove non-ascii characters. Why did the decode("ascii give out a unicode string ?
>>> teststringUni = u'aõ'
>>> type(teststringUni)
<type 'unicode'>
>>> print teststringUni
aõ
>>> teststringUni.decode("ascii" , "ignore")
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
teststringUni.decode("ascii" , "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf5' in position 1: ordinal not in range(128)
>>> teststringUni.decode("utf-8" , "ignore")
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
teststringUni.decode("utf-8" , "ignore")
File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf5' in position 1: ordinal not in range(128)
>>> teststringUni.encode("ascii" , "ignore")
'a'
Which is again what i wanted.
I don't understand this behavior. Can someone explain to me what is happening here?
edit: i thought this would me understand things so i could solve my real program problem that i state here:
Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python)
| [
"\nWhy did the decode(\"ascii\") give out a unicode string?\n\nBecause that's what decode is for: it decodes byte strings like your ASCII one into unicode.\nIn your second example, you're trying to \"decode\" a string which is already unicode, which has no effect. To print it to your terminal, though, Python must e... | [
4,
4
] | [] | [] | [
"non_ascii_characters",
"python",
"replace",
"string",
"unicode"
] | stackoverflow_0003667875_non_ascii_characters_python_replace_string_unicode.txt |
Q:
Are order of keys() and values() in python dictionary guaranteed to be the same?
Does native built-in python dict guarantee that the keys() and values() lists are ordered in the same way?
d = {'A':1, 'B':2, 'C':3, 'D':4 } # or any other content
otherd = dict(zip(d.keys(), d.values()))
Do I always have d == otherd ?
Either it's true or false, I'm interested in any reference pointer on the subject.
PS: I understand the above property will not be true for every objects that behave like a dictionary, I just wonder for the built-in dict. When I test it looks as if it's true, and it's no surprise because having the same order for keys() and values() is probably the simplest implementation anyway. But I wonder if this behavior was explicitly defined or not.
A:
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.
From the documentation for dict.
A:
Python 2.7 and above have ordered dictionaries, for which your statement:
d == dict(zip(d.keys(), d.values()))
would apply
| Are order of keys() and values() in python dictionary guaranteed to be the same? | Does native built-in python dict guarantee that the keys() and values() lists are ordered in the same way?
d = {'A':1, 'B':2, 'C':3, 'D':4 } # or any other content
otherd = dict(zip(d.keys(), d.values()))
Do I always have d == otherd ?
Either it's true or false, I'm interested in any reference pointer on the subject.
PS: I understand the above property will not be true for every objects that behave like a dictionary, I just wonder for the built-in dict. When I test it looks as if it's true, and it's no surprise because having the same order for keys() and values() is probably the simplest implementation anyway. But I wonder if this behavior was explicitly defined or not.
| [
"\nKeys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, ... | [
30,
4
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003666237_dictionary_python.txt |
Q:
Python smtp connection is always failed in a VMware Windows machine
I m trying to use smtp class from Python 2.6.4 to send smtp email from a WinXP VMware machine.
After the send method is called, I always got this error:
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it.
Few stuff I noticed:
The same code works in the physical WinXP machine with user in/not in the domain, connected to the same smtp server.
If I use the smtp server which is setup in the same VM machine, then it works.
Any help is appreciate!
A:
The phrase "...because the target machine actively refused it" usually means there's a firewall that drops any unauthorized connections. Is there a firewall service on the SMTP server that's blocking the WinXP VM's IP address?
Or, more likely: Is the SMTP server not configured to accept relays from the WinXP VM's IP address?
| Python smtp connection is always failed in a VMware Windows machine | I m trying to use smtp class from Python 2.6.4 to send smtp email from a WinXP VMware machine.
After the send method is called, I always got this error:
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it.
Few stuff I noticed:
The same code works in the physical WinXP machine with user in/not in the domain, connected to the same smtp server.
If I use the smtp server which is setup in the same VM machine, then it works.
Any help is appreciate!
| [
"The phrase \"...because the target machine actively refused it\" usually means there's a firewall that drops any unauthorized connections. Is there a firewall service on the SMTP server that's blocking the WinXP VM's IP address?\nOr, more likely: Is the SMTP server not configured to accept relays from the WinXP VM... | [
2
] | [] | [] | [
"email",
"python",
"smtp",
"vmware"
] | stackoverflow_0003664438_email_python_smtp_vmware.txt |
Q:
earliest commonly used version of Python
Is there an officially updated recommendation indicating which versions of Python should be supported by released modules? Or perhaps a page giving a survey of production usage of various versions? It's difficult to know how much use to make of newish features like context managers, class decorators, etc. when writing a module.
Note that learning which versions of Python are in common usage now is only part of my question; I'd like to find a resource which will provide up-to-date information for future readers of this thread (and myself).
A:
I'm not aware of any single resource keeping an up-to-date summary of production usage of different Python versions, but a good start would probably be to check which Python versions that are distributed with various Linux distributions. Here's a sample for some of the most used server distributions (taken from Distrowatch):
Debian
Debian 5.0 (2009-02-15): Python 2.5.2
Debian 4.0 (2007-04-08): Python 2.4.4
Debian 3.1 (2005-06-06): Python 2.3.5
Ubuntu
Ubuntu 10.04 LTS (2010-04-29): Python 2.6.5
Ubuntu 8.04 LTS (2008-04-24): Python 2.5.2
Red Hat Enterprise Linux
RHEL 5.5 (2010-03-30): Python 2.4.3
RHEL 4.8 (2009-05-19): Python 2.3.4
RHEL 3.9 (2007-05-30): Python 2.2.3
Clearly, Red Hat is the limiting factor here. The latest stable RHEL release ships with Python 2.4, and as there's a fair number of RHEL servers out there, you'll have to target Python 2.4 unless you want Red Hat users to install a newer Python version from source or from third-party RPMs. If you don't mind leaving RHEL behind you could probably go for 2.5 or 2.6 instead.
A:
Mac OS X 10.6 (Snow Leopard) has 2.6.1 as the installed version.
IIRC, 10.5 (Leopard) has 2.5 as the installed version.
| earliest commonly used version of Python | Is there an officially updated recommendation indicating which versions of Python should be supported by released modules? Or perhaps a page giving a survey of production usage of various versions? It's difficult to know how much use to make of newish features like context managers, class decorators, etc. when writing a module.
Note that learning which versions of Python are in common usage now is only part of my question; I'd like to find a resource which will provide up-to-date information for future readers of this thread (and myself).
| [
"I'm not aware of any single resource keeping an up-to-date summary of production usage of different Python versions, but a good start would probably be to check which Python versions that are distributed with various Linux distributions. Here's a sample for some of the most used server distributions (taken from D... | [
6,
0
] | [] | [] | [
"backwards_compatibility",
"python",
"version"
] | stackoverflow_0003666750_backwards_compatibility_python_version.txt |
Q:
Python decorator to refresh cursor instance
I have a method to save data in DB, and a decorator to manage the connection, but I can't figure out how to make it work.
method to save:
class DA_Row(DABase):
@DABase.connectAndDisconnect
def save(self):
"""
Guarda el spin en la base de datos
"""
self.__cursor.callproc('sp_insert_row', (
"value 1",
"value 2"
)
)
and I have here the inherited class with a function decorator that does not work.
class DABase():
def __init__(self):
self.__cursor = None
@staticmethod
def connectAndDisconnect(func):
def deco(*args):
returnValue = None
self.DBconnect()
try:
self.__cursor = self.db.cursor()
returnValue = func(*args)
finally:
self.desconectarDB()
return returnValue
return deco
....
Shown this...
How can I redefine DABase.__cursor from a decorator?
If is not possible, how to solve this problem in a different way?
Thank you for your time!
A:
self is just a name like everything else, it does not magically appear like Java's this. You need to add it to your decorator. Try this:
@staticmethod
def connectAndDisconnect(func):
# deco will be a method, so it needs self (ie a DA_Row instance)
def deco(self, *args):
returnValue = None
self.DBconnect()
try:
self.__cursor = self.db.cursor()
# func was supposed to be a method to, so it needs self
returnValue = func(self, *args)
finally:
self.desconectarDB()
return returnValue
return deco
A:
It would help if you showed the error that you're getting. However, I can take a guess...
Decorating a method of a class is hard. How is connectAndDisconnect supposed to know what self should be? connectAndDisconnect is a static method of the base class, which gets called when the derived class gets created, long before any instances of the derived class get created.
There's a trick which lets the decorator figure out what self should be, but it's a complicated hack and fragile in a way that I'll explain at the end. The trick is, use a class as the decorator, and make that class an descriptor (i.e. define __get__) to give you a chance to determine what self should be. In your case it would look something like:
class DABase(object):
def __init__(self):
self.__cursor = None
class connectAndDisconnect(object):
def __init__(self, method):
self._method = method # method is the thing being decorated
# note that it's an *unbound* method
self._instance = None # no way to know what the instance is yet
def __get__(self, instance, owner):
'This will be called when the decorated method is accessed'
self._instance = instance
return self
def __call__(self, *args):
'This is where the actual decoration takes place'
returnValue = None
# 'self' is the connectAndDisconnect object. 'self._instance' is the decorated object.
self._instance.DBConnect()
try:
self._instance.__cursor = self._instance.db.cursor()
# Since self._method is unbound, we have to pass the instance explicitly
returnValue = self._method(self._instance, *args)
finally:
self._instance.desconectarDB()
return returnValue
The derived class is unchanged:
class DA_Row(DABase):
@DABase.connectAndDisconnect
def save(self):
# ...
Now DA_Row.save is actually an instance of the connectAndDisconnect class. If d is a DA_Row object and someone calls d.save(), the first thing that happens is that connectAndDisconnect.__get__ gets called because someone tried to access d.save. This sets the _instance variable to equal d. Then connectAndDisconnect.__call__ gets called and the actual decoration takes place.
This works, most of the time. But it's fragile. It only works if you call save in the "normal" way, i.e. through an instance. If you try to do funny stuff like calling DA_Row.save(d) instead, it won't work because connectAndDisconnect.__get__ won't be able to figure out what the instance should be.
| Python decorator to refresh cursor instance | I have a method to save data in DB, and a decorator to manage the connection, but I can't figure out how to make it work.
method to save:
class DA_Row(DABase):
@DABase.connectAndDisconnect
def save(self):
"""
Guarda el spin en la base de datos
"""
self.__cursor.callproc('sp_insert_row', (
"value 1",
"value 2"
)
)
and I have here the inherited class with a function decorator that does not work.
class DABase():
def __init__(self):
self.__cursor = None
@staticmethod
def connectAndDisconnect(func):
def deco(*args):
returnValue = None
self.DBconnect()
try:
self.__cursor = self.db.cursor()
returnValue = func(*args)
finally:
self.desconectarDB()
return returnValue
return deco
....
Shown this...
How can I redefine DABase.__cursor from a decorator?
If is not possible, how to solve this problem in a different way?
Thank you for your time!
| [
"self is just a name like everything else, it does not magically appear like Java's this. You need to add it to your decorator. Try this:\n @staticmethod\n def connectAndDisconnect(func):\n # deco will be a method, so it needs self (ie a DA_Row instance)\n def deco(self, *args):\n ret... | [
4,
2
] | [] | [] | [
"connection",
"decorator",
"python"
] | stackoverflow_0003668254_connection_decorator_python.txt |
Q:
Sorting a sublist within a Python list of integers
I have an unsorted list of integers in a Python list. I want to sort the elements in a subset of the full list, not the full list itself. I also want to sort the list in-place so as to not create new lists (I'm doing this very frequently). I initially tried
p[i:j].sort()
but this didn't change the contents of p presumably because a new list was formed, sorted, and then thrown away without affecting the contents of the original list. I can, of course, create my own sort function and use loops to select the appropriate elements but this doesn't feel pythonic. Is there a better way to sort sublists in place?
A:
You can write p[i:j] = sorted(p[i:j])
A:
This is because p[i:j] returns a new list. I can think of this immediate solution:
l = p[i:j]
l.sort()
a = 0
for x in range(i, j):
p[x] = l[a]
a += 1
| Sorting a sublist within a Python list of integers | I have an unsorted list of integers in a Python list. I want to sort the elements in a subset of the full list, not the full list itself. I also want to sort the list in-place so as to not create new lists (I'm doing this very frequently). I initially tried
p[i:j].sort()
but this didn't change the contents of p presumably because a new list was formed, sorted, and then thrown away without affecting the contents of the original list. I can, of course, create my own sort function and use loops to select the appropriate elements but this doesn't feel pythonic. Is there a better way to sort sublists in place?
| [
"You can write p[i:j] = sorted(p[i:j])\n",
"This is because p[i:j] returns a new list. I can think of this immediate solution:\nl = p[i:j]\nl.sort()\na = 0\nfor x in range(i, j):\n p[x] = l[a]\n a += 1\n\n"
] | [
28,
0
] | [
"\"in place\" doesn't mean much. You want this.\np[i:j] = list( sorted( p[i:j] ) ) \n\n"
] | [
-6
] | [
"python"
] | stackoverflow_0003668930_python.txt |
Q:
Dropping a file onto a script to run as argument causes exception in Vista
edit:OK, I could swear that the way I'd tested it showed that the getcwd was also causing the exception, but now it appears it's just the file creation. When I move the try-except blocks to their it actually does catch it like you'd think it would. So chalk that up to user error.
Original Question:
I have a script I'm working on that I want to be able to drop a file on it to have it run with that file as an argument. I checked in this question, and I already have the mentioned registry keys (apparently the Python 2.6 installer takes care of it.) However, it's throwing an exception that I can't catch. Running it from the console works correctly, but when I drop a file on it, it throws an exception then closes the console window. I tried to have it redirect standard error to a file, but it threw the exception before the redirection occurred in the script. With a little testing, and some quick eyesight I saw that it was throwing an IOError when I tried to create the file to write the error to.
import sys
import os
#os.chdir("C:/Python26/Projects/arguments")
try:
print sys.argv
raw_input()
os.getcwd()
except Exception,e:
print sys.argv + '\n'
print e
f = open("./myfile.txt", "w")
If I run this from the console with any or no arguments, it behaves as one would expect. If I run it by dropping a file on it, for instance test.txt, it runs, prints the arguments correctly, then when os.getcwd() is called, it throws the exception, and does not perform any of the stuff from the except: block, making it difficult for me to find any way to actually get the exception text to stay on screen. If I uncomment the os.chdir(), the script doesn't fail. If I move that line to within the except block, it's never executed.
I'm guessing running by dropping the file on it, which according to the other linked question, uses the WSH, is somehow messing up its permissions or the cwd, but I don't know how to work around it.
A:
Seeing as this is probably not Python related, but a Windows problem (I for one could not reproduce the error given your code), I'd suggest attaching a debugger to the Python interpreter when it is started. Since you start the interpreter implicitly by a drag&drop action, you need to configure Windows to auto-attach a debugger each time Python starts. If I remember correctly, this article has the needed information to do that (you can substitute another debugger if you are not using Visual Studio).
Apart from that, I would take a snapshot with ProcMon while dragging a file onto your script, to get an idea of what is going on.
A:
As pointed out in my edit above, the errors were caused by the working directory changing to C:\windows\system32, where the script isn't allowed to create files. I don't know how to get it to not change the working directory when started that way, but was able to work around it like this.
if len(sys.argv) == 1:
files = [filename for filename in os.listdir(os.getcwd())
if filename.endswith(".txt")]
else:
files = [filename for filename in sys.argv[1:]]
Fixing the working directory can be managed this way I guess.
exepath = sys.argv[0]
os.chdir(exepath[:exepath.rfind('\\')])
| Dropping a file onto a script to run as argument causes exception in Vista | edit:OK, I could swear that the way I'd tested it showed that the getcwd was also causing the exception, but now it appears it's just the file creation. When I move the try-except blocks to their it actually does catch it like you'd think it would. So chalk that up to user error.
Original Question:
I have a script I'm working on that I want to be able to drop a file on it to have it run with that file as an argument. I checked in this question, and I already have the mentioned registry keys (apparently the Python 2.6 installer takes care of it.) However, it's throwing an exception that I can't catch. Running it from the console works correctly, but when I drop a file on it, it throws an exception then closes the console window. I tried to have it redirect standard error to a file, but it threw the exception before the redirection occurred in the script. With a little testing, and some quick eyesight I saw that it was throwing an IOError when I tried to create the file to write the error to.
import sys
import os
#os.chdir("C:/Python26/Projects/arguments")
try:
print sys.argv
raw_input()
os.getcwd()
except Exception,e:
print sys.argv + '\n'
print e
f = open("./myfile.txt", "w")
If I run this from the console with any or no arguments, it behaves as one would expect. If I run it by dropping a file on it, for instance test.txt, it runs, prints the arguments correctly, then when os.getcwd() is called, it throws the exception, and does not perform any of the stuff from the except: block, making it difficult for me to find any way to actually get the exception text to stay on screen. If I uncomment the os.chdir(), the script doesn't fail. If I move that line to within the except block, it's never executed.
I'm guessing running by dropping the file on it, which according to the other linked question, uses the WSH, is somehow messing up its permissions or the cwd, but I don't know how to work around it.
| [
"Seeing as this is probably not Python related, but a Windows problem (I for one could not reproduce the error given your code), I'd suggest attaching a debugger to the Python interpreter when it is started. Since you start the interpreter implicitly by a drag&drop action, you need to configure Windows to auto-atta... | [
1,
1
] | [] | [] | [
"arguments",
"drag_and_drop",
"exception_handling",
"python",
"windows_vista"
] | stackoverflow_0003661948_arguments_drag_and_drop_exception_handling_python_windows_vista.txt |
Q:
Python Regular Expressions - Complete Match
for my CGI application I'm writing a function to get the browser's preferred language (supplied in the HTTP_ACCEPT_LANGUAGE variable). I want to find all language tags in this variable with regular expressions (The general pattern of a language tag is defined in RFC1766). EBNF from RFC1766 ('1*8ALPHA' means one to eight ASCII chars):
Language-Tag = Primary-tag *( "-" Subtag )
Primary-tag = 1*8ALPHA
Subtag = 1*8ALPHA
I wrote this regular expression for a language tag:
(([a-z]{1,8})(-[a-z]{1,8})*)
If i use this expression, Python's re module supplies the following
>>import re
>>re.findall("(([a-z]{1,8})(-[a-z]{1,8})*)", "x-pig-latin en-us de-de en", re.IGNORECASE)
[('x-pig-latin', 'x', '-latin'), ('en-us', 'en', '-us'), ('de-de', 'de', '-de'), ('en', 'en', '')]
The result is correct. But I only need complete matches like 'de-de' or 'x-pig-latin'. Can I assume that the first match of a group is always the most complete one? Or is there a flag telling re to show the most complete matches?
Stefan
A:
You can use the ?: operator to prevent the regex engine from saving bracketed subpatterns:
((?:[a-z]{1,8})(?:-[a-z]{1,8})*)
This gives the output:
re.findall("((?:[a-z]{1,8})(?:-[a-z]{1,8})*)", "x-pig-latin en-us de-de en", re.IGNORECASE)
['x-pig-latin', 'en-us', 'de-de', 'en']
To answer your question, the first match returned by findall should be the full matching substring.
A:
Make your inner groups (i.e., parentheses) into non-capturing ones: that is, change from:
(([a-z]{1,8})(-[a-z]{1,8})*)
to:
((?:[a-z]{1,8})(?:-[a-z]{1,8})*)
To recap, the pattern notation (?: ... ) defines a non-capturing group: the parentheses stills serve the purpose of controlling priority, but don't leave traces in the match object's .groups() and other capturing-group related traits.
Plain parentheses, ( ... ), mean a capturing group.
There is no reason to use capturing groups for sub-matches that you're explicitly not interested about, of course. Use them only for the sub-matches you do care about!-)
A:
Not sure if you've already checked it out, but this article has lots of good pointers about doing Accept-Language parsing, along with a reference to a library that has already solved the problem.
As far as your re question goes, Doug Hellman has a great breakdown of re in his recent Python Module of the Week.
| Python Regular Expressions - Complete Match | for my CGI application I'm writing a function to get the browser's preferred language (supplied in the HTTP_ACCEPT_LANGUAGE variable). I want to find all language tags in this variable with regular expressions (The general pattern of a language tag is defined in RFC1766). EBNF from RFC1766 ('1*8ALPHA' means one to eight ASCII chars):
Language-Tag = Primary-tag *( "-" Subtag )
Primary-tag = 1*8ALPHA
Subtag = 1*8ALPHA
I wrote this regular expression for a language tag:
(([a-z]{1,8})(-[a-z]{1,8})*)
If i use this expression, Python's re module supplies the following
>>import re
>>re.findall("(([a-z]{1,8})(-[a-z]{1,8})*)", "x-pig-latin en-us de-de en", re.IGNORECASE)
[('x-pig-latin', 'x', '-latin'), ('en-us', 'en', '-us'), ('de-de', 'de', '-de'), ('en', 'en', '')]
The result is correct. But I only need complete matches like 'de-de' or 'x-pig-latin'. Can I assume that the first match of a group is always the most complete one? Or is there a flag telling re to show the most complete matches?
Stefan
| [
"You can use the ?: operator to prevent the regex engine from saving bracketed subpatterns:\n((?:[a-z]{1,8})(?:-[a-z]{1,8})*)\n\nThis gives the output:\nre.findall(\"((?:[a-z]{1,8})(?:-[a-z]{1,8})*)\", \"x-pig-latin en-us de-de en\", re.IGNORECASE)\n['x-pig-latin', 'en-us', 'de-de', 'en']\n\nTo answer your question... | [
4,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003669236_python_regex.txt |
Q:
Problem with deepcopy(ing) a TypedList class inheriting from list and overriding append
I don't understand why the new instance of the TypeList class does not have a my_type attribute.
Here is my code:
import copy
class TypedList(list):
def __init__(self, typeof, iterable=''):
"""
Initialize the typed list.
Examples:
tmp = TypedList(str, 'foobar') # OK
tmp = TypedList('str', 'foobar') # FAIL!
"""
if not issubclass(type(typeof), object):
raise TypeError('typeof must inherit from object')
if type(typeof) is not type:
raise TypeError('typeof, argument must be a python object type.\n'
'Not a string stating the type of python object.\n'
'Example: TypedList(str), not Typedlist("str")')
self.my_type = typeof
for item in iterable:
if type(item) != self.my_type:
raise TypeError('%s is of type %s; it should be type %s' %
(item, type(item), self.my_type))
super(TypedList, self).__init__(iterable)
def append(self, item):
"""
Append an item to the typed list.
"""
if type(item) != self.my_type:
raise TypeError('item must be of type %s' % self.my_type)
return super(TypedList, self).append(item)
if __name__ == '__main__':
foo = TypedList(str, 'test')
bar = copy.deepcopy(foo)
Executing it returns this output:
$ python tl.py
Traceback (most recent call last):
File "tl.py", line 53, in <module>
bar = copy.deepcopy(foo)
File "/usr/lib/python2.6/copy.py", line 189, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.6/copy.py", line 329, in _reconstruct
y.append(item)
File "tl.py", line 46, in append
if type(item) != self.my_type:
AttributeError: 'TypedList' object has no attribute 'my_type'
A:
I just tested your script with Python 2.5 and Python 2.7 and it works:
import copy
class TypedList(list):
def __init__(self, typeof, iterable=''):
""" Initialize the typed list.
Examples:
tmp = TypedList(str, 'foobar') # OK
tmp = TypedList('str', 'foobar') # FAIL!
"""
if not issubclass(type(typeof), object):
raise TypeError('typeof must inherit from object')
if type(typeof) is not type:
raise TypeError('typeof, argument must be a python object type.\n'
'Not a string stating the type of python object.\n'
'Example: TypedList(str), not Typedlist("str")')
self.my_type = typeof
for item in iterable:
if type(item) != self.my_type:
raise TypeError('%s is of type %s; it should be type %s' %
(item, type(item), self.my_type))
super(TypedList, self).__init__(iterable)
def append(self, item):
"""
Append an item to the typed list.
"""
if type(item) != self.my_type:
raise TypeError('item must be of type %s' % self.my_type)
return super(TypedList, self).append(item)
if __name__ == '__main__':
foo = TypedList(str, 'test')
bar = copy.deepcopy(foo)
assert foo.my_type is bar.my_type
| Problem with deepcopy(ing) a TypedList class inheriting from list and overriding append | I don't understand why the new instance of the TypeList class does not have a my_type attribute.
Here is my code:
import copy
class TypedList(list):
def __init__(self, typeof, iterable=''):
"""
Initialize the typed list.
Examples:
tmp = TypedList(str, 'foobar') # OK
tmp = TypedList('str', 'foobar') # FAIL!
"""
if not issubclass(type(typeof), object):
raise TypeError('typeof must inherit from object')
if type(typeof) is not type:
raise TypeError('typeof, argument must be a python object type.\n'
'Not a string stating the type of python object.\n'
'Example: TypedList(str), not Typedlist("str")')
self.my_type = typeof
for item in iterable:
if type(item) != self.my_type:
raise TypeError('%s is of type %s; it should be type %s' %
(item, type(item), self.my_type))
super(TypedList, self).__init__(iterable)
def append(self, item):
"""
Append an item to the typed list.
"""
if type(item) != self.my_type:
raise TypeError('item must be of type %s' % self.my_type)
return super(TypedList, self).append(item)
if __name__ == '__main__':
foo = TypedList(str, 'test')
bar = copy.deepcopy(foo)
Executing it returns this output:
$ python tl.py
Traceback (most recent call last):
File "tl.py", line 53, in <module>
bar = copy.deepcopy(foo)
File "/usr/lib/python2.6/copy.py", line 189, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.6/copy.py", line 329, in _reconstruct
y.append(item)
File "tl.py", line 46, in append
if type(item) != self.my_type:
AttributeError: 'TypedList' object has no attribute 'my_type'
| [
"I just tested your script with Python 2.5 and Python 2.7 and it works:\nimport copy\n\nclass TypedList(list):\n\n def __init__(self, typeof, iterable=''):\n \"\"\" Initialize the typed list.\n\n Examples:\n tmp = TypedList(str, 'foobar') # OK\n tmp = TypedList('str', 'foobar') # FAIL!\n \"\"\"\n ... | [
0
] | [] | [] | [
"deep_copy",
"python"
] | stackoverflow_0003669396_deep_copy_python.txt |
Q:
Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python)
I want to send Chinese characters to be translated by an online service, and have the resulting English string returned. I'm using simple JSON and urllib for this.
And yes, I am declaring.
# -*- coding: utf-8 -*-
on top of my code.
Now everything works fine if I feed urllib a string type object, even if that object contains what would be Unicode information. My function is called translate.
For example:
stringtest1 = '無與倫比的美麗'
print translate(stringtest1)
results in the proper translation and doing
type(stringtest1)
confirms this to be a string object.
But if do
stringtest1 = u'無與倫比的美麗'
and try to use my translation function I get this error:
File "C:\Python27\lib\urllib.py", line 1275, in urlencode
v = quote_plus(str(v))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-8: ordinal not in range(128)
After researching a bit, it seems this is a common problem:
Problem: neither urllib2.quote nor urllib.quote encode the unicode strings arguments
urllib.quote throws exception on Unicode URL
Now, if I type in a script
stringtest1 = '無與倫比的美麗'
stringtest2 = u'無與倫比的美麗'
print 'stringtest1',stringtest1
print 'stringtest2',stringtest2
excution of it returns:
stringtest1 無與倫比的美麗
stringtest2 無與倫比的美麗
But just typing the variables in the console:
>>> stringtest1
'\xe7\x84\xa1\xe8\x88\x87\xe5\x80\xab\xe6\xaf\x94\xe7\x9a\x84\xe7\xbe\x8e\xe9\xba\x97'
>>> stringtest2
u'\u7121\u8207\u502b\u6bd4\u7684\u7f8e\u9e97'
gets me that.
My problem is that I don't control how the information to be translated comes to my function. And it seems I have to bring it in the Unicode form, which is not accepted by the function.
So, how do I convert one thing into the other?
I've read Stack Overflow question Convert Unicode to a string in Python (containing extra symbols).
But this is not what I'm after. Urllib accepts the string object but not the Unicode object, both containing the same information
Well, at least in the eyes of the web application I'm sending the unchanged information to, I'm not sure if they're are still equivalent things in Python.
A:
When you get a unicode object and want to return a UTF-8 encoded byte string from it, use theobject.encode('utf8').
It seems strange that you don't know whether the incoming object is a str or unicode -- surely you do control the call sites to that function, too?! But if that is indeed the case, for whatever weird reason, you may need something like:
def ensureutf8(s):
if isinstance(s, unicode):
s = s.encode('utf8')
return s
which only encodes conditionally, that is, if it receives a unicode object, not if the object it receives is already a byte string. It returns a byte string in either case.
BTW, part of your confusion seems to be due to the fact that you don't know that just entering an expression at the interpreter prompt will show you its repr, which is not the same effect you get with print;-).
| Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python) | I want to send Chinese characters to be translated by an online service, and have the resulting English string returned. I'm using simple JSON and urllib for this.
And yes, I am declaring.
# -*- coding: utf-8 -*-
on top of my code.
Now everything works fine if I feed urllib a string type object, even if that object contains what would be Unicode information. My function is called translate.
For example:
stringtest1 = '無與倫比的美麗'
print translate(stringtest1)
results in the proper translation and doing
type(stringtest1)
confirms this to be a string object.
But if do
stringtest1 = u'無與倫比的美麗'
and try to use my translation function I get this error:
File "C:\Python27\lib\urllib.py", line 1275, in urlencode
v = quote_plus(str(v))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-8: ordinal not in range(128)
After researching a bit, it seems this is a common problem:
Problem: neither urllib2.quote nor urllib.quote encode the unicode strings arguments
urllib.quote throws exception on Unicode URL
Now, if I type in a script
stringtest1 = '無與倫比的美麗'
stringtest2 = u'無與倫比的美麗'
print 'stringtest1',stringtest1
print 'stringtest2',stringtest2
excution of it returns:
stringtest1 無與倫比的美麗
stringtest2 無與倫比的美麗
But just typing the variables in the console:
>>> stringtest1
'\xe7\x84\xa1\xe8\x88\x87\xe5\x80\xab\xe6\xaf\x94\xe7\x9a\x84\xe7\xbe\x8e\xe9\xba\x97'
>>> stringtest2
u'\u7121\u8207\u502b\u6bd4\u7684\u7f8e\u9e97'
gets me that.
My problem is that I don't control how the information to be translated comes to my function. And it seems I have to bring it in the Unicode form, which is not accepted by the function.
So, how do I convert one thing into the other?
I've read Stack Overflow question Convert Unicode to a string in Python (containing extra symbols).
But this is not what I'm after. Urllib accepts the string object but not the Unicode object, both containing the same information
Well, at least in the eyes of the web application I'm sending the unchanged information to, I'm not sure if they're are still equivalent things in Python.
| [
"When you get a unicode object and want to return a UTF-8 encoded byte string from it, use theobject.encode('utf8').\nIt seems strange that you don't know whether the incoming object is a str or unicode -- surely you do control the call sites to that function, too?! But if that is indeed the case, for whatever wei... | [
8
] | [] | [] | [
"python",
"string",
"unicode",
"unicode_string",
"urllib"
] | stackoverflow_0003669436_python_string_unicode_unicode_string_urllib.txt |
Q:
Are there existing python modules for dealing with / normalizing units of time represented as strings?
I am new to python and am doing an export and import to a new db.
I have a column on my export (to be imported) of strings for units of time, "20 minutes" "1.5 hours" "2 1/2 hours", etc.
I tried googling but couldn't really find any good phrases and kept coming up with information more related to datetime units rather than just units of time.
Fairly trivial to implement, but it seems like there is a good chance something exists.
Basically what I want to do is have the new DB just have the time in minutes, so I need to turn "1.5 hours" and "2 1/2 hours" into 90 and 150, respectively.
A:
For the first two formats it looks like you can use the excellent 3rd-party module dateutil, e.g.:
>>> from dateutil import parser
>>> dt = parser.parse('1.5 hours') # returns `datetime` object
>>> t = dt.time()
>>> t
datetime.time(1, 30)
This doesn't appear to work for "2 1/2 hours", however.
| Are there existing python modules for dealing with / normalizing units of time represented as strings? | I am new to python and am doing an export and import to a new db.
I have a column on my export (to be imported) of strings for units of time, "20 minutes" "1.5 hours" "2 1/2 hours", etc.
I tried googling but couldn't really find any good phrases and kept coming up with information more related to datetime units rather than just units of time.
Fairly trivial to implement, but it seems like there is a good chance something exists.
Basically what I want to do is have the new DB just have the time in minutes, so I need to turn "1.5 hours" and "2 1/2 hours" into 90 and 150, respectively.
| [
"For the first two formats it looks like you can use the excellent 3rd-party module dateutil, e.g.:\n>>> from dateutil import parser\n>>> dt = parser.parse('1.5 hours') # returns `datetime` object\n>>> t = dt.time()\n>>> t\ndatetime.time(1, 30)\n\nThis doesn't appear to work for \"2 1/2 hours\", however.\n"
] | [
1
] | [] | [] | [
"normalization",
"python",
"time"
] | stackoverflow_0003669635_normalization_python_time.txt |
Q:
Imaging library that supports 16bit tiffs
I had been using using PIL but I just found out that it doesn't support 16bit tiffs.
I need a library that can do:
1)Image conversion -->16bit tiff to jpeg
2)Image resize and crop and of jpegs
A:
ImageMagick supports 16bit Tiffs, and they have a wrapper for Python called PythonMagick.
| Imaging library that supports 16bit tiffs | I had been using using PIL but I just found out that it doesn't support 16bit tiffs.
I need a library that can do:
1)Image conversion -->16bit tiff to jpeg
2)Image resize and crop and of jpegs
| [
"ImageMagick supports 16bit Tiffs, and they have a wrapper for Python called PythonMagick.\n"
] | [
2
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0003669746_image_processing_python.txt |
Q:
I have text files in multiple languages. How to selectively delete one language in NLTK?
Maybe this is just impossible and I should give up all hope. Or maybe there's a really clever way to do it that I haven't thought of.
Here's two examples of what I've got:
يَبِسَ - يَيْبَسُ (yabisa,
yaybasu)[y-b-s][ي-ب-س] (To become dry,
stiff, rigid) 20:77 yabasan = dry.
يَسَّرَ - يُيَسِّرُ (yassara,
yuyassiru)[y-s-r][ي-س-ر] (To
facilitate, make it easy) 92:7
nuyassiruhuu = We will ease him.
and
Zu Hülfe! zu Hülfe! Help! Help!
Sonst bin ich verloren! Otherwise I am
lost! Zu Hülfe! Zu Hülfe! Help!
Help! Sonst bin ich
verloren! Otherwise I am lost! Der
listigen Schlange zum Opfer erkoren,
Selected as offering to the cunning
snake, Barmherzigige Götter! Merciful
Gods! Schon nahet sie sich, Already it
gets closer, Schon nahet sie
sich, Already it gets closer,
... it would be really annoying to go through and delete one language in order to further process these lines of text.
One way I was thinking this could be done in NLTK was to split the text into tokens, have some way of knowing the provenance of each token based on a small corpus, and then ask NLTK to 'reconstitute' only the tokens of my choosing. Is this just a wild fantasy?
A:
You can use nltk.NaiveBayesClassifier to do the job exactly as you said above.
The following link should help:
http://nltk.googlecode.com/svn/trunk/doc/book/ch06.html
It has an example of using nltk.NaiveBayesClassifier for gender identification. you use the same for language identification.
The first example you quoted will work well with nltk.NaiveBayesClassifier since the unicode set is completely different.
In the second example, there is a possibility of words like proper nouns spelled the same in both the languages which might cause some error in identification of the language.
| I have text files in multiple languages. How to selectively delete one language in NLTK? | Maybe this is just impossible and I should give up all hope. Or maybe there's a really clever way to do it that I haven't thought of.
Here's two examples of what I've got:
يَبِسَ - يَيْبَسُ (yabisa,
yaybasu)[y-b-s][ي-ب-س] (To become dry,
stiff, rigid) 20:77 yabasan = dry.
يَسَّرَ - يُيَسِّرُ (yassara,
yuyassiru)[y-s-r][ي-س-ر] (To
facilitate, make it easy) 92:7
nuyassiruhuu = We will ease him.
and
Zu Hülfe! zu Hülfe! Help! Help!
Sonst bin ich verloren! Otherwise I am
lost! Zu Hülfe! Zu Hülfe! Help!
Help! Sonst bin ich
verloren! Otherwise I am lost! Der
listigen Schlange zum Opfer erkoren,
Selected as offering to the cunning
snake, Barmherzigige Götter! Merciful
Gods! Schon nahet sie sich, Already it
gets closer, Schon nahet sie
sich, Already it gets closer,
... it would be really annoying to go through and delete one language in order to further process these lines of text.
One way I was thinking this could be done in NLTK was to split the text into tokens, have some way of knowing the provenance of each token based on a small corpus, and then ask NLTK to 'reconstitute' only the tokens of my choosing. Is this just a wild fantasy?
| [
"You can use nltk.NaiveBayesClassifier to do the job exactly as you said above.\nThe following link should help:\nhttp://nltk.googlecode.com/svn/trunk/doc/book/ch06.html\nIt has an example of using nltk.NaiveBayesClassifier for gender identification. you use the same for language identification.\nThe first example ... | [
2
] | [] | [] | [
"localization",
"nlp",
"nltk",
"python"
] | stackoverflow_0003570939_localization_nlp_nltk_python.txt |
Q:
python distutils, writing c extentions with generated source code
I have written a Python extension library in C and I am currently using distutils to build it. I also have a Python script that generates a .h file, which I would like to include with my extension.
Is it possible to setup a dependency like this with distutils? Will it be able to notice when my script changes, regenerate the .h file, and recompile the extension?
A:
You can do this by overrinding build_ext command from distutils.
from distutils.core import setup, Extension
from distutils.command.build_ext import build_ext as _build_ext
module=Extension(....) # The way to build your extension
class build_ext(_build_ext):
description = "Custom Build Process"
def initialize_options(self):
_build_ext.initialize_options(self)
def finalize_options(self):
_build_ext.finalize_options(self)
def run(self):
# Code to generate your .h
.....
# Start classic Extension build
_build_ext.run(self)
setup(...
ext_modules = [module],
cmdclass = { "build_ext": build_ext},
...)
So every time your build the extension, the .h is regenerated.
| python distutils, writing c extentions with generated source code | I have written a Python extension library in C and I am currently using distutils to build it. I also have a Python script that generates a .h file, which I would like to include with my extension.
Is it possible to setup a dependency like this with distutils? Will it be able to notice when my script changes, regenerate the .h file, and recompile the extension?
| [
"You can do this by overrinding build_ext command from distutils.\nfrom distutils.core import setup, Extension\nfrom distutils.command.build_ext import build_ext as _build_ext\n\nmodule=Extension(....) # The way to build your extension\n\nclass build_ext(_build_ext):\n description = \"Custom Build Process\"\n\n ... | [
0
] | [] | [] | [
"c",
"distutils",
"python"
] | stackoverflow_0003517301_c_distutils_python.txt |
Q:
Accessing variables by their names in a tuple
I need to access variables given their names, in the following way:
a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
names = ('a', 'b')
Then, I pass the variable names to a function, say numpy.hstack() to obtain the same result as with numpy.hstack((a,b)).
What is the best pythonic way to do so?
And what is the purpose? I have a function, that accepts names of numpy arrays and stacks the related arrays (defined in the function) together to process them. I need to create all possible combinations of these arrays, hence:
A combination (tuple) of array names is created.
The combination (tuple) is passed to a function as an argument.
The function concatenates related arrays and processes the result.
Hopefully this question is not too cryptic. Thanks for responses in advance :-)
A:
You can use the built-in function locals, which returns a dictionary representing the local namespace:
>>> a = 1
>>> locals()['a']
1
>>> a = 1; b = 2; c = 3
>>> [locals()[x] for x in ('a','b','c')]
[1, 2, 3]
You could also simply store your arrays in your own dictionary, or in a module.
A:
If i understood your question correctly, you would have to use locals() like this:
def lookup(dic, names):
return tuple(dic[name] for name in names)
...
a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
names = ('a', 'b')
numpy.hstack(lookup(locals(), names))
A:
Since you are using numpy, and wish to refer to arrays by names, it seems perhaps you should be using a recarray:
import numpy as np
import itertools as it
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.array([7,8,9])
names=('a','b','c')
arr=np.rec.fromarrays([a,b,c],names=names)
Once you define the recarray arr, you can access the individual columns by name:
In [57]: arr['a']
Out[57]: array([1, 2, 3])
In [58]: arr['c']
Out[58]: array([7, 8, 9])
So, to generate combinations of names, and combine the columns with np.hstack, you could do this:
for comb in it.combinations(names,2):
print(np.hstack(arr[c] for c in comb))
# [1 2 3 4 5 6]
# [1 2 3 7 8 9]
# [4 5 6 7 8 9]
A:
Maybe I misunderstood, but I would just use the built-in function eval and do the following. I don't know if it's particularly pythonic, mind you.
numpy.concatenate([eval(n) for n in names])
| Accessing variables by their names in a tuple | I need to access variables given their names, in the following way:
a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
names = ('a', 'b')
Then, I pass the variable names to a function, say numpy.hstack() to obtain the same result as with numpy.hstack((a,b)).
What is the best pythonic way to do so?
And what is the purpose? I have a function, that accepts names of numpy arrays and stacks the related arrays (defined in the function) together to process them. I need to create all possible combinations of these arrays, hence:
A combination (tuple) of array names is created.
The combination (tuple) is passed to a function as an argument.
The function concatenates related arrays and processes the result.
Hopefully this question is not too cryptic. Thanks for responses in advance :-)
| [
"You can use the built-in function locals, which returns a dictionary representing the local namespace:\n>>> a = 1\n>>> locals()['a']\n1\n\n>>> a = 1; b = 2; c = 3\n>>> [locals()[x] for x in ('a','b','c')]\n[1, 2, 3]\n\nYou could also simply store your arrays in your own dictionary, or in a module.\n",
"If i unde... | [
2,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003669651_python.txt |
Q:
Quick test if web-page offer asynchronous HTTP?
I am fetching current data from another company's web feed. It is a simple fetch of an XML file over HTTP. They haven't provided me with much documentation - just a URL.
Because I need to know as soon as possible when the data changes on their site, I need to poll frequently, which isn't a satisfactory solution for either side.
I was about to recommend to them that they set-up some sort of server push - presumably a long-term HTTP connection with asynchronous updates being sent by the server. I am not very familiar with any common protocols for this. It occurred to me that they may already offer this, and I have been too ignorant to realise.
Is there a common web-based protocol for server pushes over HTTP? If there is, is there a quick way I can check if they support it before I make myself look foolish by asking for something that is already available.
(Bonus points for a platform-independent, Python-based solution, but I will take what I can get.)
A:
I suggest you read this Wikipedia article on the subject. What you want is certainly possible, however it may not be supported by all browsers.
That said... I generally recommend against push technologies on the web, as they sap the resources of a server much faster than a request/response paradigm.
Perhaps there's another way? Polling frequently to see if the file changed is at least a small payload... why is it unsatisfactory for both sides?
Unless you can get the other company to change some of its practices -- perhaps to FTP you the new file, or call a webservice to let your company know that the file has changed -- you may be stuck with polling.
A:
What you want is HTTP Streaming; read this page. "Comet" is what this technology is commonly called. One implementation is the Ajax Push Engine (APE); the page I just gave you has several others.
Now I don't think it's possible to automatically test if a server supports a push technology because as of now there are no standards on this and the protocols used will vary depending on the implementation.
Alternatively you can use periodic refresh ("polling"), and the advantages of this technique are: you don't need additional software on the server, and this can be done without the cooperation of the server you are polling (it is unfeasible to use Comet if the server you are querying won't install it).
For more information and tricks to reduce bandwidth usage on polling, see this page. Some of these will require some effort from the server you are polling.
A:
I'm not aware of any method to test if a web server support a push technology.
You should ask to that company if a Comet approach could be adopted to avoid polling.
For Comet python-based solution, have a look here.
A:
To avoid unnecessary download I would check etags and Last-modified headers as described here
http://diveintopython3.ep.io/http-web-services.html
| Quick test if web-page offer asynchronous HTTP? | I am fetching current data from another company's web feed. It is a simple fetch of an XML file over HTTP. They haven't provided me with much documentation - just a URL.
Because I need to know as soon as possible when the data changes on their site, I need to poll frequently, which isn't a satisfactory solution for either side.
I was about to recommend to them that they set-up some sort of server push - presumably a long-term HTTP connection with asynchronous updates being sent by the server. I am not very familiar with any common protocols for this. It occurred to me that they may already offer this, and I have been too ignorant to realise.
Is there a common web-based protocol for server pushes over HTTP? If there is, is there a quick way I can check if they support it before I make myself look foolish by asking for something that is already available.
(Bonus points for a platform-independent, Python-based solution, but I will take what I can get.)
| [
"I suggest you read this Wikipedia article on the subject. What you want is certainly possible, however it may not be supported by all browsers.\nThat said... I generally recommend against push technologies on the web, as they sap the resources of a server much faster than a request/response paradigm. \nPerhaps the... | [
1,
1,
1,
1
] | [] | [] | [
"asynchronous",
"http",
"python",
"xmlhttprequest"
] | stackoverflow_0003668827_asynchronous_http_python_xmlhttprequest.txt |
Q:
Skip python "import" statements in exuberant ctags
if I have two files
file a.py:
class A():
pass
file b.py:
from a import A
b = A()
When I use ctags and press Ctrl+] in vim, it redirects me to import statement, not to class definition. In this code all is ok:
file a.py:
class A():
pass
file b.py:
from a import *
b = A()
A:
You can add the following line to your ~/.ctags file.
--python-kinds=-i
to have ctags skip indexing import statements. To see what else you can enable/disable:
ctags --list-kinds=python
A:
I use a mapping similar to the following which allows me to choose when there are multiple matches for a given tag:
nnoremap <C-]> :execute 'tj' expand('<cword>')<CR>zv
Also, check the man page for ctags, you might find there is a way to disable this type of tagging.
| Skip python "import" statements in exuberant ctags | if I have two files
file a.py:
class A():
pass
file b.py:
from a import A
b = A()
When I use ctags and press Ctrl+] in vim, it redirects me to import statement, not to class definition. In this code all is ok:
file a.py:
class A():
pass
file b.py:
from a import *
b = A()
| [
"You can add the following line to your ~/.ctags file.\n\n--python-kinds=-i\n\nto have ctags skip indexing import statements. To see what else you can enable/disable:\n\nctags --list-kinds=python\n\n",
"I use a mapping similar to the following which allows me to choose when there are multiple matches for a given ... | [
57,
1
] | [] | [] | [
"exuberant_ctags",
"python",
"vim"
] | stackoverflow_0003609433_exuberant_ctags_python_vim.txt |
Q:
python multi threading/ multiprocess code
In the code below, I am considering using mutli-threading or multi-process for fetching from url. I think pools would be ideal, Can anyone help suggest solution..
Idea: pool thread/process, collect data... my preference is process over thread, but not sure.
import urllib
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP')
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data
def main():
data_fp = fetch_quote(symbols)
# print data_fp
if __name__ =='__main__':
main()
A:
So here's a very simple example. It iterates over symbols passing one at a time to fetch_quote.
import urllib
import multiprocessing
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP')
def fetch_quote(symbol):
url = URL % '+'.join(symbol)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data
def main():
PROCESSES = 4
print 'Creating pool with %d processes\n' % PROCESSES
pool = multiprocessing.Pool(PROCESSES)
print 'pool = %s' % pool
print
results = [pool.apply_async(fetch_quote, sym) for sym in symbols]
print 'Ordered results using pool.apply_async():'
for r in results:
print '\t', r.get()
pool.close()
pool.join()
if __name__ =='__main__':
main()
A:
You have a process that request, several information at once. Let's try to fetch these information one by one.. Your code will be :
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data
def main():
for symbol in symbols:
data_fp = fetch_quote((symbol,))
print data_fp
if __name__ == "__main__":
main()
So main() call, one by one every url to get the data.
Let's multiprocess it with a pool:
import urllib
from multiprocessing import Pool
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data
def main():
for symbol in symbols:
data_fp = fetch_quote((symbol,))
print data_fp
if __name__ =='__main__':
pool = Pool(processes=5)
for symbol in symbols:
result = pool.apply_async(fetch_quote, [(symbol,)])
print result.get(timeout=1)
In the following main a new process is created to request each symbols urls.
Note: on python, since the GIL is present, multithreading must be mostly considered as a wrong solution.
For documentation see: Multiprocessing in python
A:
Actually it's possible to do it without neither. You can get it done in one thread using asynchronous calls, like for example twisted.web.client.getPage from Twisted Web.
| python multi threading/ multiprocess code | In the code below, I am considering using mutli-threading or multi-process for fetching from url. I think pools would be ideal, Can anyone help suggest solution..
Idea: pool thread/process, collect data... my preference is process over thread, but not sure.
import urllib
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP')
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data
def main():
data_fp = fetch_quote(symbols)
# print data_fp
if __name__ =='__main__':
main()
| [
"So here's a very simple example. It iterates over symbols passing one at a time to fetch_quote.\nimport urllib\nimport multiprocessing\n\nURL = \"http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv\"\nsymbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')\n#symbols = ('GGP')\n\ndef fet... | [
1,
1,
0
] | [
"As you would know multi-threading in Python is not actually multi-threading due to GIL. Essentially it's a single thread that's running at a given time. So in your program if you want multiple urls to be fetched at any given time, multi-threading might not be the way to go. Also after the crawl you store the data ... | [
-1
] | [
"multiprocess",
"multithreading",
"python"
] | stackoverflow_0003669791_multiprocess_multithreading_python.txt |
Q:
Pymedia installation on Windows with Python 2.6
I am trying to install latest version of Pymedia from sources. I have Python2.6 and there is no binary available.
Started with:
python setup.py build
and got the following messages:
Using WINDOWS configuration...
Path for OGG not found.
Path for VORBIS not found.
Path for FAAD not found.
Path for MP3LAME not found.
Path for VORBISENC not found.
Path for ALSA not found.
Continue building pymedia ? [Y,n]:Y
After putting the source code for OGG and VORBIS in a directory where I had put the pymedia source code, it was able to find those libs But when I put the source code libmp3lame-3.95 in that dir, it couldn't find it.
After reading setup.py file of pymedia , I also tried putting a dll for this library under libmp3lame/Release but it was still unable to locate it.
Can someone help? Is there a binary distribution available for Pymedia using Python 2.6 or higher?
A:
Somebody has done it, if you're just after pymedia for python2.6 on windows:
Have a look here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/
There's also a version for python2.7
A:
You need to install all of those modules separately, in a similar fashion (python setup.py install).
Those other modules are just prerequisites to pymedia, and need to be installed prior to installing pymedia.
It's kind of a pain with some libraries, and there are alternatives to take care of installing everything for you.
| Pymedia installation on Windows with Python 2.6 | I am trying to install latest version of Pymedia from sources. I have Python2.6 and there is no binary available.
Started with:
python setup.py build
and got the following messages:
Using WINDOWS configuration...
Path for OGG not found.
Path for VORBIS not found.
Path for FAAD not found.
Path for MP3LAME not found.
Path for VORBISENC not found.
Path for ALSA not found.
Continue building pymedia ? [Y,n]:Y
After putting the source code for OGG and VORBIS in a directory where I had put the pymedia source code, it was able to find those libs But when I put the source code libmp3lame-3.95 in that dir, it couldn't find it.
After reading setup.py file of pymedia , I also tried putting a dll for this library under libmp3lame/Release but it was still unable to locate it.
Can someone help? Is there a binary distribution available for Pymedia using Python 2.6 or higher?
| [
"Somebody has done it, if you're just after pymedia for python2.6 on windows:\nHave a look here:\nhttp://www.lfd.uci.edu/~gohlke/pythonlibs/\nThere's also a version for python2.7\n",
"You need to install all of those modules separately, in a similar fashion (python setup.py install).\nThose other modules are just... | [
8,
1
] | [] | [] | [
"python"
] | stackoverflow_0002141701_python.txt |
Q:
Using Windows 7 taskbar features in PyQt
I am looking for information on the integration of some of the new Windows 7 taskbar features into my PyQt applications.
Specifically if there already exists the possibility to use the new progress indicator (see here) and the quick links (www.petri.co.il/wp-content/uploads/new_win7_taskbar_features_8.gif).
If anyone could provide a few links or just a "not implemented yet", I'd be very grateful.
Thanks a lot.
A:
As quark said, the functionality is not in Qt 4.5, but you can call the windows API directly from Qt. Its a little bit of work though.
The new taskbar API is exposed through COM, so you can't use ctypes.windll . You need to create a .tlb file to access the functions. Get the interface definition for ITaskbarList from this forum post , or from the windows SDK. Save it to a file called e.g. TaskbarLib.idl .
Create the .tlb file. You'll probably need the Windows SDK, or get an IDL compiler from somewhere else.
midl TaskbarLib.idl /tlb TaskbarLib.tlb
Load the .tlb (you need the Win32 Extensions for Python, http://python.net/crew/skippy/win32/Downloads.html):
import comtypes.client as cc
cc.GetModule("TaskbarLib.tlb")
Create the TaskbarList object. The function for setting the progress bar is in the interface ITaskbarList3:
import comtypes.gen.TaskbarLib as tbl
taskbar = cc.CreateObject(
"{56FDF344-FD6D-11d0-958A-006097C9A090}",
interface=tbl.ITaskbarList3)
Now you can call the API functions:
taskbar.HrInit()
taskbar.SetProgressValue(self.winId(),40,100)
Here's a complete example script.
Sources:
1
2
A:
There is a Qt add-on that implements all the Windows 7 taskbar extensions. It is called Q7Goodies. It comes with a PyQt bindings, so this is probably the easiest way to take advantage of Windows 7 features in PyQt.
A:
Not implemented in Qt 4.5, but in the works for Qt 4.6 it appears. PyQt won't wrap 4.6 until Qt 4.6 is officially released, but you can play with the 4.6 snapshots or checkout the Qt repository and see if the C++ version supports the features you want. If it does then PyQt 4.6 will support it as well.
Added: The list of 4.6 features doesn't show explicit Windows 7 support, but that doesn't mean it won't have what you want, since, at least if I understand correctly, its likely they would fold that functionality into the existing widget.
| Using Windows 7 taskbar features in PyQt | I am looking for information on the integration of some of the new Windows 7 taskbar features into my PyQt applications.
Specifically if there already exists the possibility to use the new progress indicator (see here) and the quick links (www.petri.co.il/wp-content/uploads/new_win7_taskbar_features_8.gif).
If anyone could provide a few links or just a "not implemented yet", I'd be very grateful.
Thanks a lot.
| [
"As quark said, the functionality is not in Qt 4.5, but you can call the windows API directly from Qt. Its a little bit of work though.\n\nThe new taskbar API is exposed through COM, so you can't use ctypes.windll . You need to create a .tlb file to access the functions. Get the interface definition for ITaskbarLis... | [
23,
5,
3
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"taskbar",
"windows_7"
] | stackoverflow_0001736394_pyqt_pyqt4_python_taskbar_windows_7.txt |
Q:
Python - Make Script to Manipulate Windows File Paths but running on Linux
I have this script which processes lines containing windows file paths. However the script is running on Linux. Is there a way to change the os library to do Windows file path handling while running on linux?
I was thinking something like:
import os
os.pathsep = '\\'
(which doesn't work since os.pathsep is ; for some reason)
My script:
for line in INPUT.splitlines():
package_path,step_name = line.strip().split('>')
file_name = os.path.basename(package_path)
name = os.path.splitext(file_name)[0]
print template % (name,file_name,package_path)
A:
Look at the ntpath module
On Linux, I did:
>> import ntpath
>> ntpath.split("c:\windows\i\love\you.txt")
('c:\\windows\\i\\love', 'you.txt')
>> ntpath.splitext("c:\windows\i\love\you.txt")
('c:\\windows\\i\\love\\you', '.txt')
>> ntpath.basename("c:\windows\i\love\you.txt")
'you.txt'
A:
Try using os.sep = '\\'. os.pathsep is the separator used to separate the search path (PATH environment variable) on the os.
see os module description
A:
os.pathsep is the separator that is used for the PATH environment variable. You're looking for os.sep.
While I would generally advise against changing data in a module like that, it may suit your needs. Alternatively, you could implement basename yourself, something like package_path.split('\\')[-1]
| Python - Make Script to Manipulate Windows File Paths but running on Linux | I have this script which processes lines containing windows file paths. However the script is running on Linux. Is there a way to change the os library to do Windows file path handling while running on linux?
I was thinking something like:
import os
os.pathsep = '\\'
(which doesn't work since os.pathsep is ; for some reason)
My script:
for line in INPUT.splitlines():
package_path,step_name = line.strip().split('>')
file_name = os.path.basename(package_path)
name = os.path.splitext(file_name)[0]
print template % (name,file_name,package_path)
| [
"Look at the ntpath module\nOn Linux, I did:\n>> import ntpath \n>> ntpath.split(\"c:\\windows\\i\\love\\you.txt\")\n('c:\\\\windows\\\\i\\\\love', 'you.txt')\n>> ntpath.splitext(\"c:\\windows\\i\\love\\you.txt\")\n('c:\\\\windows\\\\i\\\\love\\\\you', '.txt')\n>> ntpath.basename(\"c:\\windows\\i\\love\\you.tx... | [
7,
3,
1
] | [] | [] | [
"filesystems",
"linux",
"python",
"windows"
] | stackoverflow_0003670673_filesystems_linux_python_windows.txt |
Q:
Django ORM, filtering objects by type with model inheritence
So I have two models...
Parent and Child.
Child extends Parent.
When I do
Parent.objects.all(), I get both the Parents and the Children.
I only want Parents
Is there a Parent.objects.filter() argument I can use to only get the Parent objects instead of the objects that extend parent?
A:
I've found a better way to solve this, using the django ORM and without the need for any changes to your models (such as an ABC):
class Parent(models.Model):
field1 = models.IntegerField()
field2 = models.IntegerField()
class Child(Parent):
field3 = models.IntegerField()
#Return all Parent objects that aren't also Child objects:
Parent.objects.filter(child=None)
This will result in the following query(conceptual, actual query may vary):
SELECT "ap_parent"."field1","ap_parent"."field2" FROM "ap_parent" INNER
JOIN "ap_child" ON
("parent"."parent_ptr_id" =
"ap_child"."parent_ptr_id") WHERE
"ap_child"."parent_ptr_id" IS NULL
A:
Maybe it's a good place to use an Abstract Base Class instead of using inheritance. The ABC hold all the fields that are common to your classes. So, in your case, you will have one ABC mostly defined has your current Parent Class and 2 classes that will inherit from the ABC, that correspond to your Parent and Child classes.
class ABC(models.Model):
field1 = models.CharField(max_length=200)
field2 = models.CharField(max_length=100)
....
class Meta:
abstract = True
class Parent(ABC):
....
class Child(ABC):
parent = models.ForeignKey(Parent)
Check here for more info : Model inheritance and Abstract base classes
A:
Are you sure that inheritance is the right solution here? What about this?
class MyModel(models.Model):
foo = models.IntegerField()
parent = models.ForeignKey("self", null=True)
Then you can query for all objects that are parents like this:
parents = MyModel.objects.filter(parent__isnull=True)
children = MyModel.objects.filter(parent__isnull=False)
@Alex: filtering according to type won't work. Django's inheritance model isn't really that rich. E.g. with these models:
class Parent(models.Model):
foo = models.CharField(max_length=5)
class Child(Parent):
bar = models.CharField(max_length=5)
you get this behavior:
In [1]: from myexample.models import Parent, Child
In [2]: p = Parent(foo='x')
In [3]: p.save()
In [4]: p2 = Parent(foo='y')
In [5]: p2.save()
In [6]: c1 = Child(bar='1', foo='a')
In [7]: c1.save()
In [8]: c2 = Child(bar='2', foo='b')
In [9]: c2.save()
In [10]: len(Parent.objects.all())
Out[10]: 4
In [11]: len([p for p in Parent.objects.all() if type(p) is Parent])
Out[11]: 4
In [12]: len(Child.objects.all())
Out[12]: 2
A:
The filter method is essentially about building the WHERE clause in the SQL query, and that's a realy awkward place to be quibbling about exact types. What about, instead...:
(p for Parent.objects.all() if type(p) is Parent)
this is an iterable (use [ ] on the outside instead of ( ) if you want a list instead) for all objects that are exactly of type Parent - no subclasses allowed.
| Django ORM, filtering objects by type with model inheritence | So I have two models...
Parent and Child.
Child extends Parent.
When I do
Parent.objects.all(), I get both the Parents and the Children.
I only want Parents
Is there a Parent.objects.filter() argument I can use to only get the Parent objects instead of the objects that extend parent?
| [
"I've found a better way to solve this, using the django ORM and without the need for any changes to your models (such as an ABC):\n\nclass Parent(models.Model):\n field1 = models.IntegerField()\n field2 = models.IntegerField()\n\nclass Child(Parent):\n field3 = models.IntegerField()\n\n#Return all Parent ... | [
13,
4,
2,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001447742_django_django_models_python.txt |
Q:
Parsing FLV header (duration) of remote file in Java
I'm looking for an example of parsing an FLV header for duration specifically in Java. Given the URL of an FLV file I want to download the header only and parse out the duration. I have the FLV spec but I want an example. Python or PHP would be OK too but Java is preferred.
A:
Do you have problems downloading the header or parsing it? if it's downloading then use this code:
URL url = new URL(fileUrl);
InputStream dis = url.openStream();
byte[] header = new byte[HEADER_SIZE];
dis.read(header);
You can wrap InputStream with DataInputStream if you want to read int's rather than bytes.
After that just look at getInfo method from PHP-FLV Info or read the spec.
A:
As the-alchemist states in this other question:
The Red5 project has a class called
FLVReader which does what you want.
It's LGPL licensed.
I've tried it and it works fine. You'll need this libraries:
Red5 library jar for use when building applications
Apache Commons Logging
Apache MINA
Getting the FLV video duration is as simple as this:
FLVReader flvReader = new FLVReader(...); // Can use a File or a ByteBuffer as input
long duration = flvReader.getDuration(); // Returns the duration in milliseconds
| Parsing FLV header (duration) of remote file in Java | I'm looking for an example of parsing an FLV header for duration specifically in Java. Given the URL of an FLV file I want to download the header only and parse out the duration. I have the FLV spec but I want an example. Python or PHP would be OK too but Java is preferred.
| [
"Do you have problems downloading the header or parsing it? if it's downloading then use this code:\nURL url = new URL(fileUrl);\nInputStream dis = url.openStream();\nbyte[] header = new byte[HEADER_SIZE];\ndis.read(header);\n\nYou can wrap InputStream with DataInputStream if you want to read int's rather than byte... | [
1,
0
] | [] | [] | [
"flash",
"flv",
"java",
"python"
] | stackoverflow_0001313640_flash_flv_java_python.txt |
Q:
how to select a long list of id's in sql using python
I have a very large db that I am working with, and I need to know how to select a large set of id's which doesn't have any real pattern to them. This is segment of code I have so far:
longIdList = [1, 3, 5 ,8 ....................................]
for id in longIdList
sql = "select * from Table where id = %s" %id
result = cursor.execute(sql)
print result.fetchone()
I was thinking, That there must be a quicker way of doing this... I mean my script needs to search through a db that has over 4 million id's. Is there a way that I can use a select command to grab them all in one shot. could I use the where statement with a list of id's? Thanks
A:
Yes, you can use SQL's IN() predicate to compare a column to a set of values. This is standard SQL and it's supported by every SQL database.
There may be a practical limit to the number of values you can put in an IN() predicate before it becomes too inefficient or simply exceeds a length limit on SQL queries. The largest practical list of values depends on what database you use (in Oracle it's 1000, MS SQL Server it's around 2000). My feeling is that if your list exceeds a few dozen values, I'd seek another solution.
For example, @ngroot suggests using a temp table in his answer. For analysis of this solution, see this blog by StackOverflow regular @Quassnoi: Passing parameters in MySQL: IN list vs. temporary table.
Parameterizing a list of values into an SQL query a safe way can be tricky. You should be mindful of the risk of SQL injection.
Also see this popular question on Stack Overflow: Parameterizing a SQL IN clause?
A:
You can use IN to look for multiple items simultaneously:
SELECT * FROM Table WHERE id IN (x, y, z, ...)
So maybe something like:
sql = "select * from Table where id in (%s)" % (', '.join(str(id) for id in longIdList))
A:
Serialize the list in some fashion (comma-separated or XML would be reasonable choices), then have a stored procedure on the other side that will deserialize the list into a temp table. You can then do an INNER JOIN against the temp table.
| how to select a long list of id's in sql using python | I have a very large db that I am working with, and I need to know how to select a large set of id's which doesn't have any real pattern to them. This is segment of code I have so far:
longIdList = [1, 3, 5 ,8 ....................................]
for id in longIdList
sql = "select * from Table where id = %s" %id
result = cursor.execute(sql)
print result.fetchone()
I was thinking, That there must be a quicker way of doing this... I mean my script needs to search through a db that has over 4 million id's. Is there a way that I can use a select command to grab them all in one shot. could I use the where statement with a list of id's? Thanks
| [
"Yes, you can use SQL's IN() predicate to compare a column to a set of values. This is standard SQL and it's supported by every SQL database.\nThere may be a practical limit to the number of values you can put in an IN() predicate before it becomes too inefficient or simply exceeds a length limit on SQL queries. ... | [
6,
4,
3
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0003670961_python_sql.txt |
Q:
Working around Python bug in different versions
I've come across a bug in Python (at least in 2.6.1) for the bytearray.fromhex function. This is what happens if you try the example from the docstring:
>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str
This example works fine in Python 2.7, and I want to know the best way of coding around the problem. I don't want to always convert to unicode as it's a performance hit, and testing which Python version is being used feels wrong.
So is there a better way to code around this sort of problem so that it will work for all versions, preferably without slowing it down for the working Pythons?
A:
For cases like this it's good to remember that a try block is very cheap if no exception is thrown. So I'd use:
try:
x = bytearray.fromhex(some_str)
except TypeError:
# Work-around for Python 2.6 bug
x = bytearray.fromhex(unicode(some_str))
This lets Python 2.6 work with a small performance hit, but 2.7 shouldn't suffer at all. It's certainly preferable to checking Python version explicitly!
The bug itself (and it certainly does seem to be one) is still present in Python 2.6.5, but I couldn't find any mention of it at bugs.python.org, so maybe it was fixed by accident in 2.7! It looks like a back-ported Python 3 feature that wasn't tested properly in 2.6.
A:
You can also create your own function to do the work, conditionalized on what you need:
def my_fromhex(s):
return bytearray.fromhex(s)
try:
my_fromhex('hello')
except TypeError:
def my_fromhex(s):
return bytearray.fromhex(unicode(s))
and then use my_fromhex in your code. This way, the exception only happens once, and during your runtime, the correct function is used without excess unicode casting or exception machinery.
| Working around Python bug in different versions | I've come across a bug in Python (at least in 2.6.1) for the bytearray.fromhex function. This is what happens if you try the example from the docstring:
>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str
This example works fine in Python 2.7, and I want to know the best way of coding around the problem. I don't want to always convert to unicode as it's a performance hit, and testing which Python version is being used feels wrong.
So is there a better way to code around this sort of problem so that it will work for all versions, preferably without slowing it down for the working Pythons?
| [
"For cases like this it's good to remember that a try block is very cheap if no exception is thrown. So I'd use:\ntry:\n x = bytearray.fromhex(some_str)\nexcept TypeError:\n # Work-around for Python 2.6 bug \n x = bytearray.fromhex(unicode(some_str))\n\nThis lets Python 2.6 work with a small performance hi... | [
8,
3
] | [] | [] | [
"python",
"python_2.6",
"python_2.7"
] | stackoverflow_0003670816_python_python_2.6_python_2.7.txt |
Q:
How, to prevent image cache by browser?
in my Pylons app i write a script to autogenerate thumbnail, from image geting by url.
To generate thumbnail i use PIL(python)
W wont to prevent image cache by browser.
I can't use after src ?[random_number] because the site, where i past this image must be static.
I try to send headers
response.headers['Cache-Control'] = 'no-store,no-cache, must-revalidate,post-check=0, pre-check=0,max-age=0'
But still don't work, the browser cache this image,
Can anyone help me to resolved this problem?
Thanks in advance.
A:
Traditionally, you need additional headers to catch most browsers, and even then some will still cache it. Even browsers that support the Cache-Control header (which is part of HTTP 1.1) may be connecting through an HTTP 1.0 proxy that strips out nonstandard headers. I'd try also adding an explicit Expires header with the date and time the image is sent (or just a fixed date in the past) and also a Pragma header with the value "no-cache."
response.headers['Cache-Control'] = 'no-store,no-cache, must-revalidate,post-check=0, pre-check=0,max-age=0'
response.headers['Expires'] = 'Wed, 01 Sep 2010 00:00:00 GMT'
response.headers['Pragma'] = 'no-cache'
| How, to prevent image cache by browser? | in my Pylons app i write a script to autogenerate thumbnail, from image geting by url.
To generate thumbnail i use PIL(python)
W wont to prevent image cache by browser.
I can't use after src ?[random_number] because the site, where i past this image must be static.
I try to send headers
response.headers['Cache-Control'] = 'no-store,no-cache, must-revalidate,post-check=0, pre-check=0,max-age=0'
But still don't work, the browser cache this image,
Can anyone help me to resolved this problem?
Thanks in advance.
| [
"Traditionally, you need additional headers to catch most browsers, and even then some will still cache it. Even browsers that support the Cache-Control header (which is part of HTTP 1.1) may be connecting through an HTTP 1.0 proxy that strips out nonstandard headers. I'd try also adding an explicit Expires header ... | [
0
] | [] | [] | [
"caching",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0003671321_caching_image_python_python_imaging_library.txt |
Q:
BeautifulSoup chokes on paths with back slashes
I wrote a script to automate the process of creating an image gallery. I used os.path.join() for creating paths to new image directories.
I only relized after creating all the galleries that using os.path.join() was not such a good idea as it creates paths with \ (on windows) which causes problems with firefox (it doesn't seem to understand the path format and cant find the images).
Id rather not have to create all the galleries again since the gallery headers have to be entered manually. I thought BeautifulSoups prettify() would fix the paths but it chokes on the backslashes.
e.g.
input:
<td><a rel="group" href="images\042.jpg"><img class="gimage" src="images\thumbnails\thumb_042.jpg" alt=""></a></td>
output:
<td>
<a rel="example_group" href="images">
<img class="gimage" src="images humbnails humb_042.jpg" alt="" />
</a>
</td>
How can I fix the paths?
A:
In this case, per the comments, it appears that the problem can be solved with a
global substitution of / for \:
import fileinput
import sys
for line in fileinput.input(['test.html'], inplace=True, backup='.bak'):
sys.stdout.write(line.replace('\\','/'))
| BeautifulSoup chokes on paths with back slashes | I wrote a script to automate the process of creating an image gallery. I used os.path.join() for creating paths to new image directories.
I only relized after creating all the galleries that using os.path.join() was not such a good idea as it creates paths with \ (on windows) which causes problems with firefox (it doesn't seem to understand the path format and cant find the images).
Id rather not have to create all the galleries again since the gallery headers have to be entered manually. I thought BeautifulSoups prettify() would fix the paths but it chokes on the backslashes.
e.g.
input:
<td><a rel="group" href="images\042.jpg"><img class="gimage" src="images\thumbnails\thumb_042.jpg" alt=""></a></td>
output:
<td>
<a rel="example_group" href="images">
<img class="gimage" src="images humbnails humb_042.jpg" alt="" />
</a>
</td>
How can I fix the paths?
| [
"In this case, per the comments, it appears that the problem can be solved with a\nglobal substitution of / for \\:\nimport fileinput\nimport sys\nfor line in fileinput.input(['test.html'], inplace=True, backup='.bak'):\n sys.stdout.write(line.replace('\\\\','/'))\n\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"path",
"python"
] | stackoverflow_0003662213_beautifulsoup_path_python.txt |
Q:
Problems accessing a variable which is casted into pointer to array of int with ctypes in python
I have C code which uses a variable data, which is a large 2d array created with malloc with variable size. Now I have to write an interface, so that the C functions can be called from within Python. I use ctypes for that.
C code:
FOO* pytrain(float **data){
FOO *foo = foo_autoTrain((float (*)[])data);
return foo;
}
with
FOO *foo_autoTrain(float data[nrows][ncols]) {...}
Python code:
autofoo=cdll.LoadLibrary("./libfoo.so")
... data gets filled ...
foo = autofoo.pytrain(pointer(pointer(p_data)))
My problem is, that when I try to access data in foo_autoTrain I only get 0.0 or other random values and a seg fault later. So how could I pass float (*)[])data to foo_autoTrain in Python?
Please don't hesitate to point out, if I described some part of my problem not sufficient enough.
A:
It looks to me like the issue is a miscomprehension of how multidimensional arrays work in C. An expression like a[r][c] can mean one of two things depending on the type of a. If the type of a were float **, then the expression would mean a double pointer-offset dereference, something like this if done out long-hand:
float *row = a[r]; // First dereference yields a pointer to the row array
return row[c] // Second dereference yields the value
If the type of a were instead float (*)[ncols], then the expression becomes simply shorthand for shaping a contiguous, one-dimensional memory region as a multi-dimensional array:
float *flat = (float *)a;
return flat[(r * ncols) + c]; // Same as a[r][c]
So in your C code, the type of pytrain()'s argument should be either float * or float (*)[ncols] and your Python code should look something like the following (assuming you're using NumPy for your array data):
c_float_p = ctypes.POINTER(ctypes.c_float)
autofoo.pytrain.argtypes = [c_float_p]
data = numpy.array([[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], dtype=numpy.float32)
data_p = data.ctypes.data_as(c_float_p)
autofoo.pytrain(data_p)
And if you are in fact using NumPy, check out the ctypes page of the SciPy wiki.
| Problems accessing a variable which is casted into pointer to array of int with ctypes in python | I have C code which uses a variable data, which is a large 2d array created with malloc with variable size. Now I have to write an interface, so that the C functions can be called from within Python. I use ctypes for that.
C code:
FOO* pytrain(float **data){
FOO *foo = foo_autoTrain((float (*)[])data);
return foo;
}
with
FOO *foo_autoTrain(float data[nrows][ncols]) {...}
Python code:
autofoo=cdll.LoadLibrary("./libfoo.so")
... data gets filled ...
foo = autofoo.pytrain(pointer(pointer(p_data)))
My problem is, that when I try to access data in foo_autoTrain I only get 0.0 or other random values and a seg fault later. So how could I pass float (*)[])data to foo_autoTrain in Python?
Please don't hesitate to point out, if I described some part of my problem not sufficient enough.
| [
"It looks to me like the issue is a miscomprehension of how multidimensional arrays work in C. An expression like a[r][c] can mean one of two things depending on the type of a. If the type of a were float **, then the expression would mean a double pointer-offset dereference, something like this if done out long-... | [
0
] | [] | [] | [
"casting",
"ctypes",
"multidimensional_array",
"pointers",
"python"
] | stackoverflow_0003523250_casting_ctypes_multidimensional_array_pointers_python.txt |
Q:
Why Django's ModelAdmin uses lists over tuples and vice-versa
From the Django intro tutorial, in \mysite\polls\admin.py:
from django.contrib import admin
#...
class PollAdmin(admin.ModelAdmin):
#...
inlines = [ChoiceInline]
list_display = ('question', 'pub_date', 'was_published_today')
list_filter = ['pub_date']
admin.site.register(Poll, PollAdmin)
Why do inlines and list_filter both use lists, while list_display uses a tuple? Do inlines and list_filters need to be mutable for some reason?
I'm just trying to understand the design decision here.
A:
It doesn't matter which you use because Django (and you) will never change them during runtime. All that's important is that the value be an iterable of strings. I often use foo = ["something"] when there is only one element because I've gotten nailed so often when I accidentally say foo = ("somthing") instead of foo = ("something",).
I would put this one-element-tuple-notation issue on my list of Python irritants, right after "significant whitespace". That said, I still love the language.
| Why Django's ModelAdmin uses lists over tuples and vice-versa | From the Django intro tutorial, in \mysite\polls\admin.py:
from django.contrib import admin
#...
class PollAdmin(admin.ModelAdmin):
#...
inlines = [ChoiceInline]
list_display = ('question', 'pub_date', 'was_published_today')
list_filter = ['pub_date']
admin.site.register(Poll, PollAdmin)
Why do inlines and list_filter both use lists, while list_display uses a tuple? Do inlines and list_filters need to be mutable for some reason?
I'm just trying to understand the design decision here.
| [
"It doesn't matter which you use because Django (and you) will never change them during runtime. All that's important is that the value be an iterable of strings. I often use foo = [\"something\"] when there is only one element because I've gotten nailed so often when I accidentally say foo = (\"somthing\") instead... | [
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003671437_django_python.txt |
Q:
Setup Python variable environment on ubuntu
how to set or create new environment variables in ubuntu(10.04, 64bits), for a python library. I have to configure
PYTHONPATH
library_HOME
library_data
A:
In bash, you can use export:
export PYTHONPATH=/path/to/library
export library_HOME=/path/to/library_HOME
etc.
You can put these lines in your ~/.bashrc or ~/.bash_profile to have them loaded every time you start a login shell.
| Setup Python variable environment on ubuntu | how to set or create new environment variables in ubuntu(10.04, 64bits), for a python library. I have to configure
PYTHONPATH
library_HOME
library_data
| [
"In bash, you can use export:\nexport PYTHONPATH=/path/to/library\nexport library_HOME=/path/to/library_HOME\netc.\n\nYou can put these lines in your ~/.bashrc or ~/.bash_profile to have them loaded every time you start a login shell.\n"
] | [
3
] | [] | [] | [
"python",
"ubuntu_10.04"
] | stackoverflow_0003671837_python_ubuntu_10.04.txt |
Q:
python problems with integer comparision
I'm using a function in a card game, to check the value of each card, and see if it is higher than the last card played.
def Valid(card):
prev=pile[len(pile)-1]
cardValue=0
prevValue=0
if card[0]=="J":
cardValue=11
elif card[0]=="Q":
cardValue=12
elif card[0]=="K":
cardValue=13
elif card[0]=="A":
cardValue=14
else:
cardValue=card[0]
prevValue=prev[0]
if cardValue>prevValue:
return True
elif cardValue==prevValue:
return True
else:
return False
The problem is, whenever I get a facecard, it doesnt seem to work.
It thinks 13>2 is True, for example
edit: sorry, I meant it thinks 13>2 is False
A:
I think what you meant is that it is saying that "2" > 13 which is true. You need to change
cardValue=card[0]
to
cardValue=int(card[0])
A:
Why not use a dictionary instead of a big cascade of if/else blocks?
cards = dict(zip((str(x) for x in range(1, 11)), range(1, 11)))
cards['J'] = 11
cards['Q'] = 12
cards['K'] = 13
cards['A'] = 14
then
cardValue = cards[card[0]]
A:
Using a dict will make your code much cleaner:
Replace:
if card[0]=="J":
cardValue=11
elif card[0]=="Q":
cardValue=12
elif card[0]=="K":
cardValue=13
elif card[0]=="A":
cardValue=14
else:
cardValue=card[0]
with:
cardMap = { 'J': 11, 'Q':12, 'K': 13, 'A': 14 }
cardValue = cardMap.get(card[0]) or int(card[0])
| python problems with integer comparision | I'm using a function in a card game, to check the value of each card, and see if it is higher than the last card played.
def Valid(card):
prev=pile[len(pile)-1]
cardValue=0
prevValue=0
if card[0]=="J":
cardValue=11
elif card[0]=="Q":
cardValue=12
elif card[0]=="K":
cardValue=13
elif card[0]=="A":
cardValue=14
else:
cardValue=card[0]
prevValue=prev[0]
if cardValue>prevValue:
return True
elif cardValue==prevValue:
return True
else:
return False
The problem is, whenever I get a facecard, it doesnt seem to work.
It thinks 13>2 is True, for example
edit: sorry, I meant it thinks 13>2 is False
| [
"I think what you meant is that it is saying that \"2\" > 13 which is true. You need to change \ncardValue=card[0]\n\nto\ncardValue=int(card[0])\n\n",
"Why not use a dictionary instead of a big cascade of if/else blocks?\ncards = dict(zip((str(x) for x in range(1, 11)), range(1, 11)))\ncards['J'] = 11\ncards['Q']... | [
11,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0003671936_python.txt |
Q:
How to deploy this "Python+twill+mechanize" combination to "Google App Engine"?
I've been trying to pass my login and password from Python script to the eBay sign-in page. Later I want this script to be run from "Google App Engine"
I was suggested to use "mechanize". Unfortunately, it didn't work for me:
IDLE 1.2.4
>>> import re
>>> import mechanize
>>> br = mechanize.Browser()
>>> br.open("https://signin.ebay.com")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
br.open("https://signin.ebay.com")
File "build\bdist.win32\egg\mechanize\_mechanize.py", line 203, in open
return self._mech_open(url, data, timeout=timeout)
File "build\bdist.win32\egg\mechanize\_mechanize.py", line 255, in _mech_open
raise response
httperror_seek_wrapper: HTTP Error 403: request disallowed by robots.txt
>>>
Earlier I was trying to use Python and twill - it didn't work either until one supporter suggested that I download the latest version of mechanize and then perform the following steps:
Locate the following folder on my computer: "C:\Python25\Lib\site-packages\twill\other_packages\_mechanize_dist"
Change its name to "_mechanize_dist_backup" (the full path, thus, should be "C:\Python25\Lib\site-packages\twill\other_packages\_mechanize_dist_backup")
Copy the "mechanize" folder (which is located in "mechanize-0.2.2" - the folder that I had downloaded and unzipped from the "mechanize" official site) and paste it in "C:\Python25\Lib\site-packages\twill\other_packages" (the full path, thus, being "C:\Python25\Lib\site-packages\twill\other_packages\mechanize")
Change its name to "_mechanize_dist" (the full path being "C:\Python25\Lib\site-packages\twill\other_packages_mechanize_dist")
Copy "ClientForm" file from "_mechanize_dist_backup" and paste it in "_mechanize_dist" (in fact, I found there two files named "ClientForm": one is a python file, another one is a compiled python file - I copied and pasted both of them).
After I had performed all these steps, I tried to log in to my eBay account from the twill shell in Python and it worked!!! I could even log in to my Yahoo mail box in the same way and check my mails!
But now I have a dilemma: I don't know how I could deploy my script to "Google App Engine".
Earlier I had been advised that if I want to use third-party libraries in App Engine projects, I simply have to include them with my application when I deploy it - in case with twill, for example, I just need to copy the twill folder into my application's folder and deploy it.
But now not only do I have this twill folder as a third-party library to be included, but also all these changes performed in "C:\Python25" (in "C:\Python25\Lib\site-packages\twill\other_packages", to be precise) while my application folder - the one in which I have my script ("my_script.py" file) - is located on "E" disk.
Can anybody, please, give me some suggestions here?
A:
The error message is indicating that mechanize is obeying the site's robots.txt file for you.
You should use eBay's API if you want to access their site in an automated way. If you don't, and build your own solution that ignores robots.txt, don't be surprised when they block you, and complain to Google about automated queries coming from App Engine from your app.
A:
As for GAE deployment issue, @brilliant, looks like the code you're dealing is all pure python 2.5 (the only really blocking issue would be if it isn't -- no binary extensions allowed, no code requiring Python 2.6 or better allowed, and that's just the way it is on GAE at this time).
So, under this assumption, the only issue w/deploying the code on App Engine is having all the code, NOT in site-packages (from which of course GAE's dev_appserver.py deploys absolutely nothing, nada, zilch), but rather in your GAE project's directory (I suggest a recursive zip of all the .py files, only -- remove all the .pyc files, in particular, before you zip -r it;-).
All in all, it's just a question of a couple of appropriate shell commands: cp -R then zip -r (probably harder on non-unixy shells, but, hey, even on Windows you can do it with bash from cygwin... in any case, it's hardly a "development" issue, per se;-).
| How to deploy this "Python+twill+mechanize" combination to "Google App Engine"? | I've been trying to pass my login and password from Python script to the eBay sign-in page. Later I want this script to be run from "Google App Engine"
I was suggested to use "mechanize". Unfortunately, it didn't work for me:
IDLE 1.2.4
>>> import re
>>> import mechanize
>>> br = mechanize.Browser()
>>> br.open("https://signin.ebay.com")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
br.open("https://signin.ebay.com")
File "build\bdist.win32\egg\mechanize\_mechanize.py", line 203, in open
return self._mech_open(url, data, timeout=timeout)
File "build\bdist.win32\egg\mechanize\_mechanize.py", line 255, in _mech_open
raise response
httperror_seek_wrapper: HTTP Error 403: request disallowed by robots.txt
>>>
Earlier I was trying to use Python and twill - it didn't work either until one supporter suggested that I download the latest version of mechanize and then perform the following steps:
Locate the following folder on my computer: "C:\Python25\Lib\site-packages\twill\other_packages\_mechanize_dist"
Change its name to "_mechanize_dist_backup" (the full path, thus, should be "C:\Python25\Lib\site-packages\twill\other_packages\_mechanize_dist_backup")
Copy the "mechanize" folder (which is located in "mechanize-0.2.2" - the folder that I had downloaded and unzipped from the "mechanize" official site) and paste it in "C:\Python25\Lib\site-packages\twill\other_packages" (the full path, thus, being "C:\Python25\Lib\site-packages\twill\other_packages\mechanize")
Change its name to "_mechanize_dist" (the full path being "C:\Python25\Lib\site-packages\twill\other_packages_mechanize_dist")
Copy "ClientForm" file from "_mechanize_dist_backup" and paste it in "_mechanize_dist" (in fact, I found there two files named "ClientForm": one is a python file, another one is a compiled python file - I copied and pasted both of them).
After I had performed all these steps, I tried to log in to my eBay account from the twill shell in Python and it worked!!! I could even log in to my Yahoo mail box in the same way and check my mails!
But now I have a dilemma: I don't know how I could deploy my script to "Google App Engine".
Earlier I had been advised that if I want to use third-party libraries in App Engine projects, I simply have to include them with my application when I deploy it - in case with twill, for example, I just need to copy the twill folder into my application's folder and deploy it.
But now not only do I have this twill folder as a third-party library to be included, but also all these changes performed in "C:\Python25" (in "C:\Python25\Lib\site-packages\twill\other_packages", to be precise) while my application folder - the one in which I have my script ("my_script.py" file) - is located on "E" disk.
Can anybody, please, give me some suggestions here?
| [
"The error message is indicating that mechanize is obeying the site's robots.txt file for you.\nYou should use eBay's API if you want to access their site in an automated way. If you don't, and build your own solution that ignores robots.txt, don't be surprised when they block you, and complain to Google about aut... | [
2,
2
] | [] | [] | [
"deployment",
"google_app_engine",
"mechanize",
"python",
"twill"
] | stackoverflow_0003670701_deployment_google_app_engine_mechanize_python_twill.txt |
Q:
Django / Python, Using Radio Button for boolean field in Modelform?
I'm trying to use a radio button in my modelform but its just outputting nothing when I do an override this way (it just prints the label in my form, not the radio buttosn, if I don't do the override it does a standard checkbox)
My modelfield is defined as:
Class Mymodelname (models.Model):
fieldname = models.BooleanField(max_length=1, verbose_name='ECG')
My modelform is defined as such:
from django.forms import ModelForm
from django import forms
from web1.myappname.models import Mymodelname
class createdbentry(forms.ModelForm):
choices = ( (1,'Yes'),
(0,'No'),
)
fieldname = forms.ChoiceField(widget=forms.RadioSelect
(choices=choices))
I would greatly appreciate any advice on what I'm doing wrong.. thanks
class Meta:
model = Mymodelname
A:
Does this work?
class createdbentry(forms.ModelForm):
choices = ( (1,'Yes'),
(0,'No'),
)
class Meta:
model = Mymodelname
def __init__(self, *args, **kwargs):
super(createdbentry, self).__init__(*args, **kwargs)
BinaryFieldsList = ['FirstFieldName', 'SecondFieldName', 'ThirdFieldName']
for field in BinaryFieldsList:
self.fields[field].widget = forms.RadioSelect(choices=choices)
| Django / Python, Using Radio Button for boolean field in Modelform? | I'm trying to use a radio button in my modelform but its just outputting nothing when I do an override this way (it just prints the label in my form, not the radio buttosn, if I don't do the override it does a standard checkbox)
My modelfield is defined as:
Class Mymodelname (models.Model):
fieldname = models.BooleanField(max_length=1, verbose_name='ECG')
My modelform is defined as such:
from django.forms import ModelForm
from django import forms
from web1.myappname.models import Mymodelname
class createdbentry(forms.ModelForm):
choices = ( (1,'Yes'),
(0,'No'),
)
fieldname = forms.ChoiceField(widget=forms.RadioSelect
(choices=choices))
I would greatly appreciate any advice on what I'm doing wrong.. thanks
class Meta:
model = Mymodelname
| [
"Does this work?\nclass createdbentry(forms.ModelForm):\n\n choices = ( (1,'Yes'),\n (0,'No'),\n )\n\n class Meta:\n model = Mymodelname\n\n def __init__(self, *args, **kwargs):\n super(createdbentry, self).__init__(*args, **kwargs)\n\n BinaryFieldsList = ['... | [
3
] | [] | [] | [
"django",
"django_forms",
"forms",
"python",
"radio_button"
] | stackoverflow_0003672221_django_django_forms_forms_python_radio_button.txt |
Q:
HtmlWindow doesn't display page in wxpython notebook layout
I have a project set up as a notebook layout using wxpython. I am trying to create a help panel. The HtmlWindow object doesn't display the html page on the panel. No errors are displayed and a call to HtmlWindow.GetOpenedPage() returns the page name.
import wx
import wx.html as html
class HelpPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
self.panel = wx.Panel(self, -1)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.help = html.HtmlWindow(self.panel, -1, style=wx.NO_BORDER)
self.help.LoadFile('help.html')
self.sizer.Add(self.help)
self.panel.SetSizer(self.sizer)
self.Show(True)
def add_help_panel(self, parent, evt):
self.help_panel = HelpPanel(parent, -1)
parent.AddPage(self.help_panel, 'Help')
parent.SetSelection(parent.GetPageCount()-1)
Here is the call from the menu to open the HelpPanel:
wx.EVT_MENU(self, ID_HELP, lambda evt: help.HelpPanel.add_help_panel(help.HelpPanel(self.nb, -1), self.nb, evt))
A:
I think the problem may be how your adding your HtmlWindow object to your sizer, try and setting the EXPAND flag and the proportion to 1.
self.sizer.Add(self.help, 1, wx.EXPAND)
| HtmlWindow doesn't display page in wxpython notebook layout | I have a project set up as a notebook layout using wxpython. I am trying to create a help panel. The HtmlWindow object doesn't display the html page on the panel. No errors are displayed and a call to HtmlWindow.GetOpenedPage() returns the page name.
import wx
import wx.html as html
class HelpPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
self.panel = wx.Panel(self, -1)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.help = html.HtmlWindow(self.panel, -1, style=wx.NO_BORDER)
self.help.LoadFile('help.html')
self.sizer.Add(self.help)
self.panel.SetSizer(self.sizer)
self.Show(True)
def add_help_panel(self, parent, evt):
self.help_panel = HelpPanel(parent, -1)
parent.AddPage(self.help_panel, 'Help')
parent.SetSelection(parent.GetPageCount()-1)
Here is the call from the menu to open the HelpPanel:
wx.EVT_MENU(self, ID_HELP, lambda evt: help.HelpPanel.add_help_panel(help.HelpPanel(self.nb, -1), self.nb, evt))
| [
"I think the problem may be how your adding your HtmlWindow object to your sizer, try and setting the EXPAND flag and the proportion to 1.\nself.sizer.Add(self.help, 1, wx.EXPAND)\n\n"
] | [
0
] | [] | [] | [
"python",
"wxhtmlwindow",
"wxpython"
] | stackoverflow_0003672459_python_wxhtmlwindow_wxpython.txt |
Q:
How to accomplish this in python?
Given the following input file:
a = 2
b = 3
c = a * b
d = c + 4
I want to run the above input file through a python program that produces
the following output:
a = 2
b = 3
c = a * b = 6
d = c + 4 = 10
The input file is a legal python program, but the output is python with
extra output that prints the value of each variable to the right of the
declaration/assignment. Alternatively, the output could look like:
a = 2
b = 3
c = a * b
c = 6
d = c + 4
d = 10
The motivation for this is to implement a simple "engineer's notebook"
that allows chains of calculations without needing print statements
in the source file.
Here's what I have after modifying D.Shawley's (much appreciated) contribution:
#! /usr/bin/env python
from math import *
import sys
locals = dict()
for line in sys.stdin:
line = line.strip()
if line == '':
continue
saved = locals.copy()
stmt = compile(line,'<stdin>','single')
eval(stmt,None,locals)
print line,
for (k,v) in locals.iteritems():
if k not in saved:
print '=', v,
print
A:
Something like the following is a good start. It's not very Pythonic, but it is pretty close. It doesn't distinguish between newly added variables and modified ones.
#! /usr/bin/env python
import sys
locals = dict()
for line in sys.stdin:
saved = locals.copy()
stmt = compile(line, '<stdin>', 'single')
eval(stmt, None, locals)
print line.strip(),
for (k,v) in locals.iteritems():
if k not in saved:
print '=', v,
print
| How to accomplish this in python? | Given the following input file:
a = 2
b = 3
c = a * b
d = c + 4
I want to run the above input file through a python program that produces
the following output:
a = 2
b = 3
c = a * b = 6
d = c + 4 = 10
The input file is a legal python program, but the output is python with
extra output that prints the value of each variable to the right of the
declaration/assignment. Alternatively, the output could look like:
a = 2
b = 3
c = a * b
c = 6
d = c + 4
d = 10
The motivation for this is to implement a simple "engineer's notebook"
that allows chains of calculations without needing print statements
in the source file.
Here's what I have after modifying D.Shawley's (much appreciated) contribution:
#! /usr/bin/env python
from math import *
import sys
locals = dict()
for line in sys.stdin:
line = line.strip()
if line == '':
continue
saved = locals.copy()
stmt = compile(line,'<stdin>','single')
eval(stmt,None,locals)
print line,
for (k,v) in locals.iteritems():
if k not in saved:
print '=', v,
print
| [
"Something like the following is a good start. It's not very Pythonic, but it is pretty close. It doesn't distinguish between newly added variables and modified ones.\n#! /usr/bin/env python\nimport sys\nlocals = dict()\nfor line in sys.stdin:\n saved = locals.copy()\n stmt = compile(line, '<stdin>', 'singl... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003672789_python.txt |
Q:
How to embed Evince?
I'm trying to make embed Evince (libevview-2.30) in a Python and a C program, but it doesn't work. I'm using Ubuntu Lucid. Here is my C code:
#include <gtk/gtk.h>
#include <evince/2.30/evince-view.h>
#include <evince/2.30/evince-document.h>
int main(int argc, char *argv[]){
GtkWidget *window;
EvDocument *document;
EvDocumentModel *docmodel;
GtkWidget *view;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
document = EV_DOCUMENT(ev_document_factory_get_document("file:///home/user/review.pdf", NULL));
docmodel = EV_DOCUMENT_MODEL(ev_document_model_new_with_document(EV_DOCUMENT(document)));
view = ev_view_new();
ev_view_set_model(EV_VIEW(view), EV_DOCUMENT_MODEL(docmodel));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
gtk_widget_show_all(window);
gtk_main();
return 0;
}
And here is my Python code:
import gtk
import evince
window = gtk.Window()
window.show()
view = evince.View()
document = evince.document_factory_get_document('file:///home/user/review.pdf')
model = evince.DocumentModel()
model.set_document(document)
view.set_model(model)
window.add(view)
view.show()
gtk.main()
Both programs give the same results - an empty window. What is wrong?
A:
I've figured it out. You need to put EvView widget inside a ScrolledWindow widget.
| How to embed Evince? | I'm trying to make embed Evince (libevview-2.30) in a Python and a C program, but it doesn't work. I'm using Ubuntu Lucid. Here is my C code:
#include <gtk/gtk.h>
#include <evince/2.30/evince-view.h>
#include <evince/2.30/evince-document.h>
int main(int argc, char *argv[]){
GtkWidget *window;
EvDocument *document;
EvDocumentModel *docmodel;
GtkWidget *view;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
document = EV_DOCUMENT(ev_document_factory_get_document("file:///home/user/review.pdf", NULL));
docmodel = EV_DOCUMENT_MODEL(ev_document_model_new_with_document(EV_DOCUMENT(document)));
view = ev_view_new();
ev_view_set_model(EV_VIEW(view), EV_DOCUMENT_MODEL(docmodel));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
gtk_widget_show_all(window);
gtk_main();
return 0;
}
And here is my Python code:
import gtk
import evince
window = gtk.Window()
window.show()
view = evince.View()
document = evince.document_factory_get_document('file:///home/user/review.pdf')
model = evince.DocumentModel()
model.set_document(document)
view.set_model(model)
window.add(view)
view.show()
gtk.main()
Both programs give the same results - an empty window. What is wrong?
| [
"I've figured it out. You need to put EvView widget inside a ScrolledWindow widget.\n"
] | [
2
] | [] | [] | [
"c",
"gnome",
"python"
] | stackoverflow_0003672847_c_gnome_python.txt |
Q:
List of months in Django
I'm trying to have a select form with a list of months but I can't seem to get it to post correctly.
form:
class MonthForm(forms.Form):
months = [('January','January'),
('February','February'),
('March','March'),
('April','April'),
('May','May'),
('June','June'),
('July','July'),
('August','August'),
('September','September'),
('October','October'),
('November','November'),
('December','December'),]
month = forms.ChoiceField(months)
view:
def table_view(request):
if request.method == 'POST':
month = MonthForm(request.POST).cleaned_data['month']
print month
I keep getting this error:
'MonthForm' object has no attribute 'cleaned_data'
A:
The cleaned_data attribute is present only after the form has been validated with is_valid().
Just change your code to
def table_view(request):
if request.method == 'POST':
form = MonthForm(request.POST)
if form.is_valid():
print form.cleaned_data['month']
Internally, if any errors are detected, the cleaned_data attribute will be deleted (see forms/forms.py around line 270) and hence not accessible:
if self._errors:
delattr(self, 'cleaned_data')
See also: http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#processing-the-data-from-a-form
| List of months in Django | I'm trying to have a select form with a list of months but I can't seem to get it to post correctly.
form:
class MonthForm(forms.Form):
months = [('January','January'),
('February','February'),
('March','March'),
('April','April'),
('May','May'),
('June','June'),
('July','July'),
('August','August'),
('September','September'),
('October','October'),
('November','November'),
('December','December'),]
month = forms.ChoiceField(months)
view:
def table_view(request):
if request.method == 'POST':
month = MonthForm(request.POST).cleaned_data['month']
print month
I keep getting this error:
'MonthForm' object has no attribute 'cleaned_data'
| [
"The cleaned_data attribute is present only after the form has been validated with is_valid().\nJust change your code to \ndef table_view(request):\n if request.method == 'POST':\n form = MonthForm(request.POST)\n if form.is_valid():\n print form.cleaned_data['month']\n\n\nInternally, if... | [
6
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003672959_django_python.txt |
Q:
python asyncore or threadpool for web crawler?
It seem what i can do fast crawler with python in two ways:
thread pool with block sockets
non block sockets select,asyncore,etc..
i thnk where is no real need in thread here, and solution #2 better.
which is better and why?
A:
Twisted is usually preferred to asyncore. It is an asynchronous I/O framework that can also work with thread pools.
In Python, you should prefer asynchronous IO to threads, simply because threads are a second class citizen in its canonical implementation (CPython) due to GIL.
| python asyncore or threadpool for web crawler? | It seem what i can do fast crawler with python in two ways:
thread pool with block sockets
non block sockets select,asyncore,etc..
i thnk where is no real need in thread here, and solution #2 better.
which is better and why?
| [
"Twisted is usually preferred to asyncore. It is an asynchronous I/O framework that can also work with thread pools.\nIn Python, you should prefer asynchronous IO to threads, simply because threads are a second class citizen in its canonical implementation (CPython) due to GIL.\n"
] | [
3
] | [] | [] | [
"python",
"web_crawler"
] | stackoverflow_0003673111_python_web_crawler.txt |
Q:
Python: find most frequent bytes?
I'm looking for a (preferably simple) way to find and order the most common bytes in a python stream element.
e.g.
>>> freq_bytes(b'hello world')
b'lohe wrd'
or even
>>> freq_bytes(b'hello world')
[108,111,104,101,32,119,114,100]
I currently have a function that returns a list in the form list[97] == occurrences of "a". I need that to be sorted.
I figure I basically need to flip the list so list[a] = b --> list[b] = a at the same time removing the repeates.
A:
Try the Counter class in the collections module.
from collections import Counter
string = "hello world"
print ''.join(char[0] for char in Counter(string).most_common())
Note you need Python 2.7 or later.
Edit: Forgot the most_common() method returned a list of value/count tuples, and used a list comprehension to get just the values.
A:
def frequent_bytes(aStr):
d = {}
for char in aStr:
d[char] = d.setdefault(char, 0) + 1
myList = []
for char, frequency in d.items():
myList.append((frequency, char))
myList.sort(reverse=True)
return ''.join(myList)
>>> frequent_bytes('hello world')
'lowrhed '
I just tried something obvious. @kindall's answer rocks, though. :)
| Python: find most frequent bytes? | I'm looking for a (preferably simple) way to find and order the most common bytes in a python stream element.
e.g.
>>> freq_bytes(b'hello world')
b'lohe wrd'
or even
>>> freq_bytes(b'hello world')
[108,111,104,101,32,119,114,100]
I currently have a function that returns a list in the form list[97] == occurrences of "a". I need that to be sorted.
I figure I basically need to flip the list so list[a] = b --> list[b] = a at the same time removing the repeates.
| [
"Try the Counter class in the collections module.\nfrom collections import Counter\n\nstring = \"hello world\"\nprint ''.join(char[0] for char in Counter(string).most_common())\n\nNote you need Python 2.7 or later.\nEdit: Forgot the most_common() method returned a list of value/count tuples, and used a list compreh... | [
6,
3
] | [] | [] | [
"byte",
"frequency",
"python"
] | stackoverflow_0003673175_byte_frequency_python.txt |
Q:
gtk: label which goes multi-line instead of expanding horizontally
I have a VBox which looks like this:
ImportantWidget
HSeparator
Label
I want this window to be only as wide as ImportantWidget needs to be, and no wider. However, the Label can sometimes grow to be very long. I want the following logic: if Label can fit all its text without expanding the VBox horizontally (after it has grown enough to fit ImportantWidget), then its text should all be on one line. But if it would overflow and cause horizontal resizing, then it should instead split its text across multiple lines.
Is there a widget that does this already, that's better than Label for the task? If not, what should I use?
A:
Ah yes this shows how to do it:
l = gtk.Label("Painfully long text" * 30)
l.set_line_wrap(True)
A:
EDIT:
example of a dynamic label who works in multi-line according to the size of the window and text:
import gtk
class DynamicLabel(gtk.Window):
def __init__(self):
gtk.Window.__init__(self)
self.set_title("Dynamic Label")
self.set_size_request(1, 1)
self.set_default_size(300,300)
self.set_position(gtk.WIN_POS_CENTER)
l = gtk.Label("Painfully long text " * 30)
l.set_line_wrap(True)
l.connect("size-allocate", self.size_request)
ImportantWidget = gtk.Label("ImportantWidget")
vbox = gtk.VBox(False, 2)
HSeparator = gtk.HSeparator()
vbox.pack_start(ImportantWidget, False, False, 0)
vbox.pack_start(HSeparator, False, False, 0)
vbox.pack_start(l, False, False, 0)
self.add(vbox)
self.connect("destroy", gtk.main_quit)
self.show_all()
def size_request(self, l, s ):
l.set_size_request(s.width -1, -1)
DynamicLabel()
gtk.main()
A:
It looks like you want a dynamically resizing label, which GTK doesn't do out of the box. There's a Python port of VMWare's WrapLabel widget in the Meld repository. (From this question.)
| gtk: label which goes multi-line instead of expanding horizontally | I have a VBox which looks like this:
ImportantWidget
HSeparator
Label
I want this window to be only as wide as ImportantWidget needs to be, and no wider. However, the Label can sometimes grow to be very long. I want the following logic: if Label can fit all its text without expanding the VBox horizontally (after it has grown enough to fit ImportantWidget), then its text should all be on one line. But if it would overflow and cause horizontal resizing, then it should instead split its text across multiple lines.
Is there a widget that does this already, that's better than Label for the task? If not, what should I use?
| [
"Ah yes this shows how to do it:\nl = gtk.Label(\"Painfully long text\" * 30)\nl.set_line_wrap(True)\n\n",
"EDIT:\nexample of a dynamic label who works in multi-line according to the size of the window and text:\nimport gtk\n\nclass DynamicLabel(gtk.Window):\n def __init__(self):\n gtk.Window.__init__(s... | [
1,
1,
1
] | [] | [] | [
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0003516235_gtk_pygtk_python_user_interface.txt |
Q:
Constructing python function callable from C , with input parameter having *output* semantics
The use case is the following:
Given a (fixed, not changeable) DLL implemented in C
Wanted: a wrapper to this DLL implemented in python (chosen method: ctypes)
Some of the functions in the DLL need synchronization primitives. To aim for maximum flexibility, the designers of the DLL completely rely on client-provided callbacks. More precisely this DLL shall have:
a callback function to create a synchronizaton object
callback functions to acquire/release a lock on the synchronizaton object
and one callback function to destroy the synchronizaton object
Because from the viewpoint of the DLL, the synchronizaton object is opaque, it will be repesented by a void * entity. For example if one of the DLL functions wants to acquire a lock it shall do:
void* mutex;
/* get the mutex object via the create_mutex callback */
create_mutex(&mutex);
/* acquire a lock */
lock_mutex(mutex);
... etc
It can be seen, that the callback create_mutex input parameter has output semantics. This is achieved with void ** signature.
This callback (and the other three) must be implemented in python. I've failed :-) For simplicity, let's focus on only the creating callback, and also for simplicity, let the opaque object be an int.
The toy-DLL, which emulates the use of callbacks, is the following (ct_test.c):
#include <stdio.h>
#include <stdlib.h>
typedef int (* callback_t)(int**);
callback_t func;
int* global_i_p = NULL;
int mock_callback(int** ipp)
{
int* dynamic_int_p = (int *) malloc(sizeof(int));
/* dynamic int value from C */
*dynamic_int_p = 2;
*ipp = dynamic_int_p;
return 0;
}
void set_py_callback(callback_t f)
{
func = f;
}
void set_c_callback()
{
func = mock_callback;
}
void test_callback(void)
{
printf("global_i_p before: %p\n", global_i_p);
func(&global_i_p);
printf("global_i_p after: %p, pointed value:%d\n", global_i_p, *global_i_p);
/* to be nice */
if (func == mock_callback)
free(global_i_p);
}
The python code, which would like to provide the callback, and use the DLL is the following:
from ctypes import *
lib = CDLL("ct_test.so")
# "dynamic" int value from python
int = c_int(1)
int_p = pointer(int)
def pyfunc(p_p_i):
p_p_i.contents = int_p
# create callback type and instance
CALLBACK = CFUNCTYPE(c_int, POINTER (POINTER(c_int)))
c_pyfunc = CALLBACK(pyfunc)
# functions from .so
set_py_callback = lib.set_py_callback
set_c_callback = lib.set_c_callback
test_callback = lib.test_callback
# set one of the callbacks
set_py_callback(c_pyfunc)
#set_c_callback()
# test it
test_callback()
When using the in-DLL provided callback (set via set_c_callback()), this works as expected:
~/dev/test$ python ct_test.py
global_i_p before: (nil)
global_i_p after: 0x97eb008, pointed value:2
However, in the other case - with the python callback - fails:
~/dev/test$ python ct_test.py
global_i_p before: (nil)
Traceback (most recent call last):
File "/home/packages/python/2.5/python2.5-2.5.2/Modules/_ctypes/callbacks.c", line 284, in 'converting callback result'
TypeError: an integer is required
Exception in <function pyfunc at 0xa14079c> ignored
Segmentation fault
Where am I wrong?
A:
You appear to be incorrectly defining the return type. It looks like your C callback returns an int, while the Python one you are declaring as return c_int, yet not explicitly returning anything (thus actually returning None). If you "return 0" it might stop crashing. You should do that or change the callback signature to CFUNCTYPE(None, ...etc) in any case.
Also, although it's not a current problem here, you're shadowing the "int" builtin name. This might lead to problems later.
Edited: to correctly refer to the C return type as "int", not "void".
A:
The segfault is due to incorrect pointer handling in your Python callback. You have more levels of pointer indirection than strict necessary, which is probably the source of your confusion. In the Python callback you set p_p_i.contents, but that only changes what the Python ctypes object points at, not the underlying pointer. To do that, do pointer derefrence via array access syntax. A distilled example:
ip = ctypes.POINTER(ctypes.c_int)()
i = ctypes.c_int(99)
# Wrong way
ipp = ctypes.pointer(ip)
ipp.contents = ctypes.pointer(i)
print bool(ip) # False --> still NULL
# Right way
ipp = ctypes.pointer(ip)
ipp[0] = ctypes.pointer(i)
print ip[0] # 99 --> success!
The type error is due to a type incompatibility as described in Peter Hansen's answer.
| Constructing python function callable from C , with input parameter having *output* semantics | The use case is the following:
Given a (fixed, not changeable) DLL implemented in C
Wanted: a wrapper to this DLL implemented in python (chosen method: ctypes)
Some of the functions in the DLL need synchronization primitives. To aim for maximum flexibility, the designers of the DLL completely rely on client-provided callbacks. More precisely this DLL shall have:
a callback function to create a synchronizaton object
callback functions to acquire/release a lock on the synchronizaton object
and one callback function to destroy the synchronizaton object
Because from the viewpoint of the DLL, the synchronizaton object is opaque, it will be repesented by a void * entity. For example if one of the DLL functions wants to acquire a lock it shall do:
void* mutex;
/* get the mutex object via the create_mutex callback */
create_mutex(&mutex);
/* acquire a lock */
lock_mutex(mutex);
... etc
It can be seen, that the callback create_mutex input parameter has output semantics. This is achieved with void ** signature.
This callback (and the other three) must be implemented in python. I've failed :-) For simplicity, let's focus on only the creating callback, and also for simplicity, let the opaque object be an int.
The toy-DLL, which emulates the use of callbacks, is the following (ct_test.c):
#include <stdio.h>
#include <stdlib.h>
typedef int (* callback_t)(int**);
callback_t func;
int* global_i_p = NULL;
int mock_callback(int** ipp)
{
int* dynamic_int_p = (int *) malloc(sizeof(int));
/* dynamic int value from C */
*dynamic_int_p = 2;
*ipp = dynamic_int_p;
return 0;
}
void set_py_callback(callback_t f)
{
func = f;
}
void set_c_callback()
{
func = mock_callback;
}
void test_callback(void)
{
printf("global_i_p before: %p\n", global_i_p);
func(&global_i_p);
printf("global_i_p after: %p, pointed value:%d\n", global_i_p, *global_i_p);
/* to be nice */
if (func == mock_callback)
free(global_i_p);
}
The python code, which would like to provide the callback, and use the DLL is the following:
from ctypes import *
lib = CDLL("ct_test.so")
# "dynamic" int value from python
int = c_int(1)
int_p = pointer(int)
def pyfunc(p_p_i):
p_p_i.contents = int_p
# create callback type and instance
CALLBACK = CFUNCTYPE(c_int, POINTER (POINTER(c_int)))
c_pyfunc = CALLBACK(pyfunc)
# functions from .so
set_py_callback = lib.set_py_callback
set_c_callback = lib.set_c_callback
test_callback = lib.test_callback
# set one of the callbacks
set_py_callback(c_pyfunc)
#set_c_callback()
# test it
test_callback()
When using the in-DLL provided callback (set via set_c_callback()), this works as expected:
~/dev/test$ python ct_test.py
global_i_p before: (nil)
global_i_p after: 0x97eb008, pointed value:2
However, in the other case - with the python callback - fails:
~/dev/test$ python ct_test.py
global_i_p before: (nil)
Traceback (most recent call last):
File "/home/packages/python/2.5/python2.5-2.5.2/Modules/_ctypes/callbacks.c", line 284, in 'converting callback result'
TypeError: an integer is required
Exception in <function pyfunc at 0xa14079c> ignored
Segmentation fault
Where am I wrong?
| [
"You appear to be incorrectly defining the return type. It looks like your C callback returns an int, while the Python one you are declaring as return c_int, yet not explicitly returning anything (thus actually returning None). If you \"return 0\" it might stop crashing. You should do that or change the callback... | [
0,
0
] | [] | [] | [
"callback",
"ctypes",
"python",
"void_pointers"
] | stackoverflow_0001891021_callback_ctypes_python_void_pointers.txt |
Q:
What is the most 'pythonic' way to logically combine a list of booleans?
I have a list of booleans I'd like to logically combine using and/or. The expanded operations would be:
vals = [True, False, True, True, True, False]
# And-ing them together
result = True
for item in vals:
result = result and item
# Or-ing them together
result = False
for item in vals:
result = result or item
Are there nifty one-liners for each of the above?
A:
See all(iterable) :
Return True if all elements of the
iterable are true (or if the iterable
is empty).
And any(iterable) :
Return True if any element of the
iterable is true. If the iterable is empty, return False.
A:
The best way to do it is with the any() and all() functions.
vals = [True, False, True, True, True]
if any(vals):
print "any() reckons there's something true in the list."
if all(vals):
print "all() reckons there's no non-True values in the list."
if any(x % 4 for x in range(100)):
print "One of the numbers between 0 and 99 is divisible by 4."
| What is the most 'pythonic' way to logically combine a list of booleans? | I have a list of booleans I'd like to logically combine using and/or. The expanded operations would be:
vals = [True, False, True, True, True, False]
# And-ing them together
result = True
for item in vals:
result = result and item
# Or-ing them together
result = False
for item in vals:
result = result or item
Are there nifty one-liners for each of the above?
| [
"See all(iterable) :\n\nReturn True if all elements of the\n iterable are true (or if the iterable\n is empty).\n\nAnd any(iterable) :\n\nReturn True if any element of the\n iterable is true. If the iterable is empty, return False.\n\n",
"The best way to do it is with the any() and all() functions.\nvals = [Tr... | [
123,
15
] | [] | [] | [
"boolean",
"list",
"python"
] | stackoverflow_0003673337_boolean_list_python.txt |
Q:
What module is PYSIGNAL defined in PyQt4
All of the examples I read online use
from PyQt4 import *
or some variant of that, importing everything. I don't want to do this, but I can't find where PYSIGNAL is defined!
A:
I think you want:
PyQt4.Qt.SIGNAL
This is the same as:
PyQt4.QtCore.SIGNAL
| What module is PYSIGNAL defined in PyQt4 | All of the examples I read online use
from PyQt4 import *
or some variant of that, importing everything. I don't want to do this, but I can't find where PYSIGNAL is defined!
| [
"I think you want:\nPyQt4.Qt.SIGNAL\n\nThis is the same as:\nPyQt4.QtCore.SIGNAL\n\n"
] | [
1
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0003673553_pyqt_python.txt |
Q:
python: replacing regex with BNF or pyparsing
I am parsing a relatively simple text, where each line describes a game unit. I have little knowledge of parsing techniques, so I used the following ad hoc solution:
class Unit:
# rules is an ordered dictionary of tagged regex that is intended to be applied in the given order
# the group named V would correspond to the value (if any) for that particular tag
rules = (
('Level', r'Lv. (?P<V>\d+)'),
('DPS', r'DPS: (?P<V>\d+)'),
('Type', r'(?P<V>Tank|Infantry|Artillery'),
#the XXX will be expanded into a list of valid traits
#note: (XXX| )* wouldn't work; it will match the first space it finds,
#and stop at that if it's in front of something other than a trait
('Traits', r'(?P<V>(XXX)(XXX| )*)'),
# flavor text, if any, ends with a dot
('FlavorText', r'(?P<V>.*\."?$)'),
)
rules = collections.OrderedDict(rules)
traits = '|'.join('All-Terrain', 'Armored', 'Anti-Aircraft', 'Motorized')
rules['Traits'] = re.sub('XXX', effects, rules['Traits'])
for x in rules:
rules[x] = re.sub('<V>', '<'+x+'>', rules[x])
rules[x] = re.compile(rules[x])
def __init__(self, data)
# data looks like this:
# Lv. 5 Tank DPS: 55 Motorized Armored
for field, regex in Item.rules.items():
data = regex.sub(self.parse, data, 1)
if data:
raise ParserError('Could not parse part of the input: ' + data)
def parse(self, m):
if len(m.groupdict()) != 1:
Exception('Expected a single named group')
field, value = m.groupdict().popitem()
setattr(self, field, value)
return ''
It works fine, but I feel I reached the limit of regex power. Specifically, in the case of Traits, the value ends up being a string that I need to split and convert into a list at a later point: e.g., obj.Traits would be set to 'Motorized Armored' in this code, but in a later function changed to ('Motorized', 'Armored').
I'm thinking of converting this code to use either EBNF or pyparsing grammar or something like that. My goals are:
make this code neater and less error-prone
avoid the ugly treatment of the case with a list of values (where I need do replacement inside the regex first, and later post-process the result to convert a string into a list)
What would be your suggestions about what to use, and how to rewrite the code?
P.S. I skipped some parts of the code to avoid clutter; if I introduced any errors in the process, sorry - the original code does work :)
A:
I started to write up a coaching guide for pyparsing, but looking at your rules, they translate pretty easily into pyparsing elements themselves, without dealing with EBNF, so I just cooked up a quick sample:
from pyparsing import Word, nums, oneOf, Group, OneOrMore, Regex, Optional
integer = Word(nums)
level = "Lv." + integer("Level")
dps = "DPS:" + integer("DPS")
type_ = oneOf("Tank Infantry Artillery")("Type")
traits = Group(OneOrMore(oneOf("All-Terrain Armored Anti-Aircraft Motorized")))("Traits")
flavortext = Regex(r".*\.$")("FlavorText")
rule = (Optional(level) & Optional(dps) & Optional(type_) &
Optional(traits) & Optional(flavortext))
I included the Regex example so you could see how a regular expression could be dropped in to an existing pyparsing grammar. The composition of rule using '&' operators means that the individual items could be found in any order (so the grammar takes care of the iterating over all the rules, instead of you doing it in your own code). Pyparsing uses operator overloading to build up complex parsers from simple ones: '+' for sequence, '|' and '^' for alternatives (first-match or longest-match), and so on.
Here is how the parsed results would look - note that I added results names, just as you used named groups in your regexen:
data = "Lv. 5 Tank DPS: 55 Motorized Armored"
parsed_data = rule.parseString(data)
print parsed_data.dump()
print parsed_data.DPS
print parsed_data.Type
print ' '.join(parsed_data.Traits)
prints:
['Lv.', '5', 'Tank', 'DPS:', '55', ['Motorized', 'Armored']]
- DPS: 55
- Level: 5
- Traits: ['Motorized', 'Armored']
- Type: Tank
55
Tank
Motorized Armored
Please stop by the wiki and see the other examples. You can easy_install to install pyparsing, but if you download the source distribution from SourceForge, there is a lot of additional documentation.
| python: replacing regex with BNF or pyparsing | I am parsing a relatively simple text, where each line describes a game unit. I have little knowledge of parsing techniques, so I used the following ad hoc solution:
class Unit:
# rules is an ordered dictionary of tagged regex that is intended to be applied in the given order
# the group named V would correspond to the value (if any) for that particular tag
rules = (
('Level', r'Lv. (?P<V>\d+)'),
('DPS', r'DPS: (?P<V>\d+)'),
('Type', r'(?P<V>Tank|Infantry|Artillery'),
#the XXX will be expanded into a list of valid traits
#note: (XXX| )* wouldn't work; it will match the first space it finds,
#and stop at that if it's in front of something other than a trait
('Traits', r'(?P<V>(XXX)(XXX| )*)'),
# flavor text, if any, ends with a dot
('FlavorText', r'(?P<V>.*\."?$)'),
)
rules = collections.OrderedDict(rules)
traits = '|'.join('All-Terrain', 'Armored', 'Anti-Aircraft', 'Motorized')
rules['Traits'] = re.sub('XXX', effects, rules['Traits'])
for x in rules:
rules[x] = re.sub('<V>', '<'+x+'>', rules[x])
rules[x] = re.compile(rules[x])
def __init__(self, data)
# data looks like this:
# Lv. 5 Tank DPS: 55 Motorized Armored
for field, regex in Item.rules.items():
data = regex.sub(self.parse, data, 1)
if data:
raise ParserError('Could not parse part of the input: ' + data)
def parse(self, m):
if len(m.groupdict()) != 1:
Exception('Expected a single named group')
field, value = m.groupdict().popitem()
setattr(self, field, value)
return ''
It works fine, but I feel I reached the limit of regex power. Specifically, in the case of Traits, the value ends up being a string that I need to split and convert into a list at a later point: e.g., obj.Traits would be set to 'Motorized Armored' in this code, but in a later function changed to ('Motorized', 'Armored').
I'm thinking of converting this code to use either EBNF or pyparsing grammar or something like that. My goals are:
make this code neater and less error-prone
avoid the ugly treatment of the case with a list of values (where I need do replacement inside the regex first, and later post-process the result to convert a string into a list)
What would be your suggestions about what to use, and how to rewrite the code?
P.S. I skipped some parts of the code to avoid clutter; if I introduced any errors in the process, sorry - the original code does work :)
| [
"I started to write up a coaching guide for pyparsing, but looking at your rules, they translate pretty easily into pyparsing elements themselves, without dealing with EBNF, so I just cooked up a quick sample:\nfrom pyparsing import Word, nums, oneOf, Group, OneOrMore, Regex, Optional\n\ninteger = Word(nums)\nlevel... | [
4
] | [] | [] | [
"ebnf",
"pyparsing",
"python",
"regex"
] | stackoverflow_0003673388_ebnf_pyparsing_python_regex.txt |
Q:
What is a 'good practice' way to write a Python GTK+ application?
I'm currently writing a PyGTK application and I'd like some advice as to the best way to structure my application. Basically the application will read a specific file specification and present it in a GUI for editing.
Currently I have a parser.py which handles all the low level file IO and parsing of the file. I'm displaying the contents of the file in a treeview, which means that I need to use a treestore as my data type.
The problem I've ran into is that I've only thought of two solutions to this problem. The first is that my parser could build a treestore and pass it to my ui class. That requires my parser depending on pygtk, and minimizes the potential reuse for the class. The second would be storing a reference to my ui class in parser, which would also potentially limit the reuse of my parser class as a standalone library.
To condense my question into a short one liner: Is there a way to accomplish my goals in a more pythonic or OO-friendly way?
If looking at my code would help anyone trying to answer my question: https://code.launchpad.net/~blainepace/nbtparser/trunk
Other pythonic suggestions welcome, this is my first python program and I may be stuck in a more C++ style of thinking. I plan on refactoring a lot of it.
A:
You should take a look at the tutorial "Sub-classing GObject in Python". This goes through using GObject's type system to create signals and properties, which allow you to model underlying behavior in a way that is easy to integrate with typical PyGTK semantics (connecting to signals, waiting for property notifications, etc).
Both your parser and UI should have only properties and signals to connect to. You then have a third class that connects up these signals and callbacks and starts the main loop in a if __name__ == __main__ block.
Typically, mine look something like:
class MyApp(gtk.Window):
def __init__(self, parser, ui):
gtk.Window.__init__(self)
parser.connect("some-signal", ui.update_this)
parser.connect("some-other-signal", ui.update_that, extra_params)
ui.connect("refresh-clicked", parser.reparse_file)
self.add(ui)
...and then in your main script:
parser = parser.Parser(...)
ui = view.ParseView(...)
app = MyApp(parser, ui)
app.show_all()
gtk.main()
Of course, this is often different depending on eg. am I using Glade? Do I subclass widgets for the main app or wrap them? etc.
The great thing about this is that you can then write, say, a test parser that does nothing but return pre-programmed responses, or uses a known test file. Swapping it in is as easy as changing one line above:
parser = parser.DummyParser(...)
| What is a 'good practice' way to write a Python GTK+ application? | I'm currently writing a PyGTK application and I'd like some advice as to the best way to structure my application. Basically the application will read a specific file specification and present it in a GUI for editing.
Currently I have a parser.py which handles all the low level file IO and parsing of the file. I'm displaying the contents of the file in a treeview, which means that I need to use a treestore as my data type.
The problem I've ran into is that I've only thought of two solutions to this problem. The first is that my parser could build a treestore and pass it to my ui class. That requires my parser depending on pygtk, and minimizes the potential reuse for the class. The second would be storing a reference to my ui class in parser, which would also potentially limit the reuse of my parser class as a standalone library.
To condense my question into a short one liner: Is there a way to accomplish my goals in a more pythonic or OO-friendly way?
If looking at my code would help anyone trying to answer my question: https://code.launchpad.net/~blainepace/nbtparser/trunk
Other pythonic suggestions welcome, this is my first python program and I may be stuck in a more C++ style of thinking. I plan on refactoring a lot of it.
| [
"You should take a look at the tutorial \"Sub-classing GObject in Python\". This goes through using GObject's type system to create signals and properties, which allow you to model underlying behavior in a way that is easy to integrate with typical PyGTK semantics (connecting to signals, waiting for property notifi... | [
5
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003673340_pygtk_python.txt |
Q:
AppEngine Python - updating entity properties without twenty elif statements
Suppose I have an AppEngine model defined with twenty different StringProperty properties. And then I have a web form, which POSTs updated values for an entity of this model. I end up with something like this after reading in the form data:
entity_key['name'] = 'new_name'
entity_key['city'] = 'new_city'
entity_key['state'] = 'new_state'
etc...
To actually assign these values to the entity, I'm presently doing something like this:
if property == 'name':
entity.name = entity_key['name']
elif property == 'city':
entity.city = entity_key['city']
elif property == 'state':
entity.state = entity_key['state']
etc...
Is there any way to assign the property values without twenty elif statements? I see that there is the model.properties() function, but I don't see anyway to tie all this together.
All help is appreciated.
Thank you.
A:
The same effect as for your if / elif tree could be obtained by a single statement:
setattr(entity, property, entity_key[property])
This is just elementary Python, working the same way in every Python version since 1.5.2 (and perhaps earlier -- I wasn't using Python that many years ago!-), and has nothing specifically to do with App Engine, nor with Django, nor with the combination of the two.
A:
Cool. Just for others' reference, the following two snippets are identical:
entity.some_property = "cat";
setattr(entity, "some_property", "cat")
I did know about the setattr function, Alex, so thanks for helping me out.
| AppEngine Python - updating entity properties without twenty elif statements | Suppose I have an AppEngine model defined with twenty different StringProperty properties. And then I have a web form, which POSTs updated values for an entity of this model. I end up with something like this after reading in the form data:
entity_key['name'] = 'new_name'
entity_key['city'] = 'new_city'
entity_key['state'] = 'new_state'
etc...
To actually assign these values to the entity, I'm presently doing something like this:
if property == 'name':
entity.name = entity_key['name']
elif property == 'city':
entity.city = entity_key['city']
elif property == 'state':
entity.state = entity_key['state']
etc...
Is there any way to assign the property values without twenty elif statements? I see that there is the model.properties() function, but I don't see anyway to tie all this together.
All help is appreciated.
Thank you.
| [
"The same effect as for your if / elif tree could be obtained by a single statement:\nsetattr(entity, property, entity_key[property])\n\nThis is just elementary Python, working the same way in every Python version since 1.5.2 (and perhaps earlier -- I wasn't using Python that many years ago!-), and has nothing spec... | [
2,
0
] | [] | [] | [
"djangoappengine",
"python"
] | stackoverflow_0003664719_djangoappengine_python.txt |
Q:
TypedChoiceField or ChoiceField in Django
When should you use TypedChoiceField with a coerce function over a ChoiceField with a clean method on the form for the field?
In other words why would you use MyForm over MyForm2 or vice versa. Is this simply a matter of preference?
from django import forms
CHOICES = (('1', 'A'), ('2', 'B'), ('3', 'C'))
class MyForm(forms.Form):
my_field = ChoiceField(choices=CHOICES)
def clean_my_field(self):
value = self.cleaned_data['my_field']
return int(value)
class MyForm2(forms.Form):
my_field = TypedChoiceField(choices=CHOICES, coerce=int)
A:
I would use a clean_field method for doing "heavy lifting". For instance if your field requires non-trivial, custom cleaning and/or type conversion etc. If on the other hand the requirement is straightforward such as coercing to int then the clean_field is probably an overkill. TypedChoiceField would be the way to go in that case.
| TypedChoiceField or ChoiceField in Django | When should you use TypedChoiceField with a coerce function over a ChoiceField with a clean method on the form for the field?
In other words why would you use MyForm over MyForm2 or vice versa. Is this simply a matter of preference?
from django import forms
CHOICES = (('1', 'A'), ('2', 'B'), ('3', 'C'))
class MyForm(forms.Form):
my_field = ChoiceField(choices=CHOICES)
def clean_my_field(self):
value = self.cleaned_data['my_field']
return int(value)
class MyForm2(forms.Form):
my_field = TypedChoiceField(choices=CHOICES, coerce=int)
| [
"I would use a clean_field method for doing \"heavy lifting\". For instance if your field requires non-trivial, custom cleaning and/or type conversion etc. If on the other hand the requirement is straightforward such as coercing to int then the clean_field is probably an overkill. TypedChoiceField would be the way ... | [
13
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003673833_django_django_forms_python.txt |
Q:
Why don't you need a powerful ide for writing Python?
I have heard before that many Python developers don't use an IDE like Eclipse because it is unnecessary with a language like Python.
What are the reasons people use to justify this claim?
A:
I'd say the main reason is because Python isn't horribly verbose like, e.g., Java. You don't need an IDE to generate 100s of lines of boilerplate because you don't need 100s of lines of boilerplate in Python. You tend to automate stuff within the language instead of further up the toolchain.
A second reason is that you don't need build process automation b/c there's no build process.
A:
I'm going to risk offending some people and express something that I think a lot of python lovers will agree with: Java is so bloody cumbersome and verbose that one almost needs an IDE like Eclipse just to manage its unwieldy bloat.
With python, the main programming-specific features I want from my editor are syntax highlighting and a jump-to-definition command. Bonus points for a complementary return-from-jump command.
I find Geany does what I need, and is refreshingly light, quick, and stable compared to monster IDEs like Eclipse. For other suggestions, take a look at this question.
A:
I know why you need (can benefit from) a good IDE - Rapid Application Development
Time is money :) And I'd much rather spend my time solving problems than typing every little piece of code in.
A:
Two Main Reasons
Because of the dynamic typing and generally super-powerful functionality, there just isn't much extra typing that the IDE can do for you. Implementing a Java interface in a package is a lot of work and dozens of lines of boilerplate. In Python or Ruby it just doesn't have to be typed in the first place.
Because of the dynamic typing, the fancy editor doesn't have nearly as much information at its fingertips, and so the capability is reduced as well.
So the squeeze is top-down from the reduced need and bottom-up from the reduced editor capability, the net result being a really small application area. The benefit of using a fast and familiar day-to-day editor ends up higher than the benefit of the mostly-pointless IDE.
I suppose it's also possible that the categories are a bit fuzzy now. Vi(1) is the lightest-weight and fastest "plain" editor around, and yet vim(1) can now colorize every language under the sun and TextMate is classified as "lightweight", so all of the categories have really begun to merge a bit.
A:
Python is dynamically typed and the way it handles modules as objects makes it impossible to determine what a name will resolve to at a certain time without actually running the code. Therefore, the 'tab completion' feature of IDEs is pretty useless.
Also, since Python doesn't have a build step, an IDE isn't needed to automate this. You can just fire up python app.py in a terminal and have much more control over how it runs.
A:
It sounds like 'You don't need vehicle to go to work' to me. It might be true or not, depends on how far your workplace is.
A:
IDE's assist in developer productivity and can equally apply to Python. The defining thing about an IDE is the ability to not have to "mode switch" between tasks such as editing, compiling, testing, running and debugging etc.
A:
Python uses dynamic typing and interpreting, rather than compiling.
The interpreter itself will output comprehensive error messages, similar to Perl.
If you look at dynamically typed programming languages in general, you'll find that most of them are not really suitable for IDEs. RAD components (code completion, code generation, code templates, etc) can be included in almost any smart text editor, like Vim, Emacs, Gedit, or SciTE.
I use Vim and Gedit for most of my programming, and I find, that I don't need IDE-ish stuff other than that, what is already included in those text editors. When I program in Java, however, I use Eclipse most of the time, since keeping track of all those parts manually, would be too time consuming. I tend not to use IDE's for my C++ stuff, too, but when the projects grows beyond a certain size, I tend to use either Eclipse (CDT), NetBeans, Code::Blocks, or something like that.
So it's the family of languages itself, that make IDE's unnecessary, but it doesn't mean that working with IDE's with those languages, is bad practice.
Side Note: There's even a Lua environment for Eclipse. Out of all languages, Lua is probably one of the least that needs an IDE...
A:
Well I use an IDE when programming in Python on my computer. Its easier that way . But when on the run or on university's terminal , I prefer terminal .
A:
I'm still fairly new to Python and use an IDE with code completion but find myself rarely needing it, Python does a really good job of not having an uncessarily large number of verbose calls, as dsimcha pointed out above. I find that just using a basic IDE I can work efficiently in it and the fact that the code is a lot less cluttered without having brackets makes it easier to work with files that have a lot of lines of code (something that I found unbearable in PHP due to all its syntax clutter)
As far as @Postman's answer, I'm not sure that having an IDE makes RAD any faster, at least not in the case of python, its such a succinct language, the only thing that it would help in would be code completion, the way you answered it it sounds more like you are hinting at the use of a framework, which I believe is still very important in Python which does make RAD much more possible than otherwise.
A:
The problems is IDEs dont work very well with dynamic languages.
The IDE cannot second guess runtime duck typing so other than some basic syntax checking and displaying the keywords in pretty colours they ar enot much help.
My personal experience is with groovy and eclipse where eclipse is actually pretty annoying. Method completion for a groovy object brings up about 200 posabilties, it constantly insert quotes and brackets exactly where you dont want them and messes up the syntax coloring whenever it encounters a reasonably complex regular expression. I would ditch eclipse except the majority of the code base is in Java where eclipse is useful.
| Why don't you need a powerful ide for writing Python? | I have heard before that many Python developers don't use an IDE like Eclipse because it is unnecessary with a language like Python.
What are the reasons people use to justify this claim?
| [
"I'd say the main reason is because Python isn't horribly verbose like, e.g., Java. You don't need an IDE to generate 100s of lines of boilerplate because you don't need 100s of lines of boilerplate in Python. You tend to automate stuff within the language instead of further up the toolchain.\nA second reason is ... | [
15,
9,
6,
2,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003673487_python.txt |
Q:
Best way to find max and min of two values
I have a function that is passed two values and then iterates over the range of those values. The values can be passed in any order, so I need to find which one is the lowest first. I had the function written like this:
def myFunc(x, y):
if x > y:
min_val, max_val = y, x
else:
min_val, max_val = x, y
for i in range(min_val, max_val):
...
But to save some screen space, I ended up changing it to:
def myFunc(x, y):
min_val, max_val = sorted([x, y])
for i in range(min_val, max_val):
...
How bad is this? Is there a better way that's still one line?
A:
min and max are your friends.
def myFunc(x, y):
min_val, max_val = min(x, y), max(x, y)
Edit. Benchmarked min-max version againt a simple if. Due to the function call overhead, min-max takes 2.5x longer that the simple if; see http://gist.github.com/571049
A:
Since the OP's question was posed using x and y as parameters (not lo and hi), I would go with (for both speed and clarity):
def myfunc(x, y):
lo, hi = (x, y) if x < y else (y, x)
>>> timeit.repeat("myfunc(10, 5)", "from __main__ import myfunc")
[1.2527812156004074, 1.185214249195269, 1.1886092749118689]
>>> timeit.repeat("foo(10, 5)", "from __main__ import foo")
[1.0397177348022524, 0.9580022495574667, 0.9673979369035806]
>>> timeit.repeat("f3(10, 5)", "from __main__ import f3")
[2.47303065772212, 2.4192818561823515, 2.4132735135754046]
A:
I like the sorted one. Clever but not too clever. Here are some other options.
def myFunc(min, max):
if min > max: min, max = max, min
def myFunc(x, y):
min, max = min(x, y), max(x, y)
def myFunc(x, y):
min, max = [f(x, y) for f in (min, max)]
The last one's a bit silly I admit.
A:
Unless you need to microoptimise, I'd just to this
def myFunc(x, y):
for i in range(*sorted((x, y))):
...
This is faster though
def myFunc(x, y):
for i in range(x,y) if x<y else range(y,x):
...
minmax.py
def f1(x, y):
for i in range(min(x, y), max(x, y)):
pass
def f2(x, y):
for i in range(*sorted((x, y))):
pass
def f3(x, y):
for i in range(x, y) if x<y else range(y, x):
pass
def f4(x, y):
if x>y:
x,y = y,x
for i in range(x, y):
pass
def f5(x, y):
mn,mx = ((x, y), (y, x))[x>y]
for i in range(x,y):
pass
benchmarks (f3 is fastest regardless of the order)
$ python -m timeit -s"import minmax as mm" "mm.f1(1,2)"
1000000 loops, best of 3: 1.93 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f2(1,2)"
100000 loops, best of 3: 2.4 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f3(1,2)"
1000000 loops, best of 3: 1.16 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f4(1,2)"
100000 loops, best of 3: 1.2 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f5(1,2)"
1000000 loops, best of 3: 1.58 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f1(2,1)"
100000 loops, best of 3: 1.88 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f2(2,1)"
100000 loops, best of 3: 2.39 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f3(2,1)"
1000000 loops, best of 3: 1.18 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f4(2,1)"
1000000 loops, best of 3: 1.25 usec per loop
$ python -m timeit -s"import minmax as mm" "mm.f5(2,1)"
1000000 loops, best of 3: 1.44 usec per loop
A:
Some suggestions
def myfunc(minVal, maxVal):
if minVal > maxVal: minVal, maxVal = maxVal, minVal
def myfunc2(a, b):
minVal, maxVal = ((a, b), (b, a))[a > b] # :-P
Using sorted, the min/max builtins or the second solution above seems overkill in this case.
And remember that range(min, max) will iterate from min to max - 1!
A:
The single best answer works like:
def foo(lo, hi):
if hi < lo: lo,hi = hi,lo
It's clear, makes a point, and doesn't obscure meaning in a bunch of extra glue. It's short. It's almost certainly as fast as any other option in practice, and it relies on the least amount of cleverness.
| Best way to find max and min of two values | I have a function that is passed two values and then iterates over the range of those values. The values can be passed in any order, so I need to find which one is the lowest first. I had the function written like this:
def myFunc(x, y):
if x > y:
min_val, max_val = y, x
else:
min_val, max_val = x, y
for i in range(min_val, max_val):
...
But to save some screen space, I ended up changing it to:
def myFunc(x, y):
min_val, max_val = sorted([x, y])
for i in range(min_val, max_val):
...
How bad is this? Is there a better way that's still one line?
| [
"min and max are your friends.\ndef myFunc(x, y):\n min_val, max_val = min(x, y), max(x, y)\n\n\nEdit. Benchmarked min-max version againt a simple if. Due to the function call overhead, min-max takes 2.5x longer that the simple if; see http://gist.github.com/571049\n",
"Since the OP's question was posed using ... | [
16,
6,
4,
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003672599_python.txt |
Q:
Write a regex for a pattern?
a + (ab or cd ) + g is my expression. How can I write a regex in Python to match these?
A:
To search this regex in a string, say
re.search("a\\+((ab)|(cd))\\+g", your_string)
To extract matches, use re.findall etc. No need to copy&paste the docs here. :)
EDIT: Updated after OP changed the regex.
If you want it to match whitespace in between, things get pretty ugly ...
re.search("a\W*\\+\W*((ab)|(cd))\W*\\+\W*g", your_string)
| Write a regex for a pattern? | a + (ab or cd ) + g is my expression. How can I write a regex in Python to match these?
| [
"To search this regex in a string, say\nre.search(\"a\\\\+((ab)|(cd))\\\\+g\", your_string)\n\nTo extract matches, use re.findall etc. No need to copy&paste the docs here. :)\nEDIT: Updated after OP changed the regex.\nIf you want it to match whitespace in between, things get pretty ugly ...\nre.search(\"a\\W*\\\\+... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003674403_python_regex.txt |
Q:
regex regarding symbols in urls
I want to replace consecutive symbols just one such as;
this is a dog???
to
this is a dog?
I'm using
str = re.sub("([^\s\w])(\s*\1)+", "\\1",str)
however I notice that this might replace symbols in urls that might happen in my text.
like http://example.com/this--is-a-page.html
Can someone give me some advice how to alter my regex?
A:
So you want to unleash the power of regular expressions on an irregular language like HTML. First of all, search SO for "parse HTML with regex" to find out why that might not be such a good idea.
Then consider the following: You want to replace duplicate symbols in (probably user-entered) text. You don't want to replace them inside a URL. How can you tell what a URL is? They don't always start with http – let's say ars.userfriendly.org might be a URL that is followed by a longer path that contains duplicate symbols.
Furthermore, you'll find lots of duplicate symbols that you definitely don't want to replace (think of nested parentheses (like this)), some of them maybe inside a <script> on the page you're working on (||, && etc. come to mind.
So you might come up with something like
(?<!\b(?:ftp|http|mailto)\S+)([^\\|&/=()"'\w\s])(?:\s*\1)+
which happens to work on the source code of this very page but will surely fail in other cases (for example if URLs don't start with ftp, http or mailto). Plus, it won't work in Python since it uses variable repetition inside lookbehind.
All in all, you probably won't get around parsing your HTML with a real parser, locating the body text, applying a regex to it and writing it back.
EDIT:
OK, you're already working on the parsed text, but it still might contain URLs.
Then try the following:
result = re.sub(
r"""(?ix) # case-insensitive, verbose regex
# Either match a URL
# (protocol optional (if so, URL needs to start with www or ftp))
(?P<URL>\b(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$])
# or
|
# match repeated non-word characters
(?P<rpt>[^\s\w])(?:\s{0,100}(?P=rpt))+""",
# and replace with both captured groups (one will always be empty)
r"\g<URL>\g<rpt>", subject)
Re-EDIT: Hm, Python chokes on the (?:\s*(?P=rpt))+ part, saying the + has nothing to repeat. Looks like a bug in Python (reproducible with (.)(\s*\1)+ whereas (.)(\s?\1)+ works)...
Re-Re-EDIT: If I replace the * with {0,100}, then the regex compiles. But now Python complains about an unmatched group. Obviously you can't reference a group in a replacement if it hasn't participated in the match. I give up... :(
| regex regarding symbols in urls | I want to replace consecutive symbols just one such as;
this is a dog???
to
this is a dog?
I'm using
str = re.sub("([^\s\w])(\s*\1)+", "\\1",str)
however I notice that this might replace symbols in urls that might happen in my text.
like http://example.com/this--is-a-page.html
Can someone give me some advice how to alter my regex?
| [
"So you want to unleash the power of regular expressions on an irregular language like HTML. First of all, search SO for \"parse HTML with regex\" to find out why that might not be such a good idea.\nThen consider the following: You want to replace duplicate symbols in (probably user-entered) text. You don't want t... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003674116_python_regex.txt |
Q:
compile python script in linux
So I have a python script that relies on a couple modules. Specifically pexpect and pyinoitify. I know you can compile a python script into a .exe in windows, but is there something relatively equivalent in linux? I don't care about it being a binary, I'd just like to be able to distribute my script without requiring the separate installation of pexpect and pyinotify. Is that possible/worthwhile?
A:
cx_Freeze is a cross-platform way to "freeze" a Python script into standalone binary form. According to their site:
cx_Freeze is a set of scripts and
modules for freezing Python scripts
into executables in much the same way
that py2exe and py2app do. Unlike
these two tools, cx_Freeze is cross
platform and should work on any
platform that Python itself works on.
It requires Python 2.3 or higher since
it makes use of the zip import
facility which was introduced in that
version.
A:
Generally, if the first line is
#!/usr/bin/env python
And the file has "x" mode set (chmod +x yourfile.py)
Then it's executable. No compiling required.
And yes, folks have to install the things on which you depend. It's (a) simpler and (b) less surprising if they actually do the installation, so they know what's really going on.
A:
In linux, try to avoid such things. Most package managers handle dependencies quite fine, just distribute your script and tell what dependencies it needs.
| compile python script in linux | So I have a python script that relies on a couple modules. Specifically pexpect and pyinoitify. I know you can compile a python script into a .exe in windows, but is there something relatively equivalent in linux? I don't care about it being a binary, I'd just like to be able to distribute my script without requiring the separate installation of pexpect and pyinotify. Is that possible/worthwhile?
| [
"cx_Freeze is a cross-platform way to \"freeze\" a Python script into standalone binary form. According to their site:\n\ncx_Freeze is a set of scripts and\n modules for freezing Python scripts\n into executables in much the same way\n that py2exe and py2app do. Unlike\n these two tools, cx_Freeze is cross\n p... | [
7,
0,
0
] | [] | [] | [
"binary",
"compilation",
"linux",
"python"
] | stackoverflow_0003671466_binary_compilation_linux_python.txt |
Q:
Communicating end of Queue
I'm learning to use the Queue module, and am a bit confused about how a queue consumer thread can be made to know that the queue is complete. Ideally I'd like to use get() from within the consumer thread and have it throw an exception if the queue has been marked "done". Is there a better way to communicate this than by appending a sentinel value to mark the last item in the queue?
A:
original (most of this has changed; see updates below)
Based on some of the suggestions (thanks!) of Glenn Maynard and others, I decided to roll up a descendant of Queue.Queue that implements a close method. It's available in the form of a primitive (unpackaged) module. I'll clean this up a bit and package it properly when I have a bit more time. For now the module only contains the CloseableQueue class and the Closed exception class. I'm planning to expand it to also include subclasses of Queue.LifoQueue and Queue.PriorityQueue.
It's in a pretty preliminary state currently, which is to say that although it passes its test suite, I haven't actually used it for anything yet. Your mileage may vary. I'll keep this answer updated with exciting news.
The CloseableQueue class differs a bit from Glenn's suggestion in that closing the queue will prevent future puts, but not prevent future gets until the queue is emptied. This made the most sense to me; it seemed like functionality to clear the queue could be added as a separate mixin* that would be orthogonal to the closeability functionality. So basically with CloseableQueue, by closing the queue you indicate that the last element has been put. There's also an option to do this atomically by passing last=True to the final put call. Subsequent calls to put, and subsequent calls to get once the queue is emptied, as well as outstanding blocked calls matching those descriptions, will raise the Closed exception.
This is mostly useful for situations where a single producer is generating data for one or more consumers, but it could also be useful for a multi-multi arrangement where consumers are waiting for a particular item or set of items. In particular it doesn't provide a way to determine that all of a number of producers have finished production. Getting that working would entail the provision of some way to register producers (.open()?), as well as a way to indicate that producer registration is itself closed.
Suggestions and/or code reviews are quite welcome. I haven't written a whole lot of concurrency code, but hopefully the test suite is thorough enough that the fact that the code passes it is an indication of the code's quality, rather than the suite's lack thereof. I was able to reuse a bunch of the code from the Queue module's test suite: the file itself is included in this module and used as a basis for various subclasses and routines, including regression testing. This probably (hopefully) helped to avoid complete ineptitude in the testing department. The code itself just overrides Queue.get and Queue.put with fairly minimal changes, and adds the close and closed methods.
I've sort of intentionally avoided using any new-fangled fanciness like context managers in both the code itself and in the test suite in an effort to keep the code as backwards-compatible as is the Queue module itself, which is considerably backwards indeed. I'll probably add __enter__ and __exit__ methods at some point; otherwise, the contextlib's closing function should be applicable to a CloseableQueue instance.
*: Here I use the term "mixin" loosely. As the Queue module's classes are old-style, mixins would need to be mixed using class factory functions; some restrictions apply; offer void where prohibited by Guido.
update
The CloseableQueue module now provides CloseableLifoQueue and CloseablePriorityQueue classes. I've also added some convenience functions to support iteration. Still need to rework it as a proper package. There's a class factory function to allow for convenient subclassing of other Queue.Queue-derived classes.
update 2
CloseableQueue is now available via PyPI, e.g. with
$ easy_install CloseableQueue
Comments and criticism are welcome, especially from this answer's anonymous downvoter.
A:
Queue's don't inherently have the idea of being complete or done. They can be used indefinitely. To close it up when you are done, you will indeed need to put None or some other magic value at the end and write the logic to check for it, as you described. The ideal way would probably be subclassing the Queue object.
See http://en.wikipedia.org/wiki/Queue_(data_structure) to learn more about queue in general.
A:
A sentinel is a natural way to shut down a queue, but there are a couple things to watch out for.
First, remember that you may have more than one consumer, so you need to send a sentinel once for each running consumer, and guarantee that each consumer will only consume one sentinel, to ensure that each consumer receives its shutdown sentinel.
Second, remember that Queue defines an interface, and that when possible, code should behave regardless of the underlying Queue. You might have a PriorityQueue, or you might have some other class that exposes the same interface and returns values in some other order.
Unfortunately, it's hard to deal with both of these. To deal with the general case of different queues, a consumer that's shutting down must continue to consume values after receiving its shutdown sentinel until the queue is empty. That means that it may consume another thread's sentinel. This is a weakness of the Queue interface: it should have a Queue.shutdown call to cause an exception to be thrown by all consumers, but that's missing.
So, in practice:
if you're sure you're only ever using a regular Queue, simply send one sentinel per thread.
if you may be using a PriorityQueue, ensure that the sentinel has the lowest priority.
A:
Queue is a FIFO (first in first out) register so remember that the consumer can be faster than producer. When consumers thread detect that the queue is empty normally realise one of following actions:
Send to API: switch to next thread.
Send to API: sleep some ms and than check again the queue.
Send to API: wait on event (like new message in queue).
If you wont that consumers thread terminate after job is complete than put in queue a sentinel value to terminate task.
A:
The best practice way of doing this would be to have the queue itself notify a client that it has reached the 'done' state. The client can then take any action that is appropriate.
What you have suggested; checking the queue to see if it is done periodically, would be highly undesirable. Polling is an antipattern in multithreaded programming, you should always be using notifications.
EDIT:
So your saying that the queue itself knows that it's 'done' based on some criteria and needs to notify the clients of that fact. I think you are correct and the best way to do this is by throwing when a client calls get() and the queue is in the done state. If your throwing this would negate the need for a sentinel value on the client side. Internally the queue can detect that it is 'done' in any way it pleases e.g. queue is empty, it's state was set to done etc I don't see any need for a sentinel value.
| Communicating end of Queue | I'm learning to use the Queue module, and am a bit confused about how a queue consumer thread can be made to know that the queue is complete. Ideally I'd like to use get() from within the consumer thread and have it throw an exception if the queue has been marked "done". Is there a better way to communicate this than by appending a sentinel value to mark the last item in the queue?
| [
"original (most of this has changed; see updates below)\nBased on some of the suggestions (thanks!) of Glenn Maynard and others, I decided to roll up a descendant of Queue.Queue that implements a close method. It's available in the form of a primitive (unpackaged) module. I'll clean this up a bit and package it p... | [
12,
9,
8,
2,
0
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0003605188_multithreading_python_queue.txt |
Q:
python2.5 multiprocessing Pool
I have python2.5 and multiprocessoring (get from http://code.google.com/p/python-multiprocessing/)
This simple code (get from docs), works very strange from time to time, sometimes it ok, but sometimes it throw timeout ex or hang my Windows (Vista), only reset helps :) Why this can happen?
from multiprocessing import Pool
def f(x):
print "fc",x
return x*x
pool = Pool(processes=4)
if __name__ == '__main__':
result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
print result.get(timeout=3) # prints "100" unless your computer is *very* slow
A:
This is just a wild guess, but have you tried to move the Pool creation into the if block? I suspect that otherwise it might spawn an unlimited number of new processes, causing the freeze.
| python2.5 multiprocessing Pool | I have python2.5 and multiprocessoring (get from http://code.google.com/p/python-multiprocessing/)
This simple code (get from docs), works very strange from time to time, sometimes it ok, but sometimes it throw timeout ex or hang my Windows (Vista), only reset helps :) Why this can happen?
from multiprocessing import Pool
def f(x):
print "fc",x
return x*x
pool = Pool(processes=4)
if __name__ == '__main__':
result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
print result.get(timeout=3) # prints "100" unless your computer is *very* slow
| [
"This is just a wild guess, but have you tried to move the Pool creation into the if block? I suspect that otherwise it might spawn an unlimited number of new processes, causing the freeze.\n"
] | [
4
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0003674746_multiprocessing_python.txt |
Q:
Remove class attribute in inherited class Python
Consider such code:
class A ():
name = 7
description = 8
color = 9
class B(A):
pass
Class B now has (inherits) all attributes of class A. For some reason I want B not to inherit attribute 'color'. Is there a possibility to do this?
Yes, I know, that I can first create class B with attributes 'name' and 'description' and then inherit class A from B adding attribute 'color'. But in my exact case, B is actually a reduced version of A, so for me it seems more logical to remove attribute in B (if possible).
A:
I think the best solution would be to change your class hierarchy so you can get the classes you want without any fancy tricks.
However, if you have a really good reason not to do this you could hide the color attribute using a Descriptor. You'll need to be using new style classes for this to work.
class A(object):
name = 7
description = 8
color = 9
class Hider(object):
def __get__(self,instance,owner):
raise AttributeError, "Hidden attribute"
def __set__(self, obj, val):
raise AttributeError, "Hidden attribute"
class B(A):
color = Hider()
You'll then get an AttributeError when you try to use the color attribute:
>>> B.color
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __get__
AttributeError: Hidden attribute
>>> instance = B()
>>> instance.color
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __get__
AttributeError: Hidden attribute
>>> instance.color = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __set__
AttributeError: Hidden attribute
A:
You can supply a different value for color in B, but if you want B not to have some property of A then there's only one clean way to do it: create a new base class.
class Base():
name = 7
description = 8
class A(Base):
color = 9
class B(Base):
pass
| Remove class attribute in inherited class Python | Consider such code:
class A ():
name = 7
description = 8
color = 9
class B(A):
pass
Class B now has (inherits) all attributes of class A. For some reason I want B not to inherit attribute 'color'. Is there a possibility to do this?
Yes, I know, that I can first create class B with attributes 'name' and 'description' and then inherit class A from B adding attribute 'color'. But in my exact case, B is actually a reduced version of A, so for me it seems more logical to remove attribute in B (if possible).
| [
"I think the best solution would be to change your class hierarchy so you can get the classes you want without any fancy tricks. \nHowever, if you have a really good reason not to do this you could hide the color attribute using a Descriptor. You'll need to be using new style classes for this to work.\nclass A(ob... | [
9,
8
] | [] | [] | [
"class_attributes",
"inheritance",
"python"
] | stackoverflow_0003674597_class_attributes_inheritance_python.txt |
Q:
How do I tell which widget triggered an event in Tkinter?
I have several widgets bound to the same function call. How do I tell which one triggered that call?
A:
The event has a widget field that may help you to distinguish which widget is the source:
from Tkinter import *
class MyObj:
def callback(self, event):
print event.widget.message
obj = MyObj()
root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', obj.callback)
btn.pack()
btn.message = 'Hello'
btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', obj.callback)
btn2.message = 'Salut'
btn2.pack()
root.mainloop()
| How do I tell which widget triggered an event in Tkinter? | I have several widgets bound to the same function call. How do I tell which one triggered that call?
| [
"The event has a widget field that may help you to distinguish which widget is the source:\nfrom Tkinter import *\n\nclass MyObj:\n def callback(self, event):\n print event.widget.message\n\nobj = MyObj()\nroot = Tk()\nbtn=Button(root, text=\"Click\")\nbtn.bind('<Button-1>', obj.callback)\nbtn.pack()\nbtn... | [
6
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003674916_python_tkinter.txt |
Q:
Multiple Web Development Environments on Windows
Beginner here, stuck wondering what I need to do to learn development in different web environments. Say, for instance I want to play around in PHP & MySQL. But I also want to try things with Ruby on Rails and maybe even server things with Python. Do I need a different environment for each platform? Am I required to have a virtual machine to do so? Is it easy to uninstall and start over for each endeavor for a Windows 7 machine?
Or, better yet, would it just be easier to throw Linux in a virtual environment?
A:
I started off with php and mysql, it's a lower-level then the rest of the environments like Django and Ruby on Rails; so it's much easier to understand what is really happening.
If you want to get into web development, php is a solid foundation and has easy bundle installers such as WAMP, and has a massive community.
However if understanding the core of web applications is not your goal and you want some magic to make your application quicker and speed through development, you would want to use a web application framework environment, my favorite here is Ruby on Rails.
Ruby on Rails is a little difficult for the newbie to setup, it typically sucks running in Windows, so you'd be better off with an install on top of a UNIX environment such as Linux, Mac OS, BSD.
If you do want to go the rails route, I suggest installing Ruby with a ruby manager called RVM which is very helpful for playing around with Ruby environments.
Django is a good solid framework but it's playing catch up with Rails and in my honest opinion, doesn't have all those power magic that Rails has such as database migrations.
A:
It is theoretically possible to install all of these on a single web server instance, but I imagine it might be an awfully hard thing to do. (Update: As Col. Shrapnel says, it is not impossible though. See the comments.)
You could take a look into the BitNami stack. It consists of installable packages that promise modularity (i.e. the possibility to add languages like PHP and Ruby to one server instance) and pre-configured virtual machines for the most popular development environments.
A:
I would go the vitual road (VMware or virtual box). Multiple enviroments have a lot of dependencies, so its just much much easier with vitual hosts.
| Multiple Web Development Environments on Windows | Beginner here, stuck wondering what I need to do to learn development in different web environments. Say, for instance I want to play around in PHP & MySQL. But I also want to try things with Ruby on Rails and maybe even server things with Python. Do I need a different environment for each platform? Am I required to have a virtual machine to do so? Is it easy to uninstall and start over for each endeavor for a Windows 7 machine?
Or, better yet, would it just be easier to throw Linux in a virtual environment?
| [
"I started off with php and mysql, it's a lower-level then the rest of the environments like Django and Ruby on Rails; so it's much easier to understand what is really happening. \nIf you want to get into web development, php is a solid foundation and has easy bundle installers such as WAMP, and has a massive commu... | [
1,
0,
0
] | [] | [] | [
"mysql",
"php",
"python",
"ruby_on_rails"
] | stackoverflow_0003674568_mysql_php_python_ruby_on_rails.txt |
Q:
going through a dictionary and printing its values in sequence
def display_hand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print letter,
Will return something like: b e h q u w x. This is the desired output.
How can I modify this code to get the output only when the function has finished its loops?
Something like below code causes me problems as I can't get rid of dictionary elements like commas and single quotes when printing the output:
def display_hand(hand):
dispHand = []
for letter in hand.keys():
for j in range(hand[letter]):
##code##
print dispHand
UPDATE
John's answer is very elegant i find. Allow me however to expand o Kugel's response:
Kugel's approach answered my question. However i kept running into an additional issue: the function would always return None as well as the output. Reason: Whenever you don't explicitly return a value from a function in Python, None is implicitly returned. I couldn't find a way to explicitly return the hand. In Kugel's approach i got closer but the hand is still buried in a FOR loop.
A:
You can do this in one line by combining a couple of list comprehensions:
print ' '.join(letter for letter, count in hand.iteritems() for i in range(count))
Let's break that down piece by piece. I'll use a sample dictionary that has a couple of counts greater than 1, to show the repetition part working.
>>> hand
{'h': 3, 'b': 1, 'e': 2}
Get the letters and counts in a form that we can iterate over.
>>> list(hand.iteritems())
[('h', 3), ('b', 1), ('e', 2)]
Now just the letters.
>>> [letter for letter, count in hand.iteritems()]
['h', 'b', 'e']
Repeat each letter count times.
>>> [letter for letter, count in hand.iteritems() for i in range(count)]
['h', 'h', 'h', 'b', 'e', 'e']
Use str.join to join them into one string.
>>> ' '.join(letter for letter, count in hand.iteritems() for i in range(count))
'h h h b e e'
A:
Your ##code perhaps?
dispHand.append(letter)
Update:
To print your list then:
for item in dispHand:
print item,
A:
another option without nested loop
"".join((x+' ') * y for x, y in hand.iteritems()).strip()
A:
Use
" ".join(sequence)
to print a sequence without commas and the enclosing brackets.
If you have integers or other stuff in the sequence
" ".join(str(x) for x in sequence)
| going through a dictionary and printing its values in sequence | def display_hand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print letter,
Will return something like: b e h q u w x. This is the desired output.
How can I modify this code to get the output only when the function has finished its loops?
Something like below code causes me problems as I can't get rid of dictionary elements like commas and single quotes when printing the output:
def display_hand(hand):
dispHand = []
for letter in hand.keys():
for j in range(hand[letter]):
##code##
print dispHand
UPDATE
John's answer is very elegant i find. Allow me however to expand o Kugel's response:
Kugel's approach answered my question. However i kept running into an additional issue: the function would always return None as well as the output. Reason: Whenever you don't explicitly return a value from a function in Python, None is implicitly returned. I couldn't find a way to explicitly return the hand. In Kugel's approach i got closer but the hand is still buried in a FOR loop.
| [
"You can do this in one line by combining a couple of list comprehensions:\nprint ' '.join(letter for letter, count in hand.iteritems() for i in range(count))\n\nLet's break that down piece by piece. I'll use a sample dictionary that has a couple of counts greater than 1, to show the repetition part working.\n>>> h... | [
3,
1,
1,
0
] | [] | [] | [
"dictionary",
"key",
"printing",
"python",
"sequence"
] | stackoverflow_0003669986_dictionary_key_printing_python_sequence.txt |
Q:
why is python inconsistent when interpreting a subtraction when making a list?
I am making a small program and at some point from each row of a matrix I need to subtract the average of the row itself. Quite a standard renormalization procedure.
Note in the code
def subtractaverage(data):
datanormalized=[]
for row in data:
average_row=sum(row)/len(row)
print "average=",average_row
# renormalized_row=[cell-average_row for cell in row]
renormalized_row=[-average_row+cell for cell in row]
datanormalized.append(renormalized_row)
matrixnormalized=np.array(datanormalized)
return matrixnormalized
The lines:
# renormalized_row=[cell-average_row for cell in row]
renormalized_row=[-average_row+cell for cell in row]
I first tried the first line (cell-average_row) and it did NOT work. The result was that renormalized_row ended up being equal to row.
Then the second line instead worked. SO somehow it seem that the compiler is interpreting [cell-average_row for cell in row] as [cell for cell in row].
But if I write:
renormalized_row=[cell-100 for cell in row]
it works fine (and produces a new list with the value 100 subtracted from each cell. I tried another small program, then:
rs=range(10)
val=5
t=[r-val for r in rs]
print t,rs
This also works and produces
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
as it should.
So now I am at a loss.
Yes I can use
renormalized_row=[-average_row+cell for cell in row]
but I would like to understand what is going on. Why this apparent inconsistency in the way the expression is interpreted.
I am using python2.6.5 (2.6.6 won't have a .dmg for Mac) on a OSX 10.6.4
Thanks
Trying the program later the day, on another sets of data, it actually worked. Testing it again on the original data it works again. I am even more confused. But I know even miss the casus belli to show that something was not working as it should.
Can we please close this question
A:
I guess the problem is the integer division (if row consists of integers only)
average_row=sum(row)/len(row)
which will give you an average of 0 if the length of the row is greater than the sum. Try
average_row=sum(row)/float(len(row))
instead.
| why is python inconsistent when interpreting a subtraction when making a list? | I am making a small program and at some point from each row of a matrix I need to subtract the average of the row itself. Quite a standard renormalization procedure.
Note in the code
def subtractaverage(data):
datanormalized=[]
for row in data:
average_row=sum(row)/len(row)
print "average=",average_row
# renormalized_row=[cell-average_row for cell in row]
renormalized_row=[-average_row+cell for cell in row]
datanormalized.append(renormalized_row)
matrixnormalized=np.array(datanormalized)
return matrixnormalized
The lines:
# renormalized_row=[cell-average_row for cell in row]
renormalized_row=[-average_row+cell for cell in row]
I first tried the first line (cell-average_row) and it did NOT work. The result was that renormalized_row ended up being equal to row.
Then the second line instead worked. SO somehow it seem that the compiler is interpreting [cell-average_row for cell in row] as [cell for cell in row].
But if I write:
renormalized_row=[cell-100 for cell in row]
it works fine (and produces a new list with the value 100 subtracted from each cell. I tried another small program, then:
rs=range(10)
val=5
t=[r-val for r in rs]
print t,rs
This also works and produces
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
as it should.
So now I am at a loss.
Yes I can use
renormalized_row=[-average_row+cell for cell in row]
but I would like to understand what is going on. Why this apparent inconsistency in the way the expression is interpreted.
I am using python2.6.5 (2.6.6 won't have a .dmg for Mac) on a OSX 10.6.4
Thanks
Trying the program later the day, on another sets of data, it actually worked. Testing it again on the original data it works again. I am even more confused. But I know even miss the casus belli to show that something was not working as it should.
Can we please close this question
| [
"I guess the problem is the integer division (if row consists of integers only)\naverage_row=sum(row)/len(row)\n\nwhich will give you an average of 0 if the length of the row is greater than the sum. Try\naverage_row=sum(row)/float(len(row))\n\ninstead.\n"
] | [
2
] | [] | [] | [
"list",
"python",
"subtraction"
] | stackoverflow_0003675148_list_python_subtraction.txt |
Q:
Find subsequences of strings within strings
I want to make a function which checks a string for occurrences of other strings within them.
However, the sub-strings which are being checked may be interrupted within the main string by other letters.
For instance:
a = 'abcde'
b = 'ace'
c = 'acb'
The function in question should return as b being in a, but not c.
I've tried set(a). intersection(set(b)) already, and my problem with that is that it returns c as being in a.
A:
You can turn your expected sequence into a regex:
import re
def sequence_in(s1, s2):
"""Does `s1` appear in sequence in `s2`?"""
pat = ".*".join(s1)
if re.search(pat, s2):
return True
return False
# or, more compactly:
def sequence_in(s1, s2):
"""Does `s1` appear in sequence in `s2`?"""
return bool(re.search(".*".join(s1), s2))
a = 'abcde'
b = 'ace'
c = 'acb'
assert sequence_in(b, a)
assert not sequence_in(c, a)
"ace" gets turned into the regex "a.*c.*e", which finds those three characters in sequence, with possible intervening characters.
A:
how about something like this...
def issubstr(substr, mystr, start_index=0):
try:
for letter in substr:
start_index = mystr.index(letter, start_index) + 1
return True
except: return False
or...
def issubstr(substr, mystr, start_index=0):
for letter in substr:
start_index = mystr.find(letter, start_index) + 1
if start_index == 0: return False
return True
A:
def issubstr(s1, s2):
return "".join(x for x in s2 if x in s1) == s1
>>> issubstr('ace', 'abcde')
True
>>> issubstr('acb', 'abcde')
False
| Find subsequences of strings within strings | I want to make a function which checks a string for occurrences of other strings within them.
However, the sub-strings which are being checked may be interrupted within the main string by other letters.
For instance:
a = 'abcde'
b = 'ace'
c = 'acb'
The function in question should return as b being in a, but not c.
I've tried set(a). intersection(set(b)) already, and my problem with that is that it returns c as being in a.
| [
"You can turn your expected sequence into a regex:\nimport re\n\ndef sequence_in(s1, s2):\n \"\"\"Does `s1` appear in sequence in `s2`?\"\"\"\n pat = \".*\".join(s1)\n if re.search(pat, s2):\n return True\n return False\n\n# or, more compactly:\ndef sequence_in(s1, s2):\n \"\"\"Does `s1` appea... | [
11,
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0003673434_python.txt |
Q:
how to get results from exec() in python 3.1?
how to get results from exec() in python 3.1?
#!/usr/bin/python
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = socket.gethostname()
port = 1234
sock.bind((host,port))
ret_str = "executed"
while True:
cmd, addr = sock.recvfrom(1024)
if len(cmd) > 0:
print("Received ", cmd, " command from ", addr)
exec(cmd) # here I need execution results returns to ret_str
print( "results:", ret_str )
A:
exec expression don't return a value use eval function insted.
print "result:", eval(cmd)
Update: If you still need this I came up with this hack when creating JSON-RPC python interpreter http://trypython.jcubic.pl
import sys
from StringIO import StringIO
__stdout = sys.stdout
sys.stdout = StringIO()
try:
#try if this is a expression
ret = eval(code)
result = sys.stdout.getvalue()
if ret:
result = result + ret
except:
try:
exec(code)
except:
#you can use <traceback> module here
result = 'Exception'
else:
result = sys.stdout.getvalue()
sys.stdout = __stdout
| how to get results from exec() in python 3.1? | how to get results from exec() in python 3.1?
#!/usr/bin/python
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = socket.gethostname()
port = 1234
sock.bind((host,port))
ret_str = "executed"
while True:
cmd, addr = sock.recvfrom(1024)
if len(cmd) > 0:
print("Received ", cmd, " command from ", addr)
exec(cmd) # here I need execution results returns to ret_str
print( "results:", ret_str )
| [
"exec expression don't return a value use eval function insted.\nprint \"result:\", eval(cmd)\n\nUpdate: If you still need this I came up with this hack when creating JSON-RPC python interpreter http://trypython.jcubic.pl\nimport sys\nfrom StringIO import StringIO\n__stdout = sys.stdout\nsys.stdout = StringIO()\ntr... | [
2
] | [] | [] | [
"exec",
"python",
"sockets"
] | stackoverflow_0003675512_exec_python_sockets.txt |
Q:
Get warning for python string literals not prefixed with 'u'
To follow best practices for Unicode in python, you should prefix all string literals of characters with 'u'. Is there any tool available (preferably PyDev compatible) that warns if you forget it?
A:
you should prefix all string literals with 'u'
No, not really.
You should prefix literals for strings of characters with u. But not all strings are strings of characters. When you are talking to components that are byte based, like network services, or binary files, you need to be using byte strings.
eg. Want to try to write a Unicode string into a PNG file? Not sensible. Want to base64-decode the string Y2Fm6Q==? You can't reasonably use a Unicode string here, base64 is explicitly bytes.
Sure, Python will often let you get away with passing a unicode string where a byte string is expected, but only by automatically encoding to ASCII. If the string contains non-ASCII characters you going to get UnicodeError just as surely as if you'd used bytes where unicode was expected. “Unicode is right, bytes are wrong” is a damaging myth. Manipulation for both kinds of strings are required.
If you are concerned about the transition to Python 3, you should certainly mark up your character strings as u'', but you should then also mark up your explicitly-bytes strings as b''. Strings where it doesn't matter you can leave as '' and let them get converted from byte strings to unicode strings on Python 3. There are lots of cases where Python 2 used to use bytes and Python 3 uses Unicode where it is appropriate to do this. But there are still plenty of cases where you do really need to be talking bytes, and having that converted to Python 3 as unicode will cause problems.
(The only problem with this is that b'' syntax requires Python 2.6 or later, so using it will make you incompatible with earlier versions.)
A:
You might want to write a such a warnging-generator tool by parsing Python source code using the parser or the dis built-in modules. You may also consider adding such a feature to pylint.
A:
KennyTM's comment should be posted as an answer:
from __future__ import unicode_literals
This future declaration can be used in Python 2.6 and 2.7 and enables Python 3's string syntax so that unprefixed string literals are Unicode strings and byte arrays require a b prefix.
| Get warning for python string literals not prefixed with 'u' | To follow best practices for Unicode in python, you should prefix all string literals of characters with 'u'. Is there any tool available (preferably PyDev compatible) that warns if you forget it?
| [
"\nyou should prefix all string literals with 'u'\n\nNo, not really.\nYou should prefix literals for strings of characters with u. But not all strings are strings of characters. When you are talking to components that are byte based, like network services, or binary files, you need to be using byte strings.\neg. Wa... | [
4,
2,
1
] | [] | [] | [
"pydev",
"python",
"unicode"
] | stackoverflow_0003674631_pydev_python_unicode.txt |
Q:
How to add python "libraries" to Eclypse and pydev
I am trying to learn how to use Abaqus Scripting. I just downloaded Eclipse and added the pydev plugin. Everything seems to work fine.
What I want to do now is to add all the built-in Abaqus libraries or modules.
I would like, for example, the IDE to display the class members and methods when I press the ".".
I would like to see if the code compiles fine without running it into Abaqus.
How can I do this in Eclipse? Or should I change IDE? Or is it not possible?
I just tried, but no success, I don't fully understand what I need to do.
I am very much a beginner at Python (today is my second day). I have in the abaqus folder the python folder. It leads to two subfolders:
-lib: full of .pyc file (I guess precompiled Python files)
-obj: full of windows dll and the python.exe which I guess is the interpeter.
I also tried to add this interpreter but Eclipse said it can not add it (Error getting info on the interpreter)
I just added the whole lib and obj folder. Maybe once I get more involved in Python I can give you more detailed explanations.
New information:
When I try to run the script it says:
ImportError: Bad magic number in C:\SIMULIA\Abaqus\6.9-1\Python\Lib\abaqus.pyc
Is there a compatibility problem, maybe with different versions of the Python interpreters?
A:
You can add these libraries to the settings to get the effect you want. This can be done in the Libraries setting accessed through Window > Preferences > PyDev > Interpreter - Python > Libraries. Add the .egg or source folder of the libraries you want to add and click Apply followed by OK.
| How to add python "libraries" to Eclypse and pydev | I am trying to learn how to use Abaqus Scripting. I just downloaded Eclipse and added the pydev plugin. Everything seems to work fine.
What I want to do now is to add all the built-in Abaqus libraries or modules.
I would like, for example, the IDE to display the class members and methods when I press the ".".
I would like to see if the code compiles fine without running it into Abaqus.
How can I do this in Eclipse? Or should I change IDE? Or is it not possible?
I just tried, but no success, I don't fully understand what I need to do.
I am very much a beginner at Python (today is my second day). I have in the abaqus folder the python folder. It leads to two subfolders:
-lib: full of .pyc file (I guess precompiled Python files)
-obj: full of windows dll and the python.exe which I guess is the interpeter.
I also tried to add this interpreter but Eclipse said it can not add it (Error getting info on the interpreter)
I just added the whole lib and obj folder. Maybe once I get more involved in Python I can give you more detailed explanations.
New information:
When I try to run the script it says:
ImportError: Bad magic number in C:\SIMULIA\Abaqus\6.9-1\Python\Lib\abaqus.pyc
Is there a compatibility problem, maybe with different versions of the Python interpreters?
| [
"You can add these libraries to the settings to get the effect you want. This can be done in the Libraries setting accessed through Window > Preferences > PyDev > Interpreter - Python > Libraries. Add the .egg or source folder of the libraries you want to add and click Apply followed by OK.\n"
] | [
7
] | [] | [] | [
"eclipse",
"ide",
"pydev",
"python"
] | stackoverflow_0003675585_eclipse_ide_pydev_python.txt |
Q:
Can the formatter class be used without relying on an intermediate stream/file?
import formatter
# a long string I want to format
s="""When running behind a load balancer like nginx, it is recommended to pass xheaders=True to the HTTPServer constructor. This will tell Tornado to use
headers like X-Real-IP to get the user's IP address instead of attributing all traffic to the balancer's IP address.
"""
fh=open("tmp.txt","w")
f=formatter.DumbWriter(fh)
f.send_flowing_data(s)
fh.close()
# how can i set 'results' to the formatted text without using an intermediate file?
# there doesn't seem to be a formatter method which returns a string in
# leiu of sending the data to the stream
results=open("tmp.txt").read()
print results
>>> When running behind a load balancer like nginx, it is recommended to
>>> pass xheaders=True to the HTTPServer constructor. This will tell Tornado
>>> to use headers like X-Real-IP to get the user's IP address instead of
>>> attributing all traffic to the balancer's IP address.
A:
You could use StringIO.
>>> import StringIO
>>> fh = StringIO.StringIO()
>>> f.send_flowing_data(s)
>>> print(fh.getvalue())
When running behind a load balancer like nginx, it is recommended to
pass xheaders=True to the HTTPServer constructor. This will tell Tornado
to use headers like X-Real-IP to get the user's IP address instead of
attributing all traffic to the balancer's IP address.
>>> fh.close()
| Can the formatter class be used without relying on an intermediate stream/file? | import formatter
# a long string I want to format
s="""When running behind a load balancer like nginx, it is recommended to pass xheaders=True to the HTTPServer constructor. This will tell Tornado to use
headers like X-Real-IP to get the user's IP address instead of attributing all traffic to the balancer's IP address.
"""
fh=open("tmp.txt","w")
f=formatter.DumbWriter(fh)
f.send_flowing_data(s)
fh.close()
# how can i set 'results' to the formatted text without using an intermediate file?
# there doesn't seem to be a formatter method which returns a string in
# leiu of sending the data to the stream
results=open("tmp.txt").read()
print results
>>> When running behind a load balancer like nginx, it is recommended to
>>> pass xheaders=True to the HTTPServer constructor. This will tell Tornado
>>> to use headers like X-Real-IP to get the user's IP address instead of
>>> attributing all traffic to the balancer's IP address.
| [
"You could use StringIO.\n>>> import StringIO\n>>> fh = StringIO.StringIO()\n>>> f.send_flowing_data(s)\n>>> print(fh.getvalue())\nWhen running behind a load balancer like nginx, it is recommended to\npass xheaders=True to the HTTPServer constructor. This will tell Tornado\nto use headers like X-Real-IP to get the ... | [
2
] | [] | [] | [
"formatting",
"python"
] | stackoverflow_0003675875_formatting_python.txt |
Q:
Best interface paradigm for time interval selection?
I'm working on a small project that involves selecting time intervals and then using them for my nefarious purposes (which basically boils down to making a robot voice shout things at me). However, I can't decide on a proper paradigm for choosing these intervals. The required data is as follows:
Action (Text)
Starting At (Time, can be minutes/seconds)
Interval (Time, can be minutes/seconds)
The best interface I've been able to come up with is:
Action: [_____________________] | Starting At [__][__] | Interval [__][__]
In the above example, the small [__] areas represent spinners. Can anyone else think of a more standard, consistent interface design?
A:
I'm no GUI expert, but, personally, I love interfaces that give me three ways to choose an interval: "starting at", "ending at", and "duration". Of course, when I advance (say) the duration, it's crucial to have the "ending at" advance in tandem (I find it more intuitive to have the "starting at" interval fixed when either of the other is changed, and the duration fixed -- and the "ending at" changing -- when the "starting at" is the one that's being changed -- however, I could not put into words why I find that intuitive... I guess that's part of me not "being a GUI expert", just a user who knows what I like and dislike;-).
A:
Outlook has a pretty good paradigm for choosing intervals in the appointment creator.
A:
My thoughts:
For text input, use a Miniparser, that would accept inputs like 1:30, which works much better for power users. From my limited experience watching users, this isn't harder to learn when they see samples (e.g. an initial selection) and have another mechanism to help them out when they are stuck (e.g. one spinner for minutes, one for seconds).
Try both positionings for looks and usability:
[spin-minute] [edit] [spin-second]
[edit] [spin-minute] [spin-second]
An advanced Miniparser might allow a range editor and allow different formats, say
1.30 - 2.15 (starts at 1.30, runs for 45 seconds, '-' for range)
1.30 +45 (the same, '+' for start and duration)
90 + 0.45 (the same, time in seconds)
I have no ideas how to place spinners here.
Ideally, you have a visual editor, that can show the relationship between the items:
[Action 1] [.....>----<.......................]
[Action 2] [..........>---------<.............]
Range selectors could be something like this.
dragging one of the range "bounds" should show a vertical marker (e.g. dotted line) through all sliders so that you can see the relationship between them.
You might want the movement to "snap" to other markers, so that they can be chained easily.
When implementing snapping, here are my expectations:
- make it an option
- have a method to disable it on the fly, (e.g. by holding down shift)
- when repeatedly pressing and releasing shift, it should jump between the snapped and the floating position (i.e. you have to track these separately)
| Best interface paradigm for time interval selection? | I'm working on a small project that involves selecting time intervals and then using them for my nefarious purposes (which basically boils down to making a robot voice shout things at me). However, I can't decide on a proper paradigm for choosing these intervals. The required data is as follows:
Action (Text)
Starting At (Time, can be minutes/seconds)
Interval (Time, can be minutes/seconds)
The best interface I've been able to come up with is:
Action: [_____________________] | Starting At [__][__] | Interval [__][__]
In the above example, the small [__] areas represent spinners. Can anyone else think of a more standard, consistent interface design?
| [
"I'm no GUI expert, but, personally, I love interfaces that give me three ways to choose an interval: \"starting at\", \"ending at\", and \"duration\". Of course, when I advance (say) the duration, it's crucial to have the \"ending at\" advance in tandem (I find it more intuitive to have the \"starting at\" interv... | [
3,
3,
3
] | [] | [] | [
"forms",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003673227_forms_python_user_interface_wxpython.txt |
Q:
Howto change Pythonpath in Python 3
I am trying to switch from using Python 2.6.5 to using Python 3.2a2.
I am using OSX 10.6.4.
However, when I open Idle in the Python 3.2a2 folder it cannot import any of the modules I installed to Python 2.6.5.
Is there a way that I can share the same folders on Python 3.2a2 ?
A:
Python 2 and Python 3 are sufficiently different that you cannot in general share modules between them. You will need new, Python-3-compatible modules instead of re-using the Python 2 ones.
(It's possible with a great deal of care to make scripts that will work in both, but it's not usually the done thing. Python 3 was designed to be the big syntax compatibility breaking version.)
| Howto change Pythonpath in Python 3 | I am trying to switch from using Python 2.6.5 to using Python 3.2a2.
I am using OSX 10.6.4.
However, when I open Idle in the Python 3.2a2 folder it cannot import any of the modules I installed to Python 2.6.5.
Is there a way that I can share the same folders on Python 3.2a2 ?
| [
"Python 2 and Python 3 are sufficiently different that you cannot in general share modules between them. You will need new, Python-3-compatible modules instead of re-using the Python 2 ones.\n(It's possible with a great deal of care to make scripts that will work in both, but it's not usually the done thing. Python... | [
2
] | [] | [] | [
"osx_snow_leopard",
"python",
"python_3.x",
"pythonpath",
"upgrade"
] | stackoverflow_0003675999_osx_snow_leopard_python_python_3.x_pythonpath_upgrade.txt |
Q:
How to execute another python script from your script and be able to debug?
You have wrapper python script that is calling another python script, currently using os.system('python another.py some-params').
You want to be able to debug both scripts and if you use os.system() you'll loose the debugger, so it does make sense to load the second script using the same interpretor instead of starting another one.
import doesn't to the expected thing because it does not run the __main__.
Other variants, like exec() or runpy seams to miss the argv parameters.
What solution do you see for this issue?
I'm looking for a solution that does not require you to modify the another.py script. Probably this will require to modify the sys.argv before executing it.
A:
So far I found a solution that works only with Python 2.7+ (runpy.run_path() was introduced in Python 2.7).
If you can find one that works with 2.6 (or even 2.5) you are welcome to post it.
import runpy, sys
saved_argv = sys.argv
... # patch sys.argv[1:] and load new command line parameters
# run_path() does change only sys.argv[0] but restores it
runpy.run_path('another.py', run_name="__main__")
sys.argv = saved_argv # restore sys.argv
A:
Do you have control over another.py? It would be a good idea to change it and add a main() method. Main() can then be invoked if __name__ == '__main__'. This will alleviate your problems a great deal. It is also unit testing friendly.
A:
Based on the recommendation received from EOL, I made an extension to execfile() that does solve its limitations execfile2()
Below is the code, but newer versions will be published here. It is backwards compatible with execfile().
def execfile2(filename, _globals=dict(), _locals=dict(), cmd=None, quiet=False):
_globals['__name__']='__main__'
saved_argv = sys.argv # we save sys.argv
if cmd:
sys.argv=list([filename])
if isinstance(cmd , list):
sys.argv.append(cmd)
else:
sys.argv.extend(shlex.split(cmd))
exit_code = 0
try:
execfile(filename, _globals, _locals)
except SystemExit as e:
if isinstance(e.code , int):
exit_code = e.code # this could be 0 if you do sys.exit(0)
else:
exit_code = 1
except Exception:
if not quiet:
import traceback
traceback.print_exc(file=sys.stderr)
exit_code = 1
finally:
if cmd:
sys.argv = saved_argv # we restore sys.argv
return exit_code
A:
You can make the main block call a function. This way you will be able to call the same function when importing as a module.
def main():
print "All start up commands"
if __name__ == "__main__":
main()
| How to execute another python script from your script and be able to debug? | You have wrapper python script that is calling another python script, currently using os.system('python another.py some-params').
You want to be able to debug both scripts and if you use os.system() you'll loose the debugger, so it does make sense to load the second script using the same interpretor instead of starting another one.
import doesn't to the expected thing because it does not run the __main__.
Other variants, like exec() or runpy seams to miss the argv parameters.
What solution do you see for this issue?
I'm looking for a solution that does not require you to modify the another.py script. Probably this will require to modify the sys.argv before executing it.
| [
"So far I found a solution that works only with Python 2.7+ (runpy.run_path() was introduced in Python 2.7). \nIf you can find one that works with 2.6 (or even 2.5) you are welcome to post it.\nimport runpy, sys\nsaved_argv = sys.argv\n... # patch sys.argv[1:] and load new command line parameters\n# run_path() does... | [
10,
2,
2,
1
] | [] | [] | [
"command_line",
"debugging",
"python",
"runpy"
] | stackoverflow_0003657955_command_line_debugging_python_runpy.txt |
Q:
Python + GStreamer - Won't connect
I'm having trouble combining audio and video into one file. The Python code looks like this;
filmPipe = gst.Pipeline("filmPipe")
filmSrc = gst.element_factory_make("multifilesrc", "filmSrc")
filmSrc.set_property("location", "pictures/%d.png")
filmFilt1 = gst.element_factory_make("capsfilter", "filmFilt1")
filmCap1 = gst.Caps("image/png,framerate=5/1,pixel-aspect-ratio=1/1")
filmFilt1.set_property("caps", filmCap1)
filmPngDec = gst.element_factory_make("pngdec", "filmPngDec")
filmff = gst.element_factory_make("ffmpegcolorspace", "filmff")
filmFilt2 = gst.element_factory_make("capsfilter", "filmFilt2")
filmCap2 = gst.Caps("video/x-raw-yuv")
filmFilt2.set_property("caps", filmCap2)
filmTheora = gst.element_factory_make("xvidenc", "filmTheora")
filmQue = gst.element_factory_make("queue", "filmQue")
filmOggmux = gst.element_factory_make("ffmux_mp4", "filmOggmux")
filmFilesink = gst.element_factory_make("filesink", "filmFilesink")
filmFilesink.set_property("location", self.movPath)
musicSrc = gst.element_factory_make("filesrc", "musicSrc")
musicSrc.set_property("location", self.musicPath)
musicDec = gst.element_factory_make("ffdec_mp3", "musicDec")
musicEnc = gst.element_factory_make("lame", "musicEnc")
musicQue = gst.element_factory_make("queue", "musicQue")
filmPipe.add(filmSrc, filmFilt1, filmPngDec, filmff, filmFilt2, filmTheora, filmQue, filmOggmux, filmFilesink)
filmPipe.add(musicSrc, musicDec, musicEnc, musicQue)
gst.element_link_many(filmSrc, filmFilt1, filmPngDec, filmff, filmFilt2, filmTheora, filmQue, filmOggmux, filmFilesink)
gst.element_link_many(musicSrc, musicDec, musicEnc, musicQue, filmOggmux, filmFilesink)
filmPipe.set_state(gst.STATE_PLAYING)
This returns the following error:
Traceback (most recent call last):
File "app.py", line 100, in movGen
gst.element_link_many(musicSrc, musicDec, musicEnc, musicQue, filmOggmux, filmFilesink)
gst.LinkError: failed to link filmOggmux with filmFilesink
Does anybody know where I'm going wrong, or how to fix this?
A:
You are linking 2 times filmOggmux to filmFilesink: this is not allowed, only one link is possible.
Try removing filmFilesink in the second gst.element_link_many().
| Python + GStreamer - Won't connect | I'm having trouble combining audio and video into one file. The Python code looks like this;
filmPipe = gst.Pipeline("filmPipe")
filmSrc = gst.element_factory_make("multifilesrc", "filmSrc")
filmSrc.set_property("location", "pictures/%d.png")
filmFilt1 = gst.element_factory_make("capsfilter", "filmFilt1")
filmCap1 = gst.Caps("image/png,framerate=5/1,pixel-aspect-ratio=1/1")
filmFilt1.set_property("caps", filmCap1)
filmPngDec = gst.element_factory_make("pngdec", "filmPngDec")
filmff = gst.element_factory_make("ffmpegcolorspace", "filmff")
filmFilt2 = gst.element_factory_make("capsfilter", "filmFilt2")
filmCap2 = gst.Caps("video/x-raw-yuv")
filmFilt2.set_property("caps", filmCap2)
filmTheora = gst.element_factory_make("xvidenc", "filmTheora")
filmQue = gst.element_factory_make("queue", "filmQue")
filmOggmux = gst.element_factory_make("ffmux_mp4", "filmOggmux")
filmFilesink = gst.element_factory_make("filesink", "filmFilesink")
filmFilesink.set_property("location", self.movPath)
musicSrc = gst.element_factory_make("filesrc", "musicSrc")
musicSrc.set_property("location", self.musicPath)
musicDec = gst.element_factory_make("ffdec_mp3", "musicDec")
musicEnc = gst.element_factory_make("lame", "musicEnc")
musicQue = gst.element_factory_make("queue", "musicQue")
filmPipe.add(filmSrc, filmFilt1, filmPngDec, filmff, filmFilt2, filmTheora, filmQue, filmOggmux, filmFilesink)
filmPipe.add(musicSrc, musicDec, musicEnc, musicQue)
gst.element_link_many(filmSrc, filmFilt1, filmPngDec, filmff, filmFilt2, filmTheora, filmQue, filmOggmux, filmFilesink)
gst.element_link_many(musicSrc, musicDec, musicEnc, musicQue, filmOggmux, filmFilesink)
filmPipe.set_state(gst.STATE_PLAYING)
This returns the following error:
Traceback (most recent call last):
File "app.py", line 100, in movGen
gst.element_link_many(musicSrc, musicDec, musicEnc, musicQue, filmOggmux, filmFilesink)
gst.LinkError: failed to link filmOggmux with filmFilesink
Does anybody know where I'm going wrong, or how to fix this?
| [
"You are linking 2 times filmOggmux to filmFilesink: this is not allowed, only one link is possible.\nTry removing filmFilesink in the second gst.element_link_many().\n"
] | [
1
] | [] | [] | [
"gstreamer",
"python"
] | stackoverflow_0003484953_gstreamer_python.txt |
Q:
Is it possible to check if an email contains an attachement just from the e-mail header?
I am developing an email client in Python.
Is it possible to check if an email contains an attachement just from the e-mail header without downloading the whole E-Mail?
A:
Try IMAP4.fetch(message_set, "BODYSTRUCTURE")
Read the RFC3501 for details about the FETCH BODYSTRUCTURE response.
A:
"attachment" is quite a broad term. Is an image for HTML message an attachment?
In general, you can try analyzing content-type header. If it's multipart/mixed, most likely the message contains an attachment.
| Is it possible to check if an email contains an attachement just from the e-mail header? | I am developing an email client in Python.
Is it possible to check if an email contains an attachement just from the e-mail header without downloading the whole E-Mail?
| [
"Try IMAP4.fetch(message_set, \"BODYSTRUCTURE\")\nRead the RFC3501 for details about the FETCH BODYSTRUCTURE response.\n",
"\"attachment\" is quite a broad term. Is an image for HTML message an attachment? \nIn general, you can try analyzing content-type header. If it's multipart/mixed, most likely the message co... | [
7,
5
] | [] | [] | [
"email",
"imap",
"imaplib",
"python"
] | stackoverflow_0003676344_email_imap_imaplib_python.txt |
Q:
Google App Engine many-to-many to self
I'm trying to convert a django project for GAE, and I've stumbled upon this:
(relational-databse)
class Clan(models.Model):
wars = models.ManyToManyField('self')
How can I do this in a non-relational database(i.e. gae datastore)?
A:
If you don't expect more than, say, a couple of hundred keys in the list of related entities, you could use a db.ListProperty(db.Key), containing the keys of the referenced entities.
| Google App Engine many-to-many to self | I'm trying to convert a django project for GAE, and I've stumbled upon this:
(relational-databse)
class Clan(models.Model):
wars = models.ManyToManyField('self')
How can I do this in a non-relational database(i.e. gae datastore)?
| [
"If you don't expect more than, say, a couple of hundred keys in the list of related entities, you could use a db.ListProperty(db.Key), containing the keys of the referenced entities.\n"
] | [
1
] | [] | [] | [
"django",
"google_app_engine",
"non_relational_database",
"nosql",
"python"
] | stackoverflow_0003674632_django_google_app_engine_non_relational_database_nosql_python.txt |
Q:
best way to compare sequence of letters inside file?
I have a file, that have lots of sequences of letters.
Some of these sequences might be equal, so I would like to compare them, all to all.
I'm doing something like this but this isn't exactly want I wanted:
for line in fl:
line = line.split()
for elem in line:
if '>' in elem:
pass
else:
for el in line:
if elem == el:
print elem, el
example of the file:
>1
GTCGTCGAAGCATGCCGGGCCCGCTTCGTGTTCGCTGATA
>2
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA
>3
GTCGTCGAAAGAGGCTT-GCCCGCCACGCGCCCGCTGATA
>4
GTCGTCGAAAGAGGCTT-GCCCGCTACGCGCCCCCTGATA
>5
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA
>6
GTCGTCGAAAGAGTCTGACCGCTTCTCGCCCGCTGATACG
>7
GTCGTCGAAAGAGGTCT-GACCGCTTCTCGCCCGCTGATA
So what I want if to known if any sequence is totally equal to 1, or to 2, and so on.
A:
If the goal is to simply group like sequences together, then simply sorting the data will do the trick. Here is a solution that uses BioPython to parse the input FASTA file, sorts the collection of sequences, uses the standard Python itertools.groupby function to merge ids for equal sequences, and outputs a new FASTA file:
from itertools import groupby
from Bio import SeqIO
records = list(SeqIO.parse(file('spoo.fa'),'fasta'))
def seq_getter(s): return str(s.seq)
records.sort(key=seq_getter)
for seq,equal in groupby(records, seq_getter):
ids = ','.join(s.id for s in equal)
print '>%s' % ids
print seq
Output:
>3
GTCGTCGAAAGAGGCTT-GCCCGCCACGCGCCCGCTGATA
>4
GTCGTCGAAAGAGGCTT-GCCCGCTACGCGCCCCCTGATA
>2,5
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA
>7
GTCGTCGAAAGAGGTCT-GACCGCTTCTCGCCCGCTGATA
>6
GTCGTCGAAAGAGTCTGACCGCTTCTCGCCCGCTGATACG
>1
GTCGTCGAAGCATGCCGGGCCCGCTTCGTGTTCGCTGATA
A:
The following script will return a count of sequences. It returns a dictionary with the individual, distinct sequences as keys and the numbers (the first part of each line) where these sequences occur.
#!/usr/bin/python
import sys
from collections import defaultdict
def count_sequences(filename):
result = defaultdict(list)
with open(filename) as f:
for index, line in enumerate(f):
sequence = line.replace('\n', '')
line_number = index + 1
result[sequence].append(line_number)
return result
if __name__ == '__main__':
filename = sys.argv[1]
for sequence, occurrences in count_sequences(filename).iteritems():
print "%s: %s, found in %s" % (sequence, len(occurrences), occurrences)
Sample output:
etc@etc:~$ python ./fasta.py /path/to/my/file
GTCGTCGAAAGAGGCTT-GCCCGCTACGCGCCCCCTGATA: 1, found in ['4']
GTCGTCGAAAGAGGCTT-GCCCGCCACGCGCCCGCTGATA: 1, found in ['3']
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA: 2, found in ['2', '5']
GTCGTCGAAAGAGGTCT-GACCGCTTCTCGCCCGCTGATA: 1, found in ['7']
GTCGTCGAAGCATGCCGGGCCCGCTTCGTGTTCGCTGATA: 1, found in ['1']
GTCGTCGAAAGAGTCTGACCGCTTCTCGCCCGCTGATACG: 1, found in ['6']
Update
Changed code to use dafaultdict and for loop. Thanks @KennyTM.
Update 2
Changed code to use append rather than +. Thanks @Dave Webb.
A:
In general for this type of work you may want to investigate Biopython which has lots of functionality for parsing and otherwise dealing with sequences.
However, your particular problem can be solved using a dict, an example of which Manoj has given you.
A:
Comparing long sequences of letters is going to be pretty inefficient. It will be quicker to compare the hash of the sequences. Python offers two built in data types that use hash: set and dict. It's best to use dict here as we can store the line numbers of all the matches.
I've assumed the file has identifiers and labels on alternate lines, so if we split the file text on new lines we can take one line as the id and the next as the sequence to match.
We then use a dict with the sequence as a key. The corresponding value is a list of ids which have this sequence. By using defaultdict from collections we can easily handle the case of a sequence not being in the dict; if the key hasn't be used before defaultdict will automatically create a value for us, in this case an empty list.
So when we've finished working through the file the values of the dict will effectively be a list of lists, each entry containing the ids which share a sequence. We can then use a list comprehension to pull out the interesting values, i.e. entries where more than one id is used by a sequence.
from collections import defaultdict
lines = filetext.split("\n")
sequences = defaultdict(list)
while (lines):
id = lines.pop(0)
data = lines.pop(0)
sequences[data].append(id)
results = [match for match in sequences.values() if len(match) > 1]
print results
| best way to compare sequence of letters inside file? | I have a file, that have lots of sequences of letters.
Some of these sequences might be equal, so I would like to compare them, all to all.
I'm doing something like this but this isn't exactly want I wanted:
for line in fl:
line = line.split()
for elem in line:
if '>' in elem:
pass
else:
for el in line:
if elem == el:
print elem, el
example of the file:
>1
GTCGTCGAAGCATGCCGGGCCCGCTTCGTGTTCGCTGATA
>2
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA
>3
GTCGTCGAAAGAGGCTT-GCCCGCCACGCGCCCGCTGATA
>4
GTCGTCGAAAGAGGCTT-GCCCGCTACGCGCCCCCTGATA
>5
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA
>6
GTCGTCGAAAGAGTCTGACCGCTTCTCGCCCGCTGATACG
>7
GTCGTCGAAAGAGGTCT-GACCGCTTCTCGCCCGCTGATA
So what I want if to known if any sequence is totally equal to 1, or to 2, and so on.
| [
"If the goal is to simply group like sequences together, then simply sorting the data will do the trick. Here is a solution that uses BioPython to parse the input FASTA file, sorts the collection of sequences, uses the standard Python itertools.groupby function to merge ids for equal sequences, and outputs a new F... | [
8,
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003675895_python.txt |
Q:
Installing VPython in Snow Leopard?
So, i've just startet university, and we have to install python.
Thats fine, cause it's build-in to OSX (Snow Leopard).
I have installed matplotlib, numpy and scipy using this : http://stronginference.com/scipy-superpack/
It works perfectly, and i don't have to install the python.org version.
But, now we have to install VPython, wich requires the python.org version (2.7)
I just wanna know if it's possible to install just the library's in the apple version of python (2.6.1)
Regards, Adam.
A:
This is a complicated software with a complicated build process, so first and foremost I'd advice you to save yourself some trouble and compile your own Python 2.7 and install it as a user somewhere under your home directory / install the MacOS X binary of 2.7 (probably also as a user under your home directory, but I'm less sure about that) [1]. VPython is complicated software and if they explicitly say that the want 2.7 in their docs they probably have a good reason. It might be possible but I'd expect various problems when trying with another version than their recommended one.
But if you really want to have a shot, what they call their 'Linux' download is actually their source tree. Download and try to build that with your custom build/installation of Python as basis.
[1] Compiling Python is a great learning experience, especially in combination with virtualenv and Distrubute. Multiple isolated Python's FTW.
A:
I would recommend using macports, fink or homebrew to install python 2.7. Following that, you should be able to use setuptools to install matplotlib, scipy and then vpython.
| Installing VPython in Snow Leopard? | So, i've just startet university, and we have to install python.
Thats fine, cause it's build-in to OSX (Snow Leopard).
I have installed matplotlib, numpy and scipy using this : http://stronginference.com/scipy-superpack/
It works perfectly, and i don't have to install the python.org version.
But, now we have to install VPython, wich requires the python.org version (2.7)
I just wanna know if it's possible to install just the library's in the apple version of python (2.6.1)
Regards, Adam.
| [
"This is a complicated software with a complicated build process, so first and foremost I'd advice you to save yourself some trouble and compile your own Python 2.7 and install it as a user somewhere under your home directory / install the MacOS X binary of 2.7 (probably also as a user under your home directory, bu... | [
0,
0
] | [] | [] | [
"macos",
"osx_snow_leopard",
"python",
"vpython"
] | stackoverflow_0003676184_macos_osx_snow_leopard_python_vpython.txt |
Q:
Question regarding regex and tokenizing
I need to make a tokenizer that is able to English words.
Currently, I'm stuck with characters where they can be part of of a url expression.
For instance, if the characters ':','?','=' are part of a url, i shouldn't really segment them.
My qns is, can this be expressed in regex? I have the regex
\b(?:(?:https?|ftp|file)://|www\.|ftp\.)
(?:\([-A-Z0-9+&@#/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#/%=~_|$?!:,.])*
(?:\([-A-Z0-9+&@#/%=~_|$?!:,.]*\)|[A-Z0-9+&@#/%=~_|$])
from here
but I don't know how to piece everything such that if the characters are spotted inside the above expression, don't insert spaces between them.
Help!
A:
I would approach this problem by doing a sweep with a different regexp, putting hits into an array, removing those hits from the string, and then doing your tokenizer as normal.
| Question regarding regex and tokenizing | I need to make a tokenizer that is able to English words.
Currently, I'm stuck with characters where they can be part of of a url expression.
For instance, if the characters ':','?','=' are part of a url, i shouldn't really segment them.
My qns is, can this be expressed in regex? I have the regex
\b(?:(?:https?|ftp|file)://|www\.|ftp\.)
(?:\([-A-Z0-9+&@#/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#/%=~_|$?!:,.])*
(?:\([-A-Z0-9+&@#/%=~_|$?!:,.]*\)|[A-Z0-9+&@#/%=~_|$])
from here
but I don't know how to piece everything such that if the characters are spotted inside the above expression, don't insert spaces between them.
Help!
| [
"I would approach this problem by doing a sweep with a different regexp, putting hits into an array, removing those hits from the string, and then doing your tokenizer as normal.\n"
] | [
0
] | [] | [] | [
"python",
"regex",
"tokenize"
] | stackoverflow_0003676628_python_regex_tokenize.txt |
Q:
python multidimensional list.. how to grab one dimension?
my question is, is I have a list like the following:
someList = [[0,1,2],[3,4,5],[6,7,8]]
how would I get the first entry of each sublist?
I know I could do this:
newList = []
for entry in someList:
newList.append(entry[0])
where newList would be:
[0, 3, 6]
But is there a way to do something like:
newList = someList[:][0]
?
EDIT:
Efficiency is of great concern. I am actually going through a list that has over 300000 entries
A:
EDIT: Here's some actual numbers! The izip, list comprehension, and numpy ways of doing this are all about the same speed.
# zip
>>> timeit.timeit( "newlist = zip(*someList)[0]", setup = "someList = [range(1000000), range(1000000), range(1000000)]", number = 10 )
1.4984046398561759
# izip
>>> timeit.timeit( "newlist = izip(*someList).next()", setup = "someList = range(1000000), range(1000000), range(1000000)]; from itertools import izip", number = 10 )
2.2186223645803693e-05
# list comprehension
>>> timeit.timeit( "newlist = [li[0] for li in someList]", setup = "someList = [range(1000000), range(1000000), range(1000000)]", number = 10 )
1.4677040212518477e-05
# numpy
>>> timeit.timeit( "newlist = someList[0,:]", setup = "import numpy as np; someList = np.array([range(1000000), range(1000000), range(1000000)])", number = 10 )
6.6217344397045963e-05
>>>
For large data structures like this you should use numpy, which implementes an array type in C and hence is significantly more efficient. It also provides all the matrix manipulation you will ever want.
>>> import numpy as np
>>> foo = np.array([[0,1,2],[3,4,5],[6,7,8]])
>>> foo[:,0]
array([0, 3, 6])
You can also transpose...
>>> foo.transpose()
array([[0, 3, 6],
[1, 4, 7],
[2, 5, 8]])
...work with n-dimensional arrays...
>>> foo = np.zeros((3,3,3))
>>> foo
array([[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]])
>>> foo[0,...]
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
..do efficient linear algebra...
>>> foo = no.ones((3,3))
>>> np.linalg.qr(foo)
(array([[-0.57735027, 0.81649658, 0. ],
[-0.57735027, -0.40824829, -0.70710678],
[-0.57735027, -0.40824829, 0.70710678]]), array([[ -1.73205081e+00, -1.
73205081e+00, -1.73205081e+00],
[ 0.00000000e+00, -1.57009246e-16, -1.57009246e-16],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00]]))
...and basically do anything that Matlab can.
A:
Perfect case for a list comprehension:
[sublist[0] for sublist in someList]
Since efficiency is a major concern, this will be much faster than the zip approach. Depending what you're doing with the result, you may be able to get even more efficiency by using the generator expression approach:
(sublist[0] for sublist in someList)
Note that this returns a generator instead of a list though, so can't be indexed into.
A:
zip(*someList)[0]
EDIT:
In response to recursive's comment: One might also use
from itertools import izip
izip(*someList).next()
for better performance.
Some timing analysis:
python -m timeit "someList = [range(1000000), range(1000000), range(1000000)]; newlist = zip(*someList)[0]"
10 loops, best of 3: 498 msec per loop
python -m timeit "someList = [range(1000000), range(1000000), range(1000000)]; from itertools import izip; newlist = izip(*someList).next()"
10 loops, best of 3: 111 msec per loop
python -m timeit "someList = [range(1000000), range(1000000), range(1000000)]; newlist = [li[0] for li in someList]"
10 loops, best of 3: 110 msec per loop
So izip and the list comprehension play in the same league.
Of course the list comprehension is more flexible when you need an index other than 0, and is more explicit.
EDIT2:
Even the numpy solution is not as fast (but I might have chosen a non-representative example):
python -m timeit "import numpy as np; someList = np.array([range(1000000), range(1000000), range(1000000)]); newList = someList[:,0]"
10 loops, best of 3: 551 msec per loop
| python multidimensional list.. how to grab one dimension? | my question is, is I have a list like the following:
someList = [[0,1,2],[3,4,5],[6,7,8]]
how would I get the first entry of each sublist?
I know I could do this:
newList = []
for entry in someList:
newList.append(entry[0])
where newList would be:
[0, 3, 6]
But is there a way to do something like:
newList = someList[:][0]
?
EDIT:
Efficiency is of great concern. I am actually going through a list that has over 300000 entries
| [
"EDIT: Here's some actual numbers! The izip, list comprehension, and numpy ways of doing this are all about the same speed.\n# zip\n>>> timeit.timeit( \"newlist = zip(*someList)[0]\", setup = \"someList = [range(1000000), range(1000000), range(1000000)]\", number = 10 )\n1.4984046398561759\n\n# izip\n>>> timeit.tim... | [
16,
10,
8
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003676805_list_python.txt |
Q:
Terminating a wxPython app cleanly
I'm working on a wxPython app which has multiple frames and a serial connection. I need to be able to exit the app cleanly, closing the serial connection as the app terminates.
What is the best way to do this? Should this be handled by a subclass of wxApp?
Thanks,
Josh
A:
Not totally sure what you're having trouble with here, but I'll take a shot in the dark and assume this is a program organization/design question.
There may be better ways that I'm unfamiliar with, but this is what I'd try to do: create a "parent" object (doesn't have to have any particular type) that keeps references to the multiple frames. When one of the frames receives the exit event from a menu or what have you, it calls self.parent.broadcast_quit(), which sends a quit event to each of the frames it holds references to.
This way of doing it kind of expresses a view-controller separation, where the frames are part of the view and the parent object is a tell-me-when-to-shut-down controller -- the parent can nicely encapsulate the connection teardown as well, since it can stay informed on which frames have shut down and when. You can keep details on how to tear down the view in the frames themselves, and then can send an "I'm finished" message back to the controller during their teardown, triggering some final teardown on the parent side.
See the docs for wx.PostEvent and Custom Event Classes. (Events are a nice normalized way of expressing cross-window messages in a non-blocking GUI.)
A:
I usually use my close button's event handler to close connections and what-not before closing the frame. If you want to catch the upper right "x" button, then you'll need to bind to EVT_CLOSE. Unfortunately, when you do that, you need to call your frame's Destroy() method rather than its Close() method or you'll end up in an infinite loop.
| Terminating a wxPython app cleanly | I'm working on a wxPython app which has multiple frames and a serial connection. I need to be able to exit the app cleanly, closing the serial connection as the app terminates.
What is the best way to do this? Should this be handled by a subclass of wxApp?
Thanks,
Josh
| [
"Not totally sure what you're having trouble with here, but I'll take a shot in the dark and assume this is a program organization/design question.\nThere may be better ways that I'm unfamiliar with, but this is what I'd try to do: create a \"parent\" object (doesn't have to have any particular type) that keeps ref... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003673418_python_wxpython.txt |
Q:
binding events with wxpython
I have the wxPyhon following code
self.button1 = wx.Button(self, id=-1, label='Button1',pos=(8, 8), size=(175, 28))
self.button2 = wx.Button(self, id=-1, label='Button2',pos=(16, 8), size=(175, 28))
self.button1.Bind(wx.EVT_BUTTON, self.onButton)
self.button1.Bind(wx.EVT_BUTTON, self.onButton)
and I need to process the buttons in the below function according to the luanched event
could someone provide an idea i.e
def button1Click(self,event):
if(event of button1 ) :
#proccess code
if(event of button2 ):
#proccess code
how can i know which button luanch the event
A:
One option is to use the label (or ID...but that's usually more troublesome) to key off of, such as:
def onButton(self, event):
label = event.GetEventObject().GetLabel()
if label == "foo":
...
elif label == "bar":
....
Often times, I wish that it has a call back mechanism. So another option is to use lambda during the bind. See this tutorial
A:
You should have a function for each of them if there's different processing code.
self.button1 = wx.Button(self, id=-1, label='Button1',pos=(8, 8), size=(175, 28))
self.button2 = wx.Button(self, id=-1, label='Button2',pos=(16, 8), size=(175, 28))
self.button1.Bind(wx.EVT_BUTTON, self.onButton1)
self.button1.Bind(wx.EVT_BUTTON, self.onButton2)
def onButton1(self,event):
# process code
def onButton2(self,event):
# process code
A:
Personally, I like to get the button object itself:
button = event.GetEventObject()
Then I can use any of the button's methods, like GetName, GetId, or GetLabel. Setting the name is probably the easiest since sometimes I'll have two buttons with the same label.
myButton = wx.Button(self, label="blah blah", name="blah blah one")
Now you can be pretty sneaky. Somewhere in your program, you can have a dict that maps the button names with the methods they should run:
self.myDict = {"btnOne":methodOne, "btnTwo":methodTwo}
Then in your event handler, you can have something like
myButton = event.GetEventObject()
buttonName = myButton.GetName()
if buttonName in self.myDict:
self.myDict[buttonName]()
See also http://wiki.wxpython.org/Passing%20Arguments%20to%20Callbacks or http://wiki.wxpython.org/self.Bind%20vs.%20self.button.Bind
A:
You could the buttons label to identify it like so
def onButton(self,event):
buttonLabel = event.GetEventObject().GetLabel()
if buttonLabel == "Button1":
doSomething()
elif buttonLabel == "Button2":
doSomethingElse()
| binding events with wxpython | I have the wxPyhon following code
self.button1 = wx.Button(self, id=-1, label='Button1',pos=(8, 8), size=(175, 28))
self.button2 = wx.Button(self, id=-1, label='Button2',pos=(16, 8), size=(175, 28))
self.button1.Bind(wx.EVT_BUTTON, self.onButton)
self.button1.Bind(wx.EVT_BUTTON, self.onButton)
and I need to process the buttons in the below function according to the luanched event
could someone provide an idea i.e
def button1Click(self,event):
if(event of button1 ) :
#proccess code
if(event of button2 ):
#proccess code
how can i know which button luanch the event
| [
"One option is to use the label (or ID...but that's usually more troublesome) to key off of, such as:\n def onButton(self, event):\n label = event.GetEventObject().GetLabel()\n if label == \"foo\":\n ...\n elif label == \"bar\":\n ....\n\nOften times, I wish that it has a call back mechanis... | [
3,
1,
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003672255_python_wxpython.txt |
Q:
How to convert unicode string like u'\\u4f60\\u4f60' to u'\u4f60\u4f60' in Python?
I capture the string from a html source file using regex:
f = open(rrfile, 'r')
p = re.compile(r'"name":"([^"]+)","head":"([^"]+)"')
match = re.findall(p, f.read())
And I've tried:
>>> u'\\u4f60\\u4f60'.replace('\\u', '\u')
u'\\u4f60\\u4f60'
>>> u'\\u4f60\\u4f60'.replace(u'\\u', '\u')
u'\\u4f60\\u4f60'
>>> u'\\u4f60\\u4f60'.replace('\\u', u'\u')
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: end of string in escape sequence
Could that be done by str.replace()? Or need something more complex?
A:
>>> u'\\u4f60\\u4f60'.decode('unicode_escape')
u'\u4f60\u4f60'
| How to convert unicode string like u'\\u4f60\\u4f60' to u'\u4f60\u4f60' in Python? | I capture the string from a html source file using regex:
f = open(rrfile, 'r')
p = re.compile(r'"name":"([^"]+)","head":"([^"]+)"')
match = re.findall(p, f.read())
And I've tried:
>>> u'\\u4f60\\u4f60'.replace('\\u', '\u')
u'\\u4f60\\u4f60'
>>> u'\\u4f60\\u4f60'.replace(u'\\u', '\u')
u'\\u4f60\\u4f60'
>>> u'\\u4f60\\u4f60'.replace('\\u', u'\u')
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: end of string in escape sequence
Could that be done by str.replace()? Or need something more complex?
| [
">>> u'\\\\u4f60\\\\u4f60'.decode('unicode_escape')\nu'\\u4f60\\u4f60'\n\n"
] | [
7
] | [] | [] | [
"python",
"replace",
"unicode"
] | stackoverflow_0003677213_python_replace_unicode.txt |
Q:
send an email with python
Possible Duplicate:
Receive and send emails in python
I tried searching but couldn't find a simple way to send an email.
I'm looking for something like this:
from:"Test1@test.com"#email sender
To:"test2@test.com"# my email
content:open('x.txt','r')
Everything I've found is complicated really: my project doesn't need so many lines.
Please, I like to learn: leave comments in each code and explain
A:
The docs are pretty straitforward:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.sendmail(me, [you], msg.as_string())
s.quit()
A:
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
A:
A simple example, which works for me, using smtplib:
#!/usr/bin/env python
import smtplib # Brings in the smtp library
smtpServer='smtp.yourdomain.com' # Set the server - change for your needs
fromAddr='you@yourAddress' # Set the from address - change for your needs
toAddr='you@yourAddress' # Set the to address - change for your needs
# In the lines below the subject and message text get set up
text='''Subject: Python send mail test
Hey!
This is a test of sending email from within Python.
Yourself!
'''
server = smtplib.SMTP(smtpServer) # Instantiate server object, making connection
server.set_debuglevel(1) # Turn debugging on to get problem messages
server.sendmail(fromAddr, toAddr, text) # sends the message
server.quit() # you're done
This is code I found a while back at Link and modified.
| send an email with python |
Possible Duplicate:
Receive and send emails in python
I tried searching but couldn't find a simple way to send an email.
I'm looking for something like this:
from:"Test1@test.com"#email sender
To:"test2@test.com"# my email
content:open('x.txt','r')
Everything I've found is complicated really: my project doesn't need so many lines.
Please, I like to learn: leave comments in each code and explain
| [
"The docs are pretty straitforward:\n# Import smtplib for the actual sending function\nimport smtplib\n\n# Import the email modules we'll need\nfrom email.mime.text import MIMEText\n\n# Open a plain text file for reading. For this example, assume that\n# the text file contains only ASCII characters.\nfp = open(tex... | [
8,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003677067_python.txt |
Q:
get_current_session returns None
I've been using geasessions for a while, been working great. It's simple and fast.
But today I started a new project (GAE v1.3.7) and can't get it to work, get_current_session() just returns None
I've split the code in to a new project that's just using gaesessions:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from gaesessions import get_current_session
import logging
class MainHandler(webapp.RequestHandler):
def get(self):
session = get_current_session()
logging.info(session)
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, { }))
And in the log it just says None.
The strange part is that the other solutions it still works. (I'm guessing it's due to that the db.Model for Session is already present). Tested both the version I use there and downloaded the latest version (1.04)
I've looked at the source code for gaesessions and it kinda make sense that it returns None:
_current_session = None
def get_current_session():
"""Returns the session associated with the current request."""
return _current_session
And I can't find anywhere where the Session class is invoked, but then again it could be my laking python skills.
Does anyone use gaesession and know what's happening?
A:
I think you have missed something in the installation process.
Anyway, if you scroll down the source code you will notice also this part of code that actually valorize the _current_session variable.
def __call__(self, environ, start_response):
# initialize a session for the current user
global _current_session
_current_session = Session(lifetime=self.lifetime, no_datastore=self.no_datastore, cookie_only_threshold=self.cookie_only_thresh, cookie_key=self.cookie_key)
| get_current_session returns None | I've been using geasessions for a while, been working great. It's simple and fast.
But today I started a new project (GAE v1.3.7) and can't get it to work, get_current_session() just returns None
I've split the code in to a new project that's just using gaesessions:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from gaesessions import get_current_session
import logging
class MainHandler(webapp.RequestHandler):
def get(self):
session = get_current_session()
logging.info(session)
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, { }))
And in the log it just says None.
The strange part is that the other solutions it still works. (I'm guessing it's due to that the db.Model for Session is already present). Tested both the version I use there and downloaded the latest version (1.04)
I've looked at the source code for gaesessions and it kinda make sense that it returns None:
_current_session = None
def get_current_session():
"""Returns the session associated with the current request."""
return _current_session
And I can't find anywhere where the Session class is invoked, but then again it could be my laking python skills.
Does anyone use gaesession and know what's happening?
| [
"I think you have missed something in the installation process.\nAnyway, if you scroll down the source code you will notice also this part of code that actually valorize the _current_session variable.\ndef __call__(self, environ, start_response):\n # initialize a session for the current user\n global ... | [
2
] | [] | [] | [
"google_app_engine",
"python",
"session"
] | stackoverflow_0003677611_google_app_engine_python_session.txt |
Q:
Multiprocess conditional/named Lock
In a multiprocess program I want to lock certain function based on arguments e.g.
def calculate(spreadsheet):
_do_calc(spreadsheet)
Now what I want to do is based on spreadsheet, lock the function so that multiple spreadsheets can be worked on concurrently but two calls on same spreadsheet will lock e.g.
def calculate(spreadsheet):
with Lock(spreadsheet.id):
_do_calc(spreadsheet)
Is it possible with multiprocessing.Lock , if not what are the alternatives? I am thinking of using fcntl based file locking.
Edit:
Above was a very simplified version of my problem, basically I am not using multiprocessing module, I have N number of different scripts which work on some data and sometimes same data which I wanted to avoid, so wanted someway to synchronize them at some points, e.g. all of them may import a module mylock and use mylock.lock to synchronize
import mylock
def calculate(spreadsheet):
with mylock.lock(spreadsheet.id):
_do_calc(spreadsheet)
What are the various ways i can write mylock.lock, currently I just create a file with name spreadsheet.id and delete it when lock releases.
A:
Why not give each spreadsheet a Lock as an instance attribute?
class Spreadsheet(...):
def __init__(self, ...):
self.lock = multiprocessing.Lock()
...
and then
def calculate(spreadsheet):
with spreadsheet.lock:
...
A:
You might be able to improve on simple file opening with this recipe, which I have tested on Linux and Windows.
| Multiprocess conditional/named Lock | In a multiprocess program I want to lock certain function based on arguments e.g.
def calculate(spreadsheet):
_do_calc(spreadsheet)
Now what I want to do is based on spreadsheet, lock the function so that multiple spreadsheets can be worked on concurrently but two calls on same spreadsheet will lock e.g.
def calculate(spreadsheet):
with Lock(spreadsheet.id):
_do_calc(spreadsheet)
Is it possible with multiprocessing.Lock , if not what are the alternatives? I am thinking of using fcntl based file locking.
Edit:
Above was a very simplified version of my problem, basically I am not using multiprocessing module, I have N number of different scripts which work on some data and sometimes same data which I wanted to avoid, so wanted someway to synchronize them at some points, e.g. all of them may import a module mylock and use mylock.lock to synchronize
import mylock
def calculate(spreadsheet):
with mylock.lock(spreadsheet.id):
_do_calc(spreadsheet)
What are the various ways i can write mylock.lock, currently I just create a file with name spreadsheet.id and delete it when lock releases.
| [
"Why not give each spreadsheet a Lock as an instance attribute?\nclass Spreadsheet(...):\n def __init__(self, ...):\n self.lock = multiprocessing.Lock()\n\n ...\n\nand then\ndef calculate(spreadsheet):\n with spreadsheet.lock:\n ...\n\n",
"You might be able to improve on simple file opening... | [
2,
2
] | [] | [] | [
"locking",
"mutex",
"python"
] | stackoverflow_0003676732_locking_mutex_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.