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:
Python: Help with UnboundLocalError: local variable referenced before assignment
I keep getting this error for a portion of my code.
Traceback (most recent call last):
File "./mang.py", line 1688, in <module>
files, tsize = logger()
File "./mang.py", line 1466, in logger
nl = sshfile(list, "nl")
UnboundLocalError: local variable 'sshfile' referenced before assignment
I haven't put the code up cause it goes back and forth between functions. I'm wondering if anyone could tell me why python is spitting this error? sshfile is not a variable it's a class.
A:
You probably haven't imported the file which contains the definition of sshfile, or you need to qualify the class name with the package name. It depends on how you imported it.
What package does it come from? Where is it defined?
Update
For anyone else reading this, after a discussion in the comments it turned out that the problem was that the name sshfile had been used further down in the function as a variable name, like this:
class sshfile:
pass
def a():
f = sshfile() # UnboundLocalError here
sshfile = 0
a()
The solution is to not use a variable name that hides a class name that you need to use.
|
Python: Help with UnboundLocalError: local variable referenced before assignment
|
I keep getting this error for a portion of my code.
Traceback (most recent call last):
File "./mang.py", line 1688, in <module>
files, tsize = logger()
File "./mang.py", line 1466, in logger
nl = sshfile(list, "nl")
UnboundLocalError: local variable 'sshfile' referenced before assignment
I haven't put the code up cause it goes back and forth between functions. I'm wondering if anyone could tell me why python is spitting this error? sshfile is not a variable it's a class.
|
[
"You probably haven't imported the file which contains the definition of sshfile, or you need to qualify the class name with the package name. It depends on how you imported it.\nWhat package does it come from? Where is it defined?\n\nUpdate\nFor anyone else reading this, after a discussion in the comments it turned out that the problem was that the name sshfile had been used further down in the function as a variable name, like this:\nclass sshfile:\n pass\n\ndef a():\n f = sshfile() # UnboundLocalError here\n sshfile = 0\n\na()\n\nThe solution is to not use a variable name that hides a class name that you need to use.\n"
] |
[
1
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0002256056_multithreading_python.txt
|
Q:
Why is there an error when dividing 2/5.0 in Python?
Possible Duplicate:
Python float - str - float weirdness
In python, 2/5.0 or 2/float(5) returns 0.40000000000000002
Why do I get that error at the end and how can I get the right value to use in additional calculations?
A:
Welcome to IEEE754, enjoy your stay.
Use decimal instead.
A:
Because floating point arithmetic is not exact. You should use this value in your additional calculations, and round off the result when you're finished. If you need it to be exact, use another data type.
A:
Ignacio above has the right answer.
There is are IEEE standards for efficiently storing floating point numbers into binary computers. These go in excruciating detail about exactly how numbers are stored and these rules are followed on almost every computer.
They are also wrong. Binary numbers cannot handle most normal numbers, just powers of two. Instead of doing something tricky requiring recomputation of the bottom bits to round-off or other tricks, the standards choose efficiency.
That way, you can curse at your system that runs slightly faster. There are occasional debates about changing Python in some way to work around these problems, but the answers are not trivial without a huge loss in efficiency.
Getting around this:
One option is digging into the "decimal" package of the standard library. If you stick to the examples and ignore the long page, it will get you what you want. No bets on efficiency.
Second is to do a manual rounding and string truncate yourself in one output function. Who cares if the number is off a bit if you never print those bits?
A:
Note that Python 3.1 has a new floating point formatting function that avoids this sort of appearance. See What's new in Python 3.1 for more details (search for "floating point").
A:
See this question for the explanation. The right way would be to either
Use integers until the "final" calculation
Live with rounding errors.
|
Why is there an error when dividing 2/5.0 in Python?
|
Possible Duplicate:
Python float - str - float weirdness
In python, 2/5.0 or 2/float(5) returns 0.40000000000000002
Why do I get that error at the end and how can I get the right value to use in additional calculations?
|
[
"Welcome to IEEE754, enjoy your stay.\nUse decimal instead.\n",
"Because floating point arithmetic is not exact. You should use this value in your additional calculations, and round off the result when you're finished. If you need it to be exact, use another data type.\n",
"Ignacio above has the right answer. \nThere is are IEEE standards for efficiently storing floating point numbers into binary computers. These go in excruciating detail about exactly how numbers are stored and these rules are followed on almost every computer.\nThey are also wrong. Binary numbers cannot handle most normal numbers, just powers of two. Instead of doing something tricky requiring recomputation of the bottom bits to round-off or other tricks, the standards choose efficiency.\nThat way, you can curse at your system that runs slightly faster. There are occasional debates about changing Python in some way to work around these problems, but the answers are not trivial without a huge loss in efficiency. \nGetting around this:\nOne option is digging into the \"decimal\" package of the standard library. If you stick to the examples and ignore the long page, it will get you what you want. No bets on efficiency.\nSecond is to do a manual rounding and string truncate yourself in one output function. Who cares if the number is off a bit if you never print those bits?\n",
"Note that Python 3.1 has a new floating point formatting function that avoids this sort of appearance. See What's new in Python 3.1 for more details (search for \"floating point\").\n",
"See this question for the explanation. The right way would be to either\n\nUse integers until the \"final\" calculation\nLive with rounding errors.\n\n"
] |
[
22,
3,
2,
2,
1
] |
[] |
[] |
[
"division",
"python"
] |
stackoverflow_0002250828_division_python.txt
|
Q:
SQLAlchemy Basic Question
To anyone with experience of SQLAlchemy, this will be basic I am sure; But I don't find the docs that helpful and I am sick of scratching my head.
Given two classes:
class User(Base):
__tablename__='users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
...
class UserPost(Base):
__tablename__='posts'
id = Column(Integer, primary_key=True)
poster = Column(Integer, ForeignKey('users.id'))
subject = Column(String(32))
What I am after is a method for:
post = session.query(UserPost).filter_by(subject="foo").one()
print post.poster.name
>>> "John Doe"
I was attempting this with a relation() attribute, but I just kept going round in circles with errors regarding relationship of joins and so on :S
My Relation looks like:
class UserPost(Base):
__tablename__='posts'
id = Column(Integer, primary_key=True)
poster = Column(Integer, ForeignKey('users.id'))
subject = Column(String(32))
poster_user = relation(User, primaryjoin=poster==User.id)
I am new to the voodoo of SQLAlchemy so be gentle! :)
Thanks in advance guys, and apologies in advance if this turns into a RTFM or wrong-end-of-stick
A:
I think you just have the relation definition backwards.
Try:
class User(Base):
__tablename__='users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
posts = relation("UserPost", backref="poster")
class UserPost(Base):
__tablename__='posts'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
subject = Column(String(32))
A:
Maybe you should start with elixir which provides a simpler interface to sqlalchemy:
from elixir import *
metadata.bind = 'sqlite:///:memory:'
class User(Entity):
name = Field(String(32))
posts = OneToMany('Post')
class Post(Entity):
subject = Field(String(32))
user = ManyToOne('User')
setup_all(True)
u1 = User(name='John Doe')
p1 = Post(subject='foo', user=u1)
session.commit()
print Post.query.filter_by(subject='foo').one().user.name
>>> John Doe
A:
Why not show how you have configured relation() ? That's probably the part that's not working.
|
SQLAlchemy Basic Question
|
To anyone with experience of SQLAlchemy, this will be basic I am sure; But I don't find the docs that helpful and I am sick of scratching my head.
Given two classes:
class User(Base):
__tablename__='users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
...
class UserPost(Base):
__tablename__='posts'
id = Column(Integer, primary_key=True)
poster = Column(Integer, ForeignKey('users.id'))
subject = Column(String(32))
What I am after is a method for:
post = session.query(UserPost).filter_by(subject="foo").one()
print post.poster.name
>>> "John Doe"
I was attempting this with a relation() attribute, but I just kept going round in circles with errors regarding relationship of joins and so on :S
My Relation looks like:
class UserPost(Base):
__tablename__='posts'
id = Column(Integer, primary_key=True)
poster = Column(Integer, ForeignKey('users.id'))
subject = Column(String(32))
poster_user = relation(User, primaryjoin=poster==User.id)
I am new to the voodoo of SQLAlchemy so be gentle! :)
Thanks in advance guys, and apologies in advance if this turns into a RTFM or wrong-end-of-stick
|
[
"I think you just have the relation definition backwards.\nTry:\nclass User(Base):\n __tablename__='users'\n id = Column(Integer, primary_key=True)\n name = Column(String(32))\n posts = relation(\"UserPost\", backref=\"poster\")\n\nclass UserPost(Base):\n __tablename__='posts'\n id = Column(Integer, primary_key=True)\n user_id = Column(Integer, ForeignKey('users.id'))\n subject = Column(String(32))\n\n",
"Maybe you should start with elixir which provides a simpler interface to sqlalchemy:\nfrom elixir import *\n\nmetadata.bind = 'sqlite:///:memory:'\n\nclass User(Entity):\n name = Field(String(32))\n posts = OneToMany('Post')\n\nclass Post(Entity):\n subject = Field(String(32))\n user = ManyToOne('User')\n\nsetup_all(True)\n\nu1 = User(name='John Doe')\np1 = Post(subject='foo', user=u1)\n\nsession.commit()\n\nprint Post.query.filter_by(subject='foo').one().user.name\n>>> John Doe\n\n",
"Why not show how you have configured relation() ? That's probably the part that's not working.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"orm",
"python",
"sqlalchemy"
] |
stackoverflow_0002211070_orm_python_sqlalchemy.txt
|
Q:
python Client hangs when no data to receive from server and hangs in that thread w/o letting client send
I am trying to figure out how to get my client to send and receive data 'simultaneously' and am using threads. My problem is that, depending on the way I set it up, the way here it waits for data from the server in the recieveFromServer function which is in its own thread and cannot stop it when nothing will be sent. The other way it just waits for user input, and will send to the server and then I'd call the function recieveFromServer after the client sends a message to the server which doesn't allow for fluent communication, but cannot get it to alternate automatically. How do I release the thread when the client has nothing to be sent, or there is no more to be received from the server.
It would get to long if I tried to explain everything I have tried. :)
Thanks.
The client:
from socket import *
from threading import *
import thread
import time
from struct import pack,unpack
from networklingo import *
#from exception import *
HOST = '192.168.0.105'
PORT = 21567
BUFFSIZE = 1024
ADDR = (HOST,PORT)
lock = thread.allocate_lock()
class TronClient:
def __init__(self,control=None):
self.tcpSock = socket(AF_INET,SOCK_STREAM)
#self.tcpSock.settimeout(.2)
self.recvBuff = []
def connect(self):
self.tcpSock.connect(ADDR)
self.clientUID = self.tcpSock.recv(BUFFSIZE)
print 'My clientUID is ', self.clientUID
t = Thread(target = self.receiveFromSrv())
t.setDaemon(1)
t.start()
print 'going to main loop'
self.mainLoop()
#t = Thread(target = self.mainLoop())
#t.setName('mainLoop')
#t.setDaemon(1)
#t.start()
def receiveFromSrv(self):
RECIEVING = 1
while RECIEVING:
#print 'Attempting to retrieve more data'
#lock.acquire()
#print 'Lock Aquired in recieveFromSrv'
#try:
data = self.tcpSock.recv(BUFFSIZE)
#except socket.timeout,e:
#print 'Error recieving data, ',e
#continue
#print data
if not data: continue
header = data[:6]
msgType,msgLength,clientID = unpack("hhh",header)
print msgType
print msgLength
print clientID,'\n'
msg = data[6:]
while len(msg) < msgLength:
data = self.tcpSock.recv(BUFFSIZE)
dataLen = len(data)
if dataLen <= msgLength:
msg += data
else:
remLen = msgLength-len(data) #we just need to retrieve first bit of data to complete msg
msg += data[:remLen]
self.recvBuff.append(data[remLen:])
print msg
#else:
#lock.release()
# print 'lock release in receiveFromSrv'
#time.sleep(2)
#RECIEVING = 0
def disconnect(self,data=''):
self.send(DISCONNECT_REQUEST,data)
#self.tcpSock.close()
def send(self,msgType,msg):
header = pack("hhh",msgType,len(msg),self.clientUID)
msg = header+msg
self.tcpSock.send(msg)
def mainLoop(self):
while 1:
try:
#lock.acquire()
#print 'lock aquired in mainLoop'
data = raw_input('> ')
except EOFError: # enter key hit without any data (blank line) so ignore and continue
continue
#if not data or data == '': # no valid data so just continue
# continue
if data=='exit': # client wants to disconnect, so send request to server
self.disconnect()
break
else:
self.send(TRON_CHAT,data)
#lock.release()
#print 'lock released in main loop'
#self.recieveFromSrv()
#data = self.tcpSock.recv(BUFFSIZE)
#t = Thread(target = self.receiveFromSrv())
#t.setDaemon(1)
#t.start()
if __name__ == "__main__":
cli = TronClient()
cli.connect()
#t = Thread(target = cli.connect())
#t.setName('connect')
#t.setDaemon(1)
#t.start()
The server (uses a lock when incrementing or decrementing number of clients):
from socket import *
from threading import *
import thread
from controller import *
from networklingo import *
from struct import pack,unpack
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
nclntlock = thread.allocate_lock()
class TronServer:
def __init__(self,maxConnect=4,control=None):
self.servSock = socket(AF_INET,SOCK_STREAM)
# ensure that you can restart server quickly when it terminates
self.servSock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
self.servSock.bind(ADDR)
self.servSock.listen(maxConnect)
# keep track of number of connected clients
self.clientsConnected = 0
# give each client a unique identfier for this run of server
self.clientUID = 0
# list of all clients to cycle through for sending
self.allClients = {}
# keep track of threads
self.cliThreads = {}
#reference back to controller
self.controller = control
self.recvBuff = []
def removeClient(self,clientID,addr):
if clientID in self.allClients.keys():
self.allClients[clientID].close()
print "Disconnected from", addr
nclntlock.acquire()
self.clientsConnected -= 1
nclntlock.release()
del self.allClients[clientID]
else:
print 'ClientID is not valid'
def recieve(self,clientsock,addr):
RECIEVING = 1
# loop serving the new client
while RECIEVING: # while PLAYING???
try:
data = clientsock.recv(BUFSIZE)
except:
RECIEVING = 0
continue
# if not data: break #no data was recieved
if data != '':
print 'Recieved msg from client: ',data
header = data[:6]
msgType,msgLength,clientID = unpack("hhh",header)
print msgType
print msgLength
print clientID,'\n'
if msgType == DISCONNECT_REQUEST: #handle disconnect request
self.removeClient(clientID,addr)
else: #pass message type and message off to controller
msg = data[6:]
while len(msg) < msgLength:
data = self.tcpSock.recv(BUFSIZE)
dataLen = len(data)
if dataLen <= msgLength:
msg += data
else:
remLen = msgLength-len(data) #we just need to retrieve first bit of data to complete msg
msg += data[:remLen]
self.recvBuff.append(data[remLen:])
print msg
# echo back the same data you just recieved
#clientsock.sendall(data)
self.send(TRON_CHAT,msg,-1) #send to client 0
for k in self.allClients.keys():
if self.allClients[k] == clientsock:
self.removeClient(k,addr)
print 'deleted after hard exit from clientID ', k
#self.cliThreads[k].join()
#del self.cliThreads[k]
# then tell controller to delete player with k
break
def send(self,msgType,msg,clientID=-1):
header = pack("hhh",msgType,len(msg),clientID)
msg = header+msg
if clientID in self.allClients:
self.allClients[clientID].send(msg)
elif clientID==ALL_PLAYERS:
for k in self.allClients.keys():
self.allClients[k].send(msg)
def mainLoop(self):
global nclntlock
try:
while self.controller != None and self.controller.state == WAITING:
print 'awaiting connections'
clientsock, caddy = self.servSock.accept()
nclntlock.acquire()
self.clientsConnected += 1
nclntlock.release()
print 'Client ',self.clientUID,' connected from:',caddy
clientsock.setblocking(0)
clientsock.send(str(self.clientUID))
self.allClients[self.clientUID] = clientsock
t = Thread(target = self.recieve, args = [clientsock,caddy])
t.setName('recieve-' + str(self.clientUID))
self.cliThreads[self.clientUID] = t
self.clientUID += 1
# t.setDaemon(1)
t.start()
finally:
self.servSock.close()
if __name__ == "__main__":
serv = TronServer(control = LocalController(nPlayers = 3, fWidth = 70, fHeight = 10))
t = Thread(target = serv.mainLoop())
t.setName('mainLoop')
# t.setDaemon(1)
t.start()
A:
I think you want to try and set the socket to non-blocking mode:
http://docs.python.org/library/socket.html#socket.socket.setblocking
Set blocking or non-blocking mode of
the socket: if flag is 0, the socket
is set to non-blocking, else to
blocking mode. Initially all sockets
are in blocking mode. In non-blocking
mode, if a recv() call doesn’t find
any data, or if a send() call can’t
immediately dispose of the data, a
error exception is raised; in blocking
mode, the calls block until they can
proceed. s.setblocking(0) is
equivalent to s.settimeout(0);
s.setblocking(1) is equivalent to
s.settimeout(None).
Also, instead of using raw sockets, have you considdered using the multiprocessing module. It is a higher-level abstraction for doing network IO. The section on Pipes & Queues is specific to sending and receiving data between a client/server.
|
python Client hangs when no data to receive from server and hangs in that thread w/o letting client send
|
I am trying to figure out how to get my client to send and receive data 'simultaneously' and am using threads. My problem is that, depending on the way I set it up, the way here it waits for data from the server in the recieveFromServer function which is in its own thread and cannot stop it when nothing will be sent. The other way it just waits for user input, and will send to the server and then I'd call the function recieveFromServer after the client sends a message to the server which doesn't allow for fluent communication, but cannot get it to alternate automatically. How do I release the thread when the client has nothing to be sent, or there is no more to be received from the server.
It would get to long if I tried to explain everything I have tried. :)
Thanks.
The client:
from socket import *
from threading import *
import thread
import time
from struct import pack,unpack
from networklingo import *
#from exception import *
HOST = '192.168.0.105'
PORT = 21567
BUFFSIZE = 1024
ADDR = (HOST,PORT)
lock = thread.allocate_lock()
class TronClient:
def __init__(self,control=None):
self.tcpSock = socket(AF_INET,SOCK_STREAM)
#self.tcpSock.settimeout(.2)
self.recvBuff = []
def connect(self):
self.tcpSock.connect(ADDR)
self.clientUID = self.tcpSock.recv(BUFFSIZE)
print 'My clientUID is ', self.clientUID
t = Thread(target = self.receiveFromSrv())
t.setDaemon(1)
t.start()
print 'going to main loop'
self.mainLoop()
#t = Thread(target = self.mainLoop())
#t.setName('mainLoop')
#t.setDaemon(1)
#t.start()
def receiveFromSrv(self):
RECIEVING = 1
while RECIEVING:
#print 'Attempting to retrieve more data'
#lock.acquire()
#print 'Lock Aquired in recieveFromSrv'
#try:
data = self.tcpSock.recv(BUFFSIZE)
#except socket.timeout,e:
#print 'Error recieving data, ',e
#continue
#print data
if not data: continue
header = data[:6]
msgType,msgLength,clientID = unpack("hhh",header)
print msgType
print msgLength
print clientID,'\n'
msg = data[6:]
while len(msg) < msgLength:
data = self.tcpSock.recv(BUFFSIZE)
dataLen = len(data)
if dataLen <= msgLength:
msg += data
else:
remLen = msgLength-len(data) #we just need to retrieve first bit of data to complete msg
msg += data[:remLen]
self.recvBuff.append(data[remLen:])
print msg
#else:
#lock.release()
# print 'lock release in receiveFromSrv'
#time.sleep(2)
#RECIEVING = 0
def disconnect(self,data=''):
self.send(DISCONNECT_REQUEST,data)
#self.tcpSock.close()
def send(self,msgType,msg):
header = pack("hhh",msgType,len(msg),self.clientUID)
msg = header+msg
self.tcpSock.send(msg)
def mainLoop(self):
while 1:
try:
#lock.acquire()
#print 'lock aquired in mainLoop'
data = raw_input('> ')
except EOFError: # enter key hit without any data (blank line) so ignore and continue
continue
#if not data or data == '': # no valid data so just continue
# continue
if data=='exit': # client wants to disconnect, so send request to server
self.disconnect()
break
else:
self.send(TRON_CHAT,data)
#lock.release()
#print 'lock released in main loop'
#self.recieveFromSrv()
#data = self.tcpSock.recv(BUFFSIZE)
#t = Thread(target = self.receiveFromSrv())
#t.setDaemon(1)
#t.start()
if __name__ == "__main__":
cli = TronClient()
cli.connect()
#t = Thread(target = cli.connect())
#t.setName('connect')
#t.setDaemon(1)
#t.start()
The server (uses a lock when incrementing or decrementing number of clients):
from socket import *
from threading import *
import thread
from controller import *
from networklingo import *
from struct import pack,unpack
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
nclntlock = thread.allocate_lock()
class TronServer:
def __init__(self,maxConnect=4,control=None):
self.servSock = socket(AF_INET,SOCK_STREAM)
# ensure that you can restart server quickly when it terminates
self.servSock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
self.servSock.bind(ADDR)
self.servSock.listen(maxConnect)
# keep track of number of connected clients
self.clientsConnected = 0
# give each client a unique identfier for this run of server
self.clientUID = 0
# list of all clients to cycle through for sending
self.allClients = {}
# keep track of threads
self.cliThreads = {}
#reference back to controller
self.controller = control
self.recvBuff = []
def removeClient(self,clientID,addr):
if clientID in self.allClients.keys():
self.allClients[clientID].close()
print "Disconnected from", addr
nclntlock.acquire()
self.clientsConnected -= 1
nclntlock.release()
del self.allClients[clientID]
else:
print 'ClientID is not valid'
def recieve(self,clientsock,addr):
RECIEVING = 1
# loop serving the new client
while RECIEVING: # while PLAYING???
try:
data = clientsock.recv(BUFSIZE)
except:
RECIEVING = 0
continue
# if not data: break #no data was recieved
if data != '':
print 'Recieved msg from client: ',data
header = data[:6]
msgType,msgLength,clientID = unpack("hhh",header)
print msgType
print msgLength
print clientID,'\n'
if msgType == DISCONNECT_REQUEST: #handle disconnect request
self.removeClient(clientID,addr)
else: #pass message type and message off to controller
msg = data[6:]
while len(msg) < msgLength:
data = self.tcpSock.recv(BUFSIZE)
dataLen = len(data)
if dataLen <= msgLength:
msg += data
else:
remLen = msgLength-len(data) #we just need to retrieve first bit of data to complete msg
msg += data[:remLen]
self.recvBuff.append(data[remLen:])
print msg
# echo back the same data you just recieved
#clientsock.sendall(data)
self.send(TRON_CHAT,msg,-1) #send to client 0
for k in self.allClients.keys():
if self.allClients[k] == clientsock:
self.removeClient(k,addr)
print 'deleted after hard exit from clientID ', k
#self.cliThreads[k].join()
#del self.cliThreads[k]
# then tell controller to delete player with k
break
def send(self,msgType,msg,clientID=-1):
header = pack("hhh",msgType,len(msg),clientID)
msg = header+msg
if clientID in self.allClients:
self.allClients[clientID].send(msg)
elif clientID==ALL_PLAYERS:
for k in self.allClients.keys():
self.allClients[k].send(msg)
def mainLoop(self):
global nclntlock
try:
while self.controller != None and self.controller.state == WAITING:
print 'awaiting connections'
clientsock, caddy = self.servSock.accept()
nclntlock.acquire()
self.clientsConnected += 1
nclntlock.release()
print 'Client ',self.clientUID,' connected from:',caddy
clientsock.setblocking(0)
clientsock.send(str(self.clientUID))
self.allClients[self.clientUID] = clientsock
t = Thread(target = self.recieve, args = [clientsock,caddy])
t.setName('recieve-' + str(self.clientUID))
self.cliThreads[self.clientUID] = t
self.clientUID += 1
# t.setDaemon(1)
t.start()
finally:
self.servSock.close()
if __name__ == "__main__":
serv = TronServer(control = LocalController(nPlayers = 3, fWidth = 70, fHeight = 10))
t = Thread(target = serv.mainLoop())
t.setName('mainLoop')
# t.setDaemon(1)
t.start()
|
[
"I think you want to try and set the socket to non-blocking mode:\nhttp://docs.python.org/library/socket.html#socket.socket.setblocking\n\nSet blocking or non-blocking mode of\n the socket: if flag is 0, the socket\n is set to non-blocking, else to\n blocking mode. Initially all sockets\n are in blocking mode. In non-blocking\n mode, if a recv() call doesn’t find\n any data, or if a send() call can’t\n immediately dispose of the data, a\n error exception is raised; in blocking\n mode, the calls block until they can\n proceed. s.setblocking(0) is\n equivalent to s.settimeout(0);\n s.setblocking(1) is equivalent to\n s.settimeout(None).\n\nAlso, instead of using raw sockets, have you considdered using the multiprocessing module. It is a higher-level abstraction for doing network IO. The section on Pipes & Queues is specific to sending and receiving data between a client/server.\n"
] |
[
2
] |
[] |
[] |
[
"client",
"locking",
"multithreading",
"python"
] |
stackoverflow_0002256113_client_locking_multithreading_python.txt
|
Q:
What backing storage engine should I use for my Python library?
I'm writing a data processing library in Python that reads data from a variety of sources into memory, manipulates it, then exports it into a variety of different formats. I was loading this data into memory, but some of the datasets I'm processing can be particularly large (over 4 Gig).
I need an open source library for a backing store that can deal elegantly with large datasets. It needs the ability to alter the data structure dynamically (add, rename, and remove columns), and should support reasonably fast iteration. Ideally, it should be able to handle arbitrary-sized strings and integers (just as python does) but I can build that into the library, if needed. And it needs to be able to handle missing values.
Does anyone have any suggestions?
A:
A document-oriented database should cope fine with that kind of workload as long as you do not have complex joins.
Common representatives would be CouchDB or MongoDB.
They are both well suited for MapReduce like algorithms (this includes iterating over all datasets). If you want to merge rows with new data, you will want to have the 'table' sorted or have fast access to single elements: Both boils down to having an index.
Document-oriented DBs support multiple 'tables' by having documents with different schemas. They can query documents with a specific schema without a problem.
I do not think you will find a lightweighted solution to handle multiple 4 GB datasets with the requirements you listed. Especially dynamic datastructures are difficult to implement fast.
A:
Give Metakit a try. It allows flexibility in schemas and has Python bindings. Though it doesn't get much press, it's been around awhile.
A:
Another idea might to be to use Hadoop for your backend. It has similarities with CouchDB which someone mentioned before, but focuses more on effective processing of big datasets with MapReduce algorithms.
In comparison to CouchDB, Hadoop isn't real suited for real-time applications or as a database behind a website, because it has a high latency of accessing a single entry, but it real shines when iterating over all elements and computing even Peta-Bytes of data.
So maybe you should give Hadoop a try. Of course, it might take some time to get used to those MapReduce algorithms, but they are really a great way for describing such problems. And you don't have to deal with the storage of the interim results on your own. And a nice side-effect is, that your algorithm will still work when your data set becomes bigger, but then you might have to add another server. :-)
There is also quite a lot of books and documentation about Hadoop and MapReduce available, and here is a nice tutorial which might help you to get started with Hadoop and Python.
A:
Pytables might be the answer for you, although I suspect it is mostly used for numerical data, it might fit your bill too (according to what I see on their homepage).
|
What backing storage engine should I use for my Python library?
|
I'm writing a data processing library in Python that reads data from a variety of sources into memory, manipulates it, then exports it into a variety of different formats. I was loading this data into memory, but some of the datasets I'm processing can be particularly large (over 4 Gig).
I need an open source library for a backing store that can deal elegantly with large datasets. It needs the ability to alter the data structure dynamically (add, rename, and remove columns), and should support reasonably fast iteration. Ideally, it should be able to handle arbitrary-sized strings and integers (just as python does) but I can build that into the library, if needed. And it needs to be able to handle missing values.
Does anyone have any suggestions?
|
[
"A document-oriented database should cope fine with that kind of workload as long as you do not have complex joins.\nCommon representatives would be CouchDB or MongoDB.\nThey are both well suited for MapReduce like algorithms (this includes iterating over all datasets). If you want to merge rows with new data, you will want to have the 'table' sorted or have fast access to single elements: Both boils down to having an index.\nDocument-oriented DBs support multiple 'tables' by having documents with different schemas. They can query documents with a specific schema without a problem.\nI do not think you will find a lightweighted solution to handle multiple 4 GB datasets with the requirements you listed. Especially dynamic datastructures are difficult to implement fast.\n",
"Give Metakit a try. It allows flexibility in schemas and has Python bindings. Though it doesn't get much press, it's been around awhile.\n",
"Another idea might to be to use Hadoop for your backend. It has similarities with CouchDB which someone mentioned before, but focuses more on effective processing of big datasets with MapReduce algorithms.\nIn comparison to CouchDB, Hadoop isn't real suited for real-time applications or as a database behind a website, because it has a high latency of accessing a single entry, but it real shines when iterating over all elements and computing even Peta-Bytes of data.\nSo maybe you should give Hadoop a try. Of course, it might take some time to get used to those MapReduce algorithms, but they are really a great way for describing such problems. And you don't have to deal with the storage of the interim results on your own. And a nice side-effect is, that your algorithm will still work when your data set becomes bigger, but then you might have to add another server. :-)\nThere is also quite a lot of books and documentation about Hadoop and MapReduce available, and here is a nice tutorial which might help you to get started with Hadoop and Python.\n",
"Pytables might be the answer for you, although I suspect it is mostly used for numerical data, it might fit your bill too (according to what I see on their homepage).\n"
] |
[
3,
1,
1,
0
] |
[] |
[] |
[
"python",
"storage"
] |
stackoverflow_0002254694_python_storage.txt
|
Q:
Equivalent of Beautiful Soup's renderContents() method in lxml?
Is there an equivalent of Beautiful Soup's tag.renderContents() method in lxml?
I've tried using element.text, but that doesn't render child tags, as well as ''.join(etree.tostring(child) for child in element), but that doesn't render child text. The closest I've been able to find is etree.tostring(element), but that renders the opening and closing tags of element, which I do not want.
Is there another method I'm overlooking (or an alternative approach to accomplish this)?
A:
You're most of the way there with your original idea. element.text gives you the first text child of the element, and your list comprehension gives you everything else. If you concatenate the two strings together, you get what you're looking for:
>>> xmlstr = "<sec>header <p>para 0</p> text <p>para 1</p> footer</sec>"
>>> element = etree.fromstring(xmlstr)
>>>
>>> element.text + "".join(map (etree.tostring, element))
'header <p>para 0</p> text <p>para 1</p> footer'
>>>
Ari.
A:
One hackish solution:
from lxml import etree
def render_contents(element):
"""
Surely there is a safe lxml built-in for this...
"""
tagname = element.tag
return re.sub('</%s>\s*$' % tagname, '',
re.sub(r'^<%s(\s+\w+=".*?")*?>' % tagname,
'', etree.tostring(element))).strip()
Edit
Really, there's no better method than this?
|
Equivalent of Beautiful Soup's renderContents() method in lxml?
|
Is there an equivalent of Beautiful Soup's tag.renderContents() method in lxml?
I've tried using element.text, but that doesn't render child tags, as well as ''.join(etree.tostring(child) for child in element), but that doesn't render child text. The closest I've been able to find is etree.tostring(element), but that renders the opening and closing tags of element, which I do not want.
Is there another method I'm overlooking (or an alternative approach to accomplish this)?
|
[
"You're most of the way there with your original idea. element.text gives you the first text child of the element, and your list comprehension gives you everything else. If you concatenate the two strings together, you get what you're looking for:\n>>> xmlstr = \"<sec>header <p>para 0</p> text <p>para 1</p> footer</sec>\"\n>>> element = etree.fromstring(xmlstr)\n>>>\n>>> element.text + \"\".join(map (etree.tostring, element))\n'header <p>para 0</p> text <p>para 1</p> footer'\n>>>\n\nAri.\n",
"One hackish solution:\nfrom lxml import etree\ndef render_contents(element):\n \"\"\"\n Surely there is a safe lxml built-in for this...\n \"\"\"\n tagname = element.tag\n return re.sub('</%s>\\s*$' % tagname, '',\n re.sub(r'^<%s(\\s+\\w+=\".*?\")*?>' % tagname,\n '', etree.tostring(element))).strip()\n\nEdit\nReally, there's no better method than this?\n"
] |
[
1,
0
] |
[] |
[] |
[
"beautifulsoup",
"lxml",
"python",
"rendering",
"xml"
] |
stackoverflow_0002028270_beautifulsoup_lxml_python_rendering_xml.txt
|
Q:
Running a PHP script inside a Python WSGI enviroment
I have a simple PHP script that outputs a dir listing in XML format. I use it to let a flash slideshow know what files are available to show.
I've just added the flash to a website that's powered by Django and the PHP file is now served up as it is, not parsed.
It's in the directory with the images under my media directory.
The server I use runs plesk so I do my config for each domain in a vhost.conf file (which gets included into the main appache conf I think)
It looks like this:
WSGIScriptAlias / /var/www/vhosts/<domain>/conf/django.wsgi
Alias /media/ /var/www/vhosts/<domain>/httpdocs/media/
I thought this meant that requests for anything under / are passed django to handle.
Except when they are for /media/... then they are served by apache as normal from the specified dir.
That works for the images, but does not parse the PHP file.
What should I do?
A:
Maybe read this thread, and port your PHP script to Python:
os.walk() python: xml representation of a directory structure, recursion
A:
So it turns out the problem was two things, making it hard to find.
Thanks Ignacio Vazquez-Abrams, I had my lines the wrong way around.
Once that was solved, PHP would not serve my file because it was in a dir that was symlinked from outside the allowed path(s). I resolved this by turning off open_basedir restrictions for this vhost. My new vhost.conf is below.
<Directory /var/www/vhosts/<domain>/httpdocs>
php_admin_flag engine on
php_admin_value open_basedir none
</Directory>
Alias /media/ /var/www/vhosts/<domain>/httpdocs/media/
WSGIScriptAlias / /var/www/vhosts/<domain>/conf/django.wsgi
A:
If you have not configured Apache so that it knows that .php files under the '/media' directory should be processed by PHP somehow, they will not be. So, the mod_wsgi configuration is fine, the problem is likely your PHP configuration.
How are you configuring PHP? Are you using mod_php, or PHP via fastcgi? How is Apache configured so that it knows to treat .php files as PHP and for what directories has that configuration been applied to?
A:
The WSGIScriptAlias directive there swallows up URLs meant for Alias. Swap the order.
|
Running a PHP script inside a Python WSGI enviroment
|
I have a simple PHP script that outputs a dir listing in XML format. I use it to let a flash slideshow know what files are available to show.
I've just added the flash to a website that's powered by Django and the PHP file is now served up as it is, not parsed.
It's in the directory with the images under my media directory.
The server I use runs plesk so I do my config for each domain in a vhost.conf file (which gets included into the main appache conf I think)
It looks like this:
WSGIScriptAlias / /var/www/vhosts/<domain>/conf/django.wsgi
Alias /media/ /var/www/vhosts/<domain>/httpdocs/media/
I thought this meant that requests for anything under / are passed django to handle.
Except when they are for /media/... then they are served by apache as normal from the specified dir.
That works for the images, but does not parse the PHP file.
What should I do?
|
[
"Maybe read this thread, and port your PHP script to Python:\nos.walk() python: xml representation of a directory structure, recursion\n",
"So it turns out the problem was two things, making it hard to find.\nThanks Ignacio Vazquez-Abrams, I had my lines the wrong way around.\nOnce that was solved, PHP would not serve my file because it was in a dir that was symlinked from outside the allowed path(s). I resolved this by turning off open_basedir restrictions for this vhost. My new vhost.conf is below.\n<Directory /var/www/vhosts/<domain>/httpdocs>\n php_admin_flag engine on\n php_admin_value open_basedir none\n</Directory>\n\nAlias /media/ /var/www/vhosts/<domain>/httpdocs/media/\n\nWSGIScriptAlias / /var/www/vhosts/<domain>/conf/django.wsgi\n\n",
"If you have not configured Apache so that it knows that .php files under the '/media' directory should be processed by PHP somehow, they will not be. So, the mod_wsgi configuration is fine, the problem is likely your PHP configuration.\nHow are you configuring PHP? Are you using mod_php, or PHP via fastcgi? How is Apache configured so that it knows to treat .php files as PHP and for what directories has that configuration been applied to?\n",
"The WSGIScriptAlias directive there swallows up URLs meant for Alias. Swap the order.\n"
] |
[
3,
2,
1,
1
] |
[] |
[] |
[
"apache",
"django",
"php",
"python",
"wsgi"
] |
stackoverflow_0002159637_apache_django_php_python_wsgi.txt
|
Q:
Options for read-only binary flat-file storage using Python
I have been tasked with setting up a flat-file SKU database for use on embedded devices with limited storage and processor speed.
Basically the data I need to store consists of the following:
SKU
Description
Location
Price
Qty
The file will consist of several million records.
The most important considerations are storage space and retrieval time. Records will only need to be retrieved by SKU and it will be read-only, so the file can be sorted by SKU.
I would like to access this data with Python. So my questions comes down to this.
Are there existing Python libraries that can provide this functionality for me, or do I need to roll my own?
If the answer comes down to roll my own, does anyone have a suggestions, or good references for doing so?
A:
How about SQLite with Python bindings? It has a little more than you need, but it's standard software and well-tested.
A:
The old way would be to use a simple key/value data table like gdbm module. Python comes with support for that, but it's not built into the default Python installation on my machine.
In general, use SQLite. As others wrote, it comes standard with Python, and it's used in a lot of embedded systems already.
If the records are fixed length then you can use the bisect module. The file size / the record size gives the number of records in the file. The bisect search will do an O(log(n)) lookup in the file, and you'll need to write an adapter to test for equality. While I haven't tested it, here's a sketch:
import bisect
RECORD_SIZE = 50
class MatchFirst10Chars(object):
def __init__(self, word):
self.word = word
def __lt__(self, other):
return self.word < other[:10]
class FileLookup(object):
def __init__(self, f):
self.f = f
f.seek(0, 2)
self.size = f.tell() // RECORD_SIZE
def __len__(self):
return self.size
def __getitem__(self, i):
self.f.seek(i*RECORD_SIZE)
return self.f.read(RECORD_SIZE)
SKU = "123-56-89 "
f = open("data_file")
fl = FileLookup(f)
i = bisect.bisect(fl, MatchFirst10Chars(SKU))
You could additionally gzip the file and seek on a gzip'ped file, but that's a tradeoff for space vs. time that you'll have to test.
A:
How about HDF? If you don't need SQL and require fast access to your data, there's nothing faster... in Python... for numerical or structured data.
Take a look at the DatabaseInterfaces section on the Python wiki. It's comprehensive. There are a couple of "pure" Python options listed (like SnakeSQL), which are a tad nicer to deploy. And, of course, there's always Berkeley DB and the like, which are super lean & raw.
Honestly, SQLite will probably work fine for you. If you really need to eek out more performance, then you'd be looking at a record-based format like BDB.
A:
May I suggest cdb? (Python bindings: python-cdb.)
It's a format used for read-only data, like you have; it's basically 256 giant hash tables, each able to have a different number of buckets. The cool thing about cdb is that the file doesn't need to be loaded into memory; it's structured in a way that you can do lookups by just mmaping in the bits you need.
The cdb spec is a good read, not least because the lines are formatted to create a uniform right margin. :-D
A:
A simple solution is CPickle. You can also find similar questions on SO.
A:
A variation of Andrew Dalke's answer (so you can still use binary search to locate the SKU quickly) which may reduce the space requirements would be to have fixed sized records at the start of the file (one per SKU) and then all the Descriptions and Locations (as null terminated strings say)
You get to save space by not having to pad out the locations and descriptions to fixed length. Also you can save space if there are lots of duplicate locations
Here is an example:
say you have
SKU 16 bytes
Description Variable length
Location Variable length
Price 4 bytes (up to $42949672.95)
Quantity 4 bytes (up to 4294967295)
offset SKU desc_off loc_off Price Quantity
0x00000000 SKU0000000000001 0x01f78a40 0x01f78a47 0x000003e8 0x000f4240
0x00000020 SKU0000000000002 0x01f78a53 0x01f78a59 ...
...
... # 999998 more records
...
0x01f78a40 Widget\x00
0x01f78a47 Head office\x00
0x01f78a53 Table\x00
0x01f78a59 Warehouse\x00
|
Options for read-only binary flat-file storage using Python
|
I have been tasked with setting up a flat-file SKU database for use on embedded devices with limited storage and processor speed.
Basically the data I need to store consists of the following:
SKU
Description
Location
Price
Qty
The file will consist of several million records.
The most important considerations are storage space and retrieval time. Records will only need to be retrieved by SKU and it will be read-only, so the file can be sorted by SKU.
I would like to access this data with Python. So my questions comes down to this.
Are there existing Python libraries that can provide this functionality for me, or do I need to roll my own?
If the answer comes down to roll my own, does anyone have a suggestions, or good references for doing so?
|
[
"How about SQLite with Python bindings? It has a little more than you need, but it's standard software and well-tested.\n",
"The old way would be to use a simple key/value data table like gdbm module. Python comes with support for that, but it's not built into the default Python installation on my machine.\nIn general, use SQLite. As others wrote, it comes standard with Python, and it's used in a lot of embedded systems already.\nIf the records are fixed length then you can use the bisect module. The file size / the record size gives the number of records in the file. The bisect search will do an O(log(n)) lookup in the file, and you'll need to write an adapter to test for equality. While I haven't tested it, here's a sketch:\nimport bisect\n\nRECORD_SIZE = 50\n\nclass MatchFirst10Chars(object):\n def __init__(self, word):\n self.word = word\n def __lt__(self, other):\n return self.word < other[:10]\n\nclass FileLookup(object):\n def __init__(self, f):\n self.f = f\n f.seek(0, 2)\n self.size = f.tell() // RECORD_SIZE\n def __len__(self):\n return self.size\n\n def __getitem__(self, i):\n self.f.seek(i*RECORD_SIZE)\n return self.f.read(RECORD_SIZE)\n\n\nSKU = \"123-56-89 \"\nf = open(\"data_file\")\nfl = FileLookup(f)\ni = bisect.bisect(fl, MatchFirst10Chars(SKU))\n\nYou could additionally gzip the file and seek on a gzip'ped file, but that's a tradeoff for space vs. time that you'll have to test.\n",
"How about HDF? If you don't need SQL and require fast access to your data, there's nothing faster... in Python... for numerical or structured data.\nTake a look at the DatabaseInterfaces section on the Python wiki. It's comprehensive. There are a couple of \"pure\" Python options listed (like SnakeSQL), which are a tad nicer to deploy. And, of course, there's always Berkeley DB and the like, which are super lean & raw.\nHonestly, SQLite will probably work fine for you. If you really need to eek out more performance, then you'd be looking at a record-based format like BDB.\n",
"May I suggest cdb? (Python bindings: python-cdb.)\nIt's a format used for read-only data, like you have; it's basically 256 giant hash tables, each able to have a different number of buckets. The cool thing about cdb is that the file doesn't need to be loaded into memory; it's structured in a way that you can do lookups by just mmaping in the bits you need.\nThe cdb spec is a good read, not least because the lines are formatted to create a uniform right margin. :-D\n",
"A simple solution is CPickle. You can also find similar questions on SO.\n",
"A variation of Andrew Dalke's answer (so you can still use binary search to locate the SKU quickly) which may reduce the space requirements would be to have fixed sized records at the start of the file (one per SKU) and then all the Descriptions and Locations (as null terminated strings say)\nYou get to save space by not having to pad out the locations and descriptions to fixed length. Also you can save space if there are lots of duplicate locations\nHere is an example:\nsay you have\nSKU 16 bytes\nDescription Variable length\nLocation Variable length\nPrice 4 bytes (up to $42949672.95)\nQuantity 4 bytes (up to 4294967295)\n\n\n\n offset SKU desc_off loc_off Price Quantity\n0x00000000 SKU0000000000001 0x01f78a40 0x01f78a47 0x000003e8 0x000f4240\n0x00000020 SKU0000000000002 0x01f78a53 0x01f78a59 ...\n...\n... # 999998 more records\n...\n0x01f78a40 Widget\\x00\n0x01f78a47 Head office\\x00\n0x01f78a53 Table\\x00\n0x01f78a59 Warehouse\\x00\n\n"
] |
[
4,
4,
1,
1,
0,
0
] |
[] |
[] |
[
"data_structures",
"flat_file",
"minimum_size",
"python"
] |
stackoverflow_0002256256_data_structures_flat_file_minimum_size_python.txt
|
Q:
Python IRC Client
import socket
from time import strftime
time = strftime("%H:%M:%S")
irc = 'irc.tormented-box.net'
port = 6667
channel = '#test'
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
print sck.recv(4096)
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN ' + channel + '\r\n')
while True:
data = sck.recv(4096)
if data.find('PING') != -1:
sck.send('PONG ' + data.split() [1] + '\r\n')
elif data.find ( 'PRIVMSG' ) != -1:
nick = data.split ( '!' ) [ 0 ].replace ( ':', '')
if data.find('!op') != -1:
sck.send('MODE #test +o ' + nick + '\r\n')
When I'm trying to !op nick in IRC I end up op'ing myself Instead of giving +o to the other user, I'm not sure what I have to change in the "nick" variable.. I'll appreciate it if someone can help me.. thanks.
A:
You really need to rethink how you're trying to parse messages; as-is I can say "haha !opwned PRIVMSG" to get ops. (For everyone else: PRIVMSG is part of the IRC protocol, not normally said by users.)
However, I don't see the error in your current code, but you've changed what you're really running when you posted to SO (see how the indentation is wrong on the last line, this won't run at all). Did you accidentally change something else important too?
Set yourself up some kind of debug console with raw IRC traffic; it will be immensely valuable. Writing to a simple file works (make sure you flush it and then you can use "tail --follow" to view it as your bot runs). You can then inject your own debug messages too, which will help you debug problems like this. (Eg. You'd include repr(nick) and repr(data) to see what's happening.)
A:
You may find the Supybot project to be of interest, it is an IRC bot written in Python, and it is very easy to create your own plugins, a lot of this extra work is already done for you, so you can just worry about those features you want.
G'Luck!
Supybot Sourceforge
|
Python IRC Client
|
import socket
from time import strftime
time = strftime("%H:%M:%S")
irc = 'irc.tormented-box.net'
port = 6667
channel = '#test'
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
print sck.recv(4096)
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN ' + channel + '\r\n')
while True:
data = sck.recv(4096)
if data.find('PING') != -1:
sck.send('PONG ' + data.split() [1] + '\r\n')
elif data.find ( 'PRIVMSG' ) != -1:
nick = data.split ( '!' ) [ 0 ].replace ( ':', '')
if data.find('!op') != -1:
sck.send('MODE #test +o ' + nick + '\r\n')
When I'm trying to !op nick in IRC I end up op'ing myself Instead of giving +o to the other user, I'm not sure what I have to change in the "nick" variable.. I'll appreciate it if someone can help me.. thanks.
|
[
"You really need to rethink how you're trying to parse messages; as-is I can say \"haha !opwned PRIVMSG\" to get ops. (For everyone else: PRIVMSG is part of the IRC protocol, not normally said by users.)\nHowever, I don't see the error in your current code, but you've changed what you're really running when you posted to SO (see how the indentation is wrong on the last line, this won't run at all). Did you accidentally change something else important too?\nSet yourself up some kind of debug console with raw IRC traffic; it will be immensely valuable. Writing to a simple file works (make sure you flush it and then you can use \"tail --follow\" to view it as your bot runs). You can then inject your own debug messages too, which will help you debug problems like this. (Eg. You'd include repr(nick) and repr(data) to see what's happening.)\n",
"You may find the Supybot project to be of interest, it is an IRC bot written in Python, and it is very easy to create your own plugins, a lot of this extra work is already done for you, so you can just worry about those features you want. \nG'Luck!\nSupybot Sourceforge\n"
] |
[
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002215448_python.txt
|
Q:
Options for storing metadata about CUPS print jobs?
I'm writing a print system that puts a simplified interface on top of CUPS. Users drop jobs into one queue, the system processes them in various ways (statistics, page quotas, etc.), and then offers the user a web interface to dispatch the job to one of multiple printers.
Since there may be several user kiosks, an admin station, etc., I need to store job metadata in something that can handle concurrent access. (Can you call data structures "re-entrant"?) A few options I can imagine are
a MySQL database: massively overkill, but certainly stable and supported
metadata files, with concurrent access handled manually: perfectly tailored to my needs, but then I have to re-implement a subset of MySQL's atomicity, and probably do it poorly
write into the CUPS control files, using the provided thread-safe cupsipp.h API
The last option sounds most attractive, but there's a catch: I'm writing this in Python, and neither pycups nor pkipplib seem to have any way to modify a control file.
Edit: I should clarify that pkipplib can generate new IPP requests, but doesn't give any way to modify the existing control file. That is, I would have to make my updates by submitting them as new jobs.
Anyone have a better idea? Advice would be much appreciated.
A:
Have you considered sqlite or redis? Both of those are low overhead and easy to spin up, especially when you're not really dealing with complex datasets.
|
Options for storing metadata about CUPS print jobs?
|
I'm writing a print system that puts a simplified interface on top of CUPS. Users drop jobs into one queue, the system processes them in various ways (statistics, page quotas, etc.), and then offers the user a web interface to dispatch the job to one of multiple printers.
Since there may be several user kiosks, an admin station, etc., I need to store job metadata in something that can handle concurrent access. (Can you call data structures "re-entrant"?) A few options I can imagine are
a MySQL database: massively overkill, but certainly stable and supported
metadata files, with concurrent access handled manually: perfectly tailored to my needs, but then I have to re-implement a subset of MySQL's atomicity, and probably do it poorly
write into the CUPS control files, using the provided thread-safe cupsipp.h API
The last option sounds most attractive, but there's a catch: I'm writing this in Python, and neither pycups nor pkipplib seem to have any way to modify a control file.
Edit: I should clarify that pkipplib can generate new IPP requests, but doesn't give any way to modify the existing control file. That is, I would have to make my updates by submitting them as new jobs.
Anyone have a better idea? Advice would be much appreciated.
|
[
"Have you considered sqlite or redis? Both of those are low overhead and easy to spin up, especially when you're not really dealing with complex datasets.\n"
] |
[
0
] |
[] |
[] |
[
"concurrency",
"cups",
"ipp_protocol",
"python"
] |
stackoverflow_0002254693_concurrency_cups_ipp_protocol_python.txt
|
Q:
What does `**` mean in the expression `dict(d1, **d2)`?
I am intrigued by the following python expression:
d3 = dict(d1, **d2)
The task is to merge 2 dictionaries into a third one, and the above expression accomplishes the task just fine. I am interested in the ** operator and what exactly is it doing to the expression. I thought that ** was the power operator and haven't seen it used in the context above yet.
The full snippet of code is this:
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'c': 3, 'd': 4}
>>> d3 = dict(d1, **d2)
>>> print d3
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
A:
** in argument lists has a special meaning, as covered in section 4.7 of the tutorial. The dictionary (or dictionary-like) object passed with **kwargs is expanded into keyword arguments to the callable, much like *args is expanded into separate positional arguments.
A:
The ** turns the dictionary into keyword parameters:
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'c': 3, 'd': 4}
>>> d3 = dict(d1, **d2)
Becomes:
>>> d3 = dict(d1, c=3, d=4)
A:
In Python, any function can accept multiple arguments with *;
or multiple keyword arguments with **.
Receiving-side example:
>>> def fn(**kwargs):
... for kwarg in kwargs:
... print kwarg
...
>>> fn(a=1,b=2,c=3)
a
c
b
Calling-side example (thanks Thomas):
>>> mydict = dict(a=1,b=2,c=3)
>>> fn(**mydict)
a
c
b
A:
It's also worth mentioning the mechanics of the dict constructor. It takes an initial dictionary as its first argument and can also take keyword arguments, each representing a new member to add to the newly created dictionary.
A:
you have got your answer of the ** operator. here's another way to add dictionaries
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'c': 3, 'd': 4}
>>> d3=d1.copy()
>>> d3.update(d2)
>>> d3
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
A:
That operator is used to unpack argument list:
http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists
|
What does `**` mean in the expression `dict(d1, **d2)`?
|
I am intrigued by the following python expression:
d3 = dict(d1, **d2)
The task is to merge 2 dictionaries into a third one, and the above expression accomplishes the task just fine. I am interested in the ** operator and what exactly is it doing to the expression. I thought that ** was the power operator and haven't seen it used in the context above yet.
The full snippet of code is this:
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'c': 3, 'd': 4}
>>> d3 = dict(d1, **d2)
>>> print d3
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
|
[
"** in argument lists has a special meaning, as covered in section 4.7 of the tutorial. The dictionary (or dictionary-like) object passed with **kwargs is expanded into keyword arguments to the callable, much like *args is expanded into separate positional arguments.\n",
"The ** turns the dictionary into keyword parameters:\n>>> d1 = {'a': 1, 'b': 2}\n>>> d2 = {'c': 3, 'd': 4}\n>>> d3 = dict(d1, **d2)\n\nBecomes:\n>>> d3 = dict(d1, c=3, d=4)\n\n",
"In Python, any function can accept multiple arguments with *;\nor multiple keyword arguments with **.\nReceiving-side example:\n>>> def fn(**kwargs):\n... for kwarg in kwargs:\n... print kwarg\n... \n>>> fn(a=1,b=2,c=3)\na\nc\nb\n\nCalling-side example (thanks Thomas):\n>>> mydict = dict(a=1,b=2,c=3)\n>>> fn(**mydict)\na\nc\nb\n\n",
"It's also worth mentioning the mechanics of the dict constructor. It takes an initial dictionary as its first argument and can also take keyword arguments, each representing a new member to add to the newly created dictionary.\n",
"you have got your answer of the ** operator. here's another way to add dictionaries\n>>> d1 = {'a': 1, 'b': 2}\n>>> d2 = {'c': 3, 'd': 4}\n>>> d3=d1.copy()\n>>> d3.update(d2)\n>>> d3\n{'a': 1, 'c': 3, 'b': 2, 'd': 4}\n\n",
"That operator is used to unpack argument list:\nhttp://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists\n"
] |
[
50,
17,
11,
3,
2,
1
] |
[] |
[] |
[
"dictionary",
"operators",
"python",
"set_operations",
"syntax"
] |
stackoverflow_0002255878_dictionary_operators_python_set_operations_syntax.txt
|
Q:
Is there a Term::ANSIScreen equivalent for Python?
Perl has the excellent module Term::ANSIScreen for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aware of an equivalent?
A:
If you only need colors You may want to borrow the implementation from pygments. IMO it's much cleaner than the one from ActiveState
http://dev.pocoo.org/hg/pygments-main/file/b2deea5b5030/pygments/console.py
A:
Here's a cookbook recipe on ActiveState to get you started. It covers colors and positioning.
[Edit: The pygments code submitted above by Jorge Vargas is a better approach. ]
A:
There is also the termcolor and the termstyle packages. The latter is capable of disabling colour output if stdout is not a terminal.
See also this question.
A:
While I haven't used it myself, I believe the curses library is commonly used for this:
http://docs.python.org/library/curses.html
And the How-to:
http://docs.python.org/howto/curses.html#curses-howto
Unfortunatly, this module doesn't appear to be available in the standard library for windows.
This site apparently has a windows solution:
http://adamv.com/dev/python/curses/
|
Is there a Term::ANSIScreen equivalent for Python?
|
Perl has the excellent module Term::ANSIScreen for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aware of an equivalent?
|
[
"If you only need colors You may want to borrow the implementation from pygments. IMO it's much cleaner than the one from ActiveState\nhttp://dev.pocoo.org/hg/pygments-main/file/b2deea5b5030/pygments/console.py\n",
"Here's a cookbook recipe on ActiveState to get you started. It covers colors and positioning.\n[Edit: The pygments code submitted above by Jorge Vargas is a better approach. ]\n",
"There is also the termcolor and the termstyle packages. The latter is capable of disabling colour output if stdout is not a terminal.\nSee also this question.\n",
"While I haven't used it myself, I believe the curses library is commonly used for this:\nhttp://docs.python.org/library/curses.html\nAnd the How-to:\nhttp://docs.python.org/howto/curses.html#curses-howto\nUnfortunatly, this module doesn't appear to be available in the standard library for windows.\nThis site apparently has a windows solution:\nhttp://adamv.com/dev/python/curses/\n"
] |
[
8,
3,
3,
2
] |
[] |
[] |
[
"ansi",
"perl",
"python"
] |
stackoverflow_0000471463_ansi_perl_python.txt
|
Q:
Sorting dictionary keys by values in a list?
I have a dictionary and a list. The values of the keys match those of the list, I'm just trying to find out how to sort the values in the dictionary by the values in the list.
>>> l = [1, 2, 37, 32, 4, 3]
>>> d = {
32: 'Megumi',
1: 'Ai',
2: 'Risa',
3: 'Eri',
4: 'Sayumi',
37: 'Mai'
}
I've tried using something along the lines of...
>>> sorted(dict.keys(), key=list.index)
... but obviously that only returns the keys in the desired order.
(Should have realized at 3AM that list and dict were horrible names, I changed them to l and d accordingly.)
A:
Don't shadow the builtins dict and list
>>> L = [1, 2, 37, 32, 4, 3]
>>> D = {
... 32: 'Megumi',
... 1: 'Ai',
... 2: 'Risa',
... 3: 'Eri',
... 4: 'Sayumi',
... 37: 'Mai'
... }
# Seems roundabout to use sorted here
# This causes an index error for keys in D that are not listed in L
>>> sorted(D.items(), key=lambda x:L.index(x[0]))
[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi'), (3, 'Eri')]
>>>
# I think this is more direct than using sorted.
# This also ignores/skips keys in D that aren't listed in L
>>> [(i,D[i]) for i in L]
[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi'), (3, 'Eri')]
>>>
A:
You shouldn't call you variables dict and list, because then, you cant use the build-in methods any more. I have renamed them in this example.
>>> l = [1, 2, 37, 32, 4]
>>> d = dict = {
... 32: 'Megumi',
... 1: 'Ai',
... 2: 'Risa',
... 3: 'Eri',
... 4: 'Sayumi',
... 37: 'Mai'
... }
You can't sort the default dict type in Python, because it's a hash table and therefore sorted by the hash functions of the keys. Anyway, you might find some alternative Python implementations when you search for OrderedDict or something like that in google.
But you can create a new list containing the (key, value)-tuples from the dictionary, which is sorted by the first list:
>>> s = list((i, d.get(i)) for i in L)
>>> print s
[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi')]
Or if you are only interested in the values:
>>> s = list(d.get(i) for i in L)
>>> print s
['Ai', 'Risa', 'Mai', 'Megumi', 'Sayumi']
Hope that helps!
A:
You can't sort a dictionary because a dictionary is not ordered.
What you can do instead is:
Get all the key-value pairs out of the dictionary, sort them and put them into a list or
What you are already doing: keep a sorted list of the keys and use the dictionary when you need the value corresponding to a key.
A:
Sorted dict is in fact a list of 2-tuples, because in Python 2.x there're no ordered dictionaty built-in. You almost got the solution, just add a value lookup after sorting keys:
[(k,dict[k]) for k in sorted(dict.keys(), key=list.index)]
But this fails when a key is not in list. Let's add a modification to put all such values at the end of sort, ordered by value:
def _index(x): # Allow non-full key list to be used in sorting
try: return (list.index(x), x)
except ValueError: return (sys.maxint, x)
[(k,dict[k]) for k in sorted(dict.keys(), key=_index)]
A:
In Python 3.1, you could use the OrderedDict class:
from collections import OrderedDict
l = [1, 2, 37, 32, 4]
d = {
32: 'Megumi',
1: 'Ai',
2: 'Risa',
3: 'Eri',
4: 'Sayumi',
37: 'Mai'
}
def myindex(element):
try:
return l.index(element)
except ValueError:
return -1 # nonexisting keys are appended to the beginning of the list
od = OrderedDict(sorted(d.items(), key = lambda t: myindex(t[0])))
print(od)
As I didn't know what you want to do with keys that aren't in the list, I just return -1 in that case, meaning those elements are prepended to the list somehow (i.e. in non-stable order).
My example will print
OrderedDict([(3, 'Eri'), (1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi')])
|
Sorting dictionary keys by values in a list?
|
I have a dictionary and a list. The values of the keys match those of the list, I'm just trying to find out how to sort the values in the dictionary by the values in the list.
>>> l = [1, 2, 37, 32, 4, 3]
>>> d = {
32: 'Megumi',
1: 'Ai',
2: 'Risa',
3: 'Eri',
4: 'Sayumi',
37: 'Mai'
}
I've tried using something along the lines of...
>>> sorted(dict.keys(), key=list.index)
... but obviously that only returns the keys in the desired order.
(Should have realized at 3AM that list and dict were horrible names, I changed them to l and d accordingly.)
|
[
"Don't shadow the builtins dict and list\n>>> L = [1, 2, 37, 32, 4, 3]\n>>> D = {\n... 32: 'Megumi',\n... 1: 'Ai',\n... 2: 'Risa',\n... 3: 'Eri',\n... 4: 'Sayumi',\n... 37: 'Mai'\n... }\n\n# Seems roundabout to use sorted here\n# This causes an index error for keys in D that are not listed in L\n>>> sorted(D.items(), key=lambda x:L.index(x[0]))\n[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi'), (3, 'Eri')]\n>>>\n\n# I think this is more direct than using sorted.\n# This also ignores/skips keys in D that aren't listed in L\n>>> [(i,D[i]) for i in L]\n[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi'), (3, 'Eri')]\n>>>\n\n",
"You shouldn't call you variables dict and list, because then, you cant use the build-in methods any more. I have renamed them in this example.\n>>> l = [1, 2, 37, 32, 4]\n>>> d = dict = {\n... 32: 'Megumi', \n... 1: 'Ai',\n... 2: 'Risa',\n... 3: 'Eri', \n... 4: 'Sayumi', \n... 37: 'Mai'\n... }\n\nYou can't sort the default dict type in Python, because it's a hash table and therefore sorted by the hash functions of the keys. Anyway, you might find some alternative Python implementations when you search for OrderedDict or something like that in google.\nBut you can create a new list containing the (key, value)-tuples from the dictionary, which is sorted by the first list:\n>>> s = list((i, d.get(i)) for i in L)\n>>> print s\n[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi')]\n\nOr if you are only interested in the values:\n>>> s = list(d.get(i) for i in L)\n>>> print s\n['Ai', 'Risa', 'Mai', 'Megumi', 'Sayumi']\n\nHope that helps!\n",
"You can't sort a dictionary because a dictionary is not ordered.\nWhat you can do instead is:\n\nGet all the key-value pairs out of the dictionary, sort them and put them into a list or\nWhat you are already doing: keep a sorted list of the keys and use the dictionary when you need the value corresponding to a key.\n\n",
"Sorted dict is in fact a list of 2-tuples, because in Python 2.x there're no ordered dictionaty built-in. You almost got the solution, just add a value lookup after sorting keys:\n[(k,dict[k]) for k in sorted(dict.keys(), key=list.index)]\n\nBut this fails when a key is not in list. Let's add a modification to put all such values at the end of sort, ordered by value:\ndef _index(x): # Allow non-full key list to be used in sorting\n try: return (list.index(x), x)\n except ValueError: return (sys.maxint, x)\n\n[(k,dict[k]) for k in sorted(dict.keys(), key=_index)]\n\n",
"In Python 3.1, you could use the OrderedDict class:\nfrom collections import OrderedDict\n\nl = [1, 2, 37, 32, 4]\nd = {\n 32: 'Megumi', \n 1: 'Ai',\n 2: 'Risa',\n 3: 'Eri', \n 4: 'Sayumi', \n 37: 'Mai'\n}\n\ndef myindex(element):\n try:\n return l.index(element)\n except ValueError:\n return -1 # nonexisting keys are appended to the beginning of the list\n\nod = OrderedDict(sorted(d.items(), key = lambda t: myindex(t[0])))\n\nprint(od)\n\nAs I didn't know what you want to do with keys that aren't in the list, I just return -1 in that case, meaning those elements are prepended to the list somehow (i.e. in non-stable order).\nMy example will print\nOrderedDict([(3, 'Eri'), (1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi')])\n\n"
] |
[
6,
4,
1,
0,
0
] |
[] |
[] |
[
"dictionary",
"list",
"python",
"sorting"
] |
stackoverflow_0002257101_dictionary_list_python_sorting.txt
|
Q:
How can I count words in complex documents (.rtf, .doc, .odt, etc)?
I'm trying to write a Python function that, given the path to a document file, returns the number of words in that document. This is fairly easy to do with .txt files, and there are tools that allow me to hack support for a few more complex document formats together, but I want a really comprehensive solution.
Looking at OpenOffice.org's py-uno scripting interface and list of supported formats, it would seem ideal to load the documents in a headless OOo and call its word-count function. However, I can't find any py-uno tutorials or sample code that go beyond basic document generation, and even the code snippets I have found are out of date by a half-decade and no longer work.
Whether by using OOo and Uno or not, how can I get reliable word-counts for documents of various formats?
A:
load the documents in a headless OOo
and call its word-count function
PyODConverter is a recent (11-2009) script to use OOo to convert multiple file types. Looking at the script, it has basic loading of all the OOo supported documents.
This is how you start OOo as a headless service:
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
Then you just have to write a small bootstrapper that calls OOo on the commandline, runs your script, then closes OOo.
A:
This could be not the option for you, but in case it is - you can upload documents to Google Docs and then export in .txt format. Google usually does very nice job for the conversion.
You can find relevant APIs here: http://code.google.com/intl/pl/apis/documents/docs/1.0/developers_guide_python.html
Take a look at login, uploading and exporting sections.
|
How can I count words in complex documents (.rtf, .doc, .odt, etc)?
|
I'm trying to write a Python function that, given the path to a document file, returns the number of words in that document. This is fairly easy to do with .txt files, and there are tools that allow me to hack support for a few more complex document formats together, but I want a really comprehensive solution.
Looking at OpenOffice.org's py-uno scripting interface and list of supported formats, it would seem ideal to load the documents in a headless OOo and call its word-count function. However, I can't find any py-uno tutorials or sample code that go beyond basic document generation, and even the code snippets I have found are out of date by a half-decade and no longer work.
Whether by using OOo and Uno or not, how can I get reliable word-counts for documents of various formats?
|
[
"load the documents in a headless OOo\nand call its word-count function\nPyODConverter is a recent (11-2009) script to use OOo to convert multiple file types. Looking at the script, it has basic loading of all the OOo supported documents. \nThis is how you start OOo as a headless service:\nsoffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard\n\nThen you just have to write a small bootstrapper that calls OOo on the commandline, runs your script, then closes OOo.\n\n",
"This could be not the option for you, but in case it is - you can upload documents to Google Docs and then export in .txt format. Google usually does very nice job for the conversion.\nYou can find relevant APIs here: http://code.google.com/intl/pl/apis/documents/docs/1.0/developers_guide_python.html\nTake a look at login, uploading and exporting sections.\n"
] |
[
3,
2
] |
[] |
[] |
[
"document",
"openoffice.org",
"python",
"word_count"
] |
stackoverflow_0002256881_document_openoffice.org_python_word_count.txt
|
Q:
How to organize Python source code files?
I am developing a Python App Engine app, where I want to split the content of a source code file Models.py into separate files for each model, but I want to put it all in a folder called Models. The problem is that when I do that, my app can't find the classes anymore. What should I do?
This question is not about MVC but another question with the same title is.
A:
Put an empty __init__.py file in the Models directory.
Then, in your app; presumably one level up, you reference modules in the Models directory like this:
import Models
and do something with it like this:
Models.my_model.MyClassName
You can also use the from keyword like this:
from Models import my_model
and reference like this:
my_model.MyClassName
If you only need one method from a module, you could also do this:
from Models.my_model import my_method_name
my_method_name()
Obligatory link to the documentation.
A:
In response to your comment to Adam's answer, regarding having 10 imports for 10 classes, firstly don't forget that there's no need to have one class per module in Python. Modules should be organised by functionality, so you can group related classes in a single file if that makes sense.
If you still wanted to make all the classes importable in one go, you could import them all in the __init__.py file itself using the from submodule import Class syntax, then just import the containing module - import mainmodule and refer to mainmodule.Class1 etc, or even use from mainmodule import Class1, Class2, Class3 to import the classes directly into your namespace and refer to them directly.
A:
Adam Bernier provides a good technical description of how packages work. A great description of how to arrange and ship a project is described in http://jcalderone.livejournal.com/39794.html
|
How to organize Python source code files?
|
I am developing a Python App Engine app, where I want to split the content of a source code file Models.py into separate files for each model, but I want to put it all in a folder called Models. The problem is that when I do that, my app can't find the classes anymore. What should I do?
This question is not about MVC but another question with the same title is.
|
[
"Put an empty __init__.py file in the Models directory.\nThen, in your app; presumably one level up, you reference modules in the Models directory like this:\nimport Models\n\nand do something with it like this:\nModels.my_model.MyClassName\n\nYou can also use the from keyword like this:\nfrom Models import my_model\n\nand reference like this:\nmy_model.MyClassName\n\nIf you only need one method from a module, you could also do this:\nfrom Models.my_model import my_method_name\nmy_method_name()\n\nObligatory link to the documentation.\n",
"In response to your comment to Adam's answer, regarding having 10 imports for 10 classes, firstly don't forget that there's no need to have one class per module in Python. Modules should be organised by functionality, so you can group related classes in a single file if that makes sense.\nIf you still wanted to make all the classes importable in one go, you could import them all in the __init__.py file itself using the from submodule import Class syntax, then just import the containing module - import mainmodule and refer to mainmodule.Class1 etc, or even use from mainmodule import Class1, Class2, Class3 to import the classes directly into your namespace and refer to them directly.\n",
"Adam Bernier provides a good technical description of how packages work. A great description of how to arrange and ship a project is described in http://jcalderone.livejournal.com/39794.html\n"
] |
[
12,
4,
1
] |
[] |
[] |
[
"code_formatting",
"code_structure",
"google_app_engine",
"project_structure",
"python"
] |
stackoverflow_0002256126_code_formatting_code_structure_google_app_engine_project_structure_python.txt
|
Q:
Testing python methods that call class methods
I have a very simple method:
Class Team(models.Model):
def sides(self):
return SideNames.objects.filter(team=self)
SideNames is another model defined in the same file as Team,
Which when I try and test:
self.assertEquals(len(t.sides()), 2)
I get the following error:
return SideNames.objects.filter(team=self)
AttributeError: 'NoneType' object has no attribute 'objects'
but if I change the test to be
self.assertEquals(len(SideNames.objects.filter(team=t)), 2)
Then I don't get the error. What's the difference between calling SideNames.objects.filter from the test itself and calling the actual method?
For reference, here are the 2 classes in their entirety.
class Team(models.Model):
"""The model for a football team."""
class Admin:
pass
def __unicode__(self):
return u'%s' % self.name
def is_player(self, player):
"""Checks to see if 'player' is a member if this team. Returns True if they are, or False otherwise."""
try:
teamPlayer = TeamPlayers.objects.get(player=player, team=self)
return True
except ObjectDoesNotExist:
return False
def sides(self):
"""Return the side names for this team"""
return SideNames.objects.filter(team=self)
def updateSides(self, side_a, side_b):
"""Update the side names"""
names = SideNames.objects.filter(team=self);
a = SideNames.objects.get(name = names[0].name)
a.name = side_a
a.save()
b = SideNames.objects.get(name = names[1].name)
b.name = side_b
b.save()
name = models.CharField("Team Name", max_length=255)
organiser = models.ForeignKey(User)
class SideNames(models.Model):
"""Holds the names of the sides for each team"""
class Admin:
pass
def __unicode__(self):
"""Pretty print the SideNames object"""
return self.name
team = models.ForeignKey(Team)
name = models.CharField(max_length=128)
A:
In the module that defines the test, you're importing the name SideNames from some other module. In the module where that sides method is defined, the name SideNames is not defined or imported.
A:
By any chance, does your test do something like this:
from myapp import models
...
models.SideNames = None
since that's the only explanation I can think of for why SideNames should be None in the context of that method.
As an aside, the method itself is pointless, as backwards relations are automatically provided by Django, so you could just call t.sidenames_set.all().
|
Testing python methods that call class methods
|
I have a very simple method:
Class Team(models.Model):
def sides(self):
return SideNames.objects.filter(team=self)
SideNames is another model defined in the same file as Team,
Which when I try and test:
self.assertEquals(len(t.sides()), 2)
I get the following error:
return SideNames.objects.filter(team=self)
AttributeError: 'NoneType' object has no attribute 'objects'
but if I change the test to be
self.assertEquals(len(SideNames.objects.filter(team=t)), 2)
Then I don't get the error. What's the difference between calling SideNames.objects.filter from the test itself and calling the actual method?
For reference, here are the 2 classes in their entirety.
class Team(models.Model):
"""The model for a football team."""
class Admin:
pass
def __unicode__(self):
return u'%s' % self.name
def is_player(self, player):
"""Checks to see if 'player' is a member if this team. Returns True if they are, or False otherwise."""
try:
teamPlayer = TeamPlayers.objects.get(player=player, team=self)
return True
except ObjectDoesNotExist:
return False
def sides(self):
"""Return the side names for this team"""
return SideNames.objects.filter(team=self)
def updateSides(self, side_a, side_b):
"""Update the side names"""
names = SideNames.objects.filter(team=self);
a = SideNames.objects.get(name = names[0].name)
a.name = side_a
a.save()
b = SideNames.objects.get(name = names[1].name)
b.name = side_b
b.save()
name = models.CharField("Team Name", max_length=255)
organiser = models.ForeignKey(User)
class SideNames(models.Model):
"""Holds the names of the sides for each team"""
class Admin:
pass
def __unicode__(self):
"""Pretty print the SideNames object"""
return self.name
team = models.ForeignKey(Team)
name = models.CharField(max_length=128)
|
[
"In the module that defines the test, you're importing the name SideNames from some other module. In the module where that sides method is defined, the name SideNames is not defined or imported.\n",
"By any chance, does your test do something like this:\nfrom myapp import models\n\n...\n\nmodels.SideNames = None\n\nsince that's the only explanation I can think of for why SideNames should be None in the context of that method.\nAs an aside, the method itself is pointless, as backwards relations are automatically provided by Django, so you could just call t.sidenames_set.all().\n"
] |
[
1,
1
] |
[] |
[] |
[
"python",
"python_unittest",
"unit_testing"
] |
stackoverflow_0002256063_python_python_unittest_unit_testing.txt
|
Q:
How do I do os.getpid() in C++?
newb here. I am trying to make a c++ program that will read from a named pipe created by python. My problem is, the named pipe created by python uses os.getpid() as part of the pipe name. when i try calling the pipe from c++, i use getpid(). i am not getting the same value from c++. is there a method equivalent in c++ for os.getpid?
thanks!
edit:
sorry, i am actually using os.getpid() to get the session id via ProcessIDtoSessionID(). i then use the session id as part of the pipe name
A:
You don't get same proccess IDs because your python program and c++ programs are run in different proccesses thus having different process IDs. So generally use a different logic to name your fifo files.
A:
You won't get the same value if you're running as a separate process as each process has their own process ID. Find some other way to identify the pipe.
A:
The standard library does not give you anything other than files. You will need to use some other OS specific API.
A:
You cannot easily retrieve the Python interpreter's PID from your C++ program.
Either assign the named pipe a constant name, or if you really need multiple pipes of the same Python program, create a temporary file to which the Python programs write their PIDs (use file locking!) - then you can read the PIDs from the C++ program.
|
How do I do os.getpid() in C++?
|
newb here. I am trying to make a c++ program that will read from a named pipe created by python. My problem is, the named pipe created by python uses os.getpid() as part of the pipe name. when i try calling the pipe from c++, i use getpid(). i am not getting the same value from c++. is there a method equivalent in c++ for os.getpid?
thanks!
edit:
sorry, i am actually using os.getpid() to get the session id via ProcessIDtoSessionID(). i then use the session id as part of the pipe name
|
[
"You don't get same proccess IDs because your python program and c++ programs are run in different proccesses thus having different process IDs. So generally use a different logic to name your fifo files.\n",
"You won't get the same value if you're running as a separate process as each process has their own process ID. Find some other way to identify the pipe.\n",
"The standard library does not give you anything other than files. You will need to use some other OS specific API.\n",
"You cannot easily retrieve the Python interpreter's PID from your C++ program.\nEither assign the named pipe a constant name, or if you really need multiple pipes of the same Python program, create a temporary file to which the Python programs write their PIDs (use file locking!) - then you can read the PIDs from the C++ program.\n"
] |
[
4,
2,
0,
0
] |
[] |
[] |
[
"c++",
"python"
] |
stackoverflow_0002257415_c++_python.txt
|
Q:
Django version selection
Greetings,
I am currently working on a long term project that uses Django 1.1.1, and we are planning to release it around march of 2010.
Now while surfing I came upon to this article which says the planned release date of Django 1.2.0 is March 9, 2010.
Now I am a bit confused. If I should continue developing under 1.1.1 or start developing using 1.2.0 beta.
A:
I'd say only develop for the latest version if there is a specific feature you need/like. Read up on it so you know of course what is in store.
1.0 onwards. I've found swapping django versions to be relatively trouble free. At any stage all you need to do is swap symlinks on a source tree on your test server. and of course running that thorough unit test suite you've written will show up any version skew bugs.
A:
The upgrade path is not difficult. I would familiarize yourself with the differences and avoid deprecations, but continue on the battle tested 1.1 branch. While you should never ever trust software release dates, you also probably don't want to bet your farm on a brand new branch with features you clearly don't need yet. You've got plenty to do to release in a month. Upgrade when you have time. If your release was scheduled for June you might consider it, but for now stick with stability. That's mho.
A:
Part of our current application under development is being put into production now, but we hope to use Django 1.2 final. Our strategy is to write code, test and deploy using Django 1.1.1, but also test using virtualenv. There's really no reason not to test your code under 1.2 whatever your deployment decision because you'll want it eventually to be compatible with 1.2.
virtualenv makes the whole process painless and is the key to quickly switching between environments. It's incredibly easy to set up:
easy_install virtualenv
virtualenv django12
cd django12
source bin/activate
Then download and install Django 1.2 in the virtual environment and run your tests. I run the development server in virtualenv on port 8081, so I can have both servers -- using the same application code -- running at the same time, ports 8080, 8081.
In our case we had to remove one import and wrap a few others with try/except conditions. I had to write a dummy csrf_token template tag for CSRF to work -- the Django developers have informed me they'll include a dummy tag in 1.2 final. We also upgraded the South migrations tool to 0.7-pre, as the current release doesn't support Django 1.2.
Bottom line: Regardless of your deployment decision, a case can be made for testing both versions of Django if at all possible.
|
Django version selection
|
Greetings,
I am currently working on a long term project that uses Django 1.1.1, and we are planning to release it around march of 2010.
Now while surfing I came upon to this article which says the planned release date of Django 1.2.0 is March 9, 2010.
Now I am a bit confused. If I should continue developing under 1.1.1 or start developing using 1.2.0 beta.
|
[
"I'd say only develop for the latest version if there is a specific feature you need/like. Read up on it so you know of course what is in store. \n1.0 onwards. I've found swapping django versions to be relatively trouble free. At any stage all you need to do is swap symlinks on a source tree on your test server. and of course running that thorough unit test suite you've written will show up any version skew bugs.\n",
"The upgrade path is not difficult. I would familiarize yourself with the differences and avoid deprecations, but continue on the battle tested 1.1 branch. While you should never ever trust software release dates, you also probably don't want to bet your farm on a brand new branch with features you clearly don't need yet. You've got plenty to do to release in a month. Upgrade when you have time. If your release was scheduled for June you might consider it, but for now stick with stability. That's mho. \n",
"Part of our current application under development is being put into production now, but we hope to use Django 1.2 final. Our strategy is to write code, test and deploy using Django 1.1.1, but also test using virtualenv. There's really no reason not to test your code under 1.2 whatever your deployment decision because you'll want it eventually to be compatible with 1.2.\nvirtualenv makes the whole process painless and is the key to quickly switching between environments. It's incredibly easy to set up:\neasy_install virtualenv\nvirtualenv django12\ncd django12\nsource bin/activate\n\nThen download and install Django 1.2 in the virtual environment and run your tests. I run the development server in virtualenv on port 8081, so I can have both servers -- using the same application code -- running at the same time, ports 8080, 8081.\nIn our case we had to remove one import and wrap a few others with try/except conditions. I had to write a dummy csrf_token template tag for CSRF to work -- the Django developers have informed me they'll include a dummy tag in 1.2 final. We also upgraded the South migrations tool to 0.7-pre, as the current release doesn't support Django 1.2.\nBottom line: Regardless of your deployment decision, a case can be made for testing both versions of Django if at all possible.\n"
] |
[
4,
1,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002251696_django_python.txt
|
Q:
How to parse a file line by line, char by char in Python?
How do you read a character by character from a source file in python until end of line and how do you check for end of line in python so that you can then start reading from the next line and finally how do we check for the end of file condition to finish the read in the entire file.
Thank You:).
A:
You can simply iterate over each line in Python. Use the universal end-of-line mode if you want Python to care about Windows/UNIX/Mac line ends automatically:
with open("mytextfile.txt", "rtU") as f:
for line in f:
# Now you have one line of text in the variable "line" and can
# iterate over its characters like so:
for ch in line:
... # do something here
You won't have to care about EOL/EOF yourself in this example code.
Note that the line variable includes line endings. If you don't want them, you could use line = line.rstrip(), for example.
A:
You don't have to worry about line and file endings, just do
file = open('yourfile', 'r')
for line in file.readlines():
for c in line:
# do sth.
|
How to parse a file line by line, char by char in Python?
|
How do you read a character by character from a source file in python until end of line and how do you check for end of line in python so that you can then start reading from the next line and finally how do we check for the end of file condition to finish the read in the entire file.
Thank You:).
|
[
"You can simply iterate over each line in Python. Use the universal end-of-line mode if you want Python to care about Windows/UNIX/Mac line ends automatically:\nwith open(\"mytextfile.txt\", \"rtU\") as f:\n for line in f:\n # Now you have one line of text in the variable \"line\" and can\n # iterate over its characters like so:\n for ch in line:\n ... # do something here\n\nYou won't have to care about EOL/EOF yourself in this example code.\nNote that the line variable includes line endings. If you don't want them, you could use line = line.rstrip(), for example.\n",
"You don't have to worry about line and file endings, just do\nfile = open('yourfile', 'r')\nfor line in file.readlines():\n for c in line:\n # do sth.\n\n"
] |
[
8,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002257665_python.txt
|
Q:
Executing server-side Unix scripts asynchronously
We have a collection of Unix scripts (and/or Python modules) that each perform a long running task. I would like to provide a web interface for them that does the following:
Asks for relevant data to pass into scripts.
Allows for starting/stopping/killing them.
Allows for monitoring the progress and/or other information provided by the scripts.
Possibly some kind of logging (although the scripts already do logging).
I do know how to write a server that does this (e.g. by using Python's built-in HTTP server/JSON), but doing this properly is non-trivial and I do not want to reinvent the wheel.
Are there any existing solutions that allow for maintaining asynchronous server-side tasks?
A:
Django is great for writing web applications, and the subprocess module (subprocess.Popen en .communicate()) is great for executing shell scripts. You can give it a stdin,stdout and stderr stream for communication if you want.
A:
Answering my own question, I recently saw the announcement of Celery 1.0, which seems to do much of what I am looking for.
A:
I would use SGE, but I think it could be overkill for your need...
|
Executing server-side Unix scripts asynchronously
|
We have a collection of Unix scripts (and/or Python modules) that each perform a long running task. I would like to provide a web interface for them that does the following:
Asks for relevant data to pass into scripts.
Allows for starting/stopping/killing them.
Allows for monitoring the progress and/or other information provided by the scripts.
Possibly some kind of logging (although the scripts already do logging).
I do know how to write a server that does this (e.g. by using Python's built-in HTTP server/JSON), but doing this properly is non-trivial and I do not want to reinvent the wheel.
Are there any existing solutions that allow for maintaining asynchronous server-side tasks?
|
[
"Django is great for writing web applications, and the subprocess module (subprocess.Popen en .communicate()) is great for executing shell scripts. You can give it a stdin,stdout and stderr stream for communication if you want.\n",
"Answering my own question, I recently saw the announcement of Celery 1.0, which seems to do much of what I am looking for.\n",
"I would use SGE, but I think it could be overkill for your need...\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"asynchronous",
"http",
"python",
"unix"
] |
stackoverflow_0001897748_asynchronous_http_python_unix.txt
|
Q:
Review Website In Python. Is django right for this?
Basically, I misread this but would still really appreciate some assurance. I recently came across the django tutorial (http://djangotutorial.com) and have fell in love with the framework. I have a website that is simply ran on wordpress and a simple plugin at the moment at http://runningshoesreview.org.
I've been wanting to do many things, such as allow users to add their own reviews, talk to eachother, comment, etc. Naturally, I see django as a perfect fit until I came across this:
"It’s not intended to be a public interface to data"
It's was referencing the django admin section, I think. Can someone tell me if django is what I need for this task?
Thanks,
Cody
A:
The Django admin is for administrator use only.
You could use this for moderation and general admin tasks.
You would create a different interface using django for your users.
Django would be a great framework for your app. I'm developing a service with it now.
There are other great frameworks out there too. CakePHP & Code Igniter for PHP, and Ruby on Rails. There is no one best framework but people tend to pick one and stick with it, so use the one that uses the language you like best and offers the features you need/want.
A:
Django provides an automatically generated admin interface for your models. For your blog you can use this admin interface to create new posts, moderate comments and so on.
However, you should not allow your users to access this interface for security reasons, so when you want normal users to create comments, you should simple provide a form for them to enter the comment (see the form handling section in the documentation).
And yes, django is suited great for blogs and things like that. However you should keep in mind that django is a framework for creating web applications and not a ready-made web application. However, if you are a developer, you will like the tools django offers you and you will be able to create individual web applications quickly...
Maybe you should also take a look at some django examples (I think there are also some blog examples) and see if you understand the source. Here is for example the source of the blog running at djangoproject.com
A:
Read the first few chapters of The Django Book to give you an idea of how Django works - won't take you long and will open your eyes to the possibilities.
A:
Django is a general-purpose framework and is perfectly fine for your intended uses, although probably an overkill, since adding these features to WordPress is likely simpler, especially if your host doesn't support Python and you'd have to move hosts.
As for the comment you quotes, it simply means that you shouldn't let normal users muck around with admin controls.
A:
The django admin area is a backend, an area you have to login first. So it's not the typical website approach for a public review site.
After a user logs in you can restrict the database access (=model editing) to certain parts, but you can't avoid people DROPing the whole content of smth. they have access to.
There is nothing in the backend that lets you setup some kind of website feeling (navigation structure, e.g.).
Take a CMS with lots of plugins available if it's really just about chat, comments and votes. They all should allow you to add the thin layer of development ("glue") where needed, be they Typo3, Drupal, Joomla, even Wordpress.
Take a look at http://djangosites.org - some of them even offer complete source code...
|
Review Website In Python. Is django right for this?
|
Basically, I misread this but would still really appreciate some assurance. I recently came across the django tutorial (http://djangotutorial.com) and have fell in love with the framework. I have a website that is simply ran on wordpress and a simple plugin at the moment at http://runningshoesreview.org.
I've been wanting to do many things, such as allow users to add their own reviews, talk to eachother, comment, etc. Naturally, I see django as a perfect fit until I came across this:
"It’s not intended to be a public interface to data"
It's was referencing the django admin section, I think. Can someone tell me if django is what I need for this task?
Thanks,
Cody
|
[
"The Django admin is for administrator use only.\nYou could use this for moderation and general admin tasks.\nYou would create a different interface using django for your users.\nDjango would be a great framework for your app. I'm developing a service with it now.\nThere are other great frameworks out there too. CakePHP & Code Igniter for PHP, and Ruby on Rails. There is no one best framework but people tend to pick one and stick with it, so use the one that uses the language you like best and offers the features you need/want.\n",
"Django provides an automatically generated admin interface for your models. For your blog you can use this admin interface to create new posts, moderate comments and so on.\nHowever, you should not allow your users to access this interface for security reasons, so when you want normal users to create comments, you should simple provide a form for them to enter the comment (see the form handling section in the documentation).\nAnd yes, django is suited great for blogs and things like that. However you should keep in mind that django is a framework for creating web applications and not a ready-made web application. However, if you are a developer, you will like the tools django offers you and you will be able to create individual web applications quickly...\nMaybe you should also take a look at some django examples (I think there are also some blog examples) and see if you understand the source. Here is for example the source of the blog running at djangoproject.com\n",
"Read the first few chapters of The Django Book to give you an idea of how Django works - won't take you long and will open your eyes to the possibilities.\n",
"Django is a general-purpose framework and is perfectly fine for your intended uses, although probably an overkill, since adding these features to WordPress is likely simpler, especially if your host doesn't support Python and you'd have to move hosts.\nAs for the comment you quotes, it simply means that you shouldn't let normal users muck around with admin controls.\n",
"The django admin area is a backend, an area you have to login first. So it's not the typical website approach for a public review site.\nAfter a user logs in you can restrict the database access (=model editing) to certain parts, but you can't avoid people DROPing the whole content of smth. they have access to.\nThere is nothing in the backend that lets you setup some kind of website feeling (navigation structure, e.g.).\nTake a CMS with lots of plugins available if it's really just about chat, comments and votes. They all should allow you to add the thin layer of development (\"glue\") where needed, be they Typo3, Drupal, Joomla, even Wordpress.\nTake a look at http://djangosites.org - some of them even offer complete source code...\n"
] |
[
3,
1,
1,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002256892_django_python.txt
|
Q:
Python Shell, Logging Commands for Easy Re-Execution
Say I do something like this in a python shell for my Django app:
>>>from myapp.models import User
>>>user = User.objects.get(pk=5)
>>>groups = user.groups.all()
What I'd like to do is stash these 3 commands somehow without leaving the shell. The goal being I can quickly restore a similar environment if I restart the shell session later.
A:
The Django shell will use IPython if available, which supports a persistent history.
Also, writing throwaway scripts is not difficult.
A:
So thanks to Ignacio, with IPython installed:
>>>from myapp.models import User
>>>user = User.objects.get(pk=5)
>>>groups = user.groups.all()
>>>#Ipython Tricks Follow
>>>hist #shows you lines in your history
>>>edit 1:3 # Edit n:m lines above in text editor. I save it as ~/testscript
>>>run ~/testscript
Groovy!
A:
Koobz, since you've just become a recent convert to ipython, there's a cool hack I use for automatically importing all my application models in interactive mode:
#!/bin/env python
# based on http://proteus-tech.com/blog/code-garden/bpython-django/
try:
from django.core.management import setup_environ
import settings
setup_environ(settings)
print "imported django settings"
try:
exec_strs = ["from %s.models import *"%apps for apps in settings.INSTALLED_APPS if apps not in ['django_extensions']]
for x in exec_strs:
try:
exec(x)
except:
print 'not imported for %s' %x
print 'imported django models'
except:
pass
except:
pass
Then I just alias: ipython -i $HOME/.pythonrc
|
Python Shell, Logging Commands for Easy Re-Execution
|
Say I do something like this in a python shell for my Django app:
>>>from myapp.models import User
>>>user = User.objects.get(pk=5)
>>>groups = user.groups.all()
What I'd like to do is stash these 3 commands somehow without leaving the shell. The goal being I can quickly restore a similar environment if I restart the shell session later.
|
[
"The Django shell will use IPython if available, which supports a persistent history.\nAlso, writing throwaway scripts is not difficult.\n",
"So thanks to Ignacio, with IPython installed:\n>>>from myapp.models import User\n>>>user = User.objects.get(pk=5)\n>>>groups = user.groups.all()\n>>>#Ipython Tricks Follow\n>>>hist #shows you lines in your history\n>>>edit 1:3 # Edit n:m lines above in text editor. I save it as ~/testscript\n>>>run ~/testscript\n\nGroovy!\n",
"Koobz, since you've just become a recent convert to ipython, there's a cool hack I use for automatically importing all my application models in interactive mode:\n#!/bin/env python\n# based on http://proteus-tech.com/blog/code-garden/bpython-django/\ntry:\n from django.core.management import setup_environ\n import settings\n setup_environ(settings)\n print \"imported django settings\"\n try:\n exec_strs = [\"from %s.models import *\"%apps for apps in settings.INSTALLED_APPS if apps not in ['django_extensions']]\n for x in exec_strs:\n try:\n exec(x)\n except:\n print 'not imported for %s' %x\n print 'imported django models'\n except:\n pass\nexcept:\n pass\n\nThen I just alias: ipython -i $HOME/.pythonrc\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"django",
"python",
"shell"
] |
stackoverflow_0002242288_django_python_shell.txt
|
Q:
Script access to WebGoat urls?
I've been solving a couple of the WebGoat exampels for a uni-lab thing. In one of the exercises I tried to use a python script with urllib2 to do automated "tests" so I didnt manually have to used ascii(substr(first_name,3,1)) > 97 etc.
But I seem to get the same page eventhough I try different urls when using an urllib2 script aka f2, f3 and f4.html is all the basic first page and not the same page as if you access it in a browser:
import urllib2
import urllib
import cookielib
import sys
myjar = cookielib.FileCookieJar("cookies.txt");
cookieHandler = urllib2.HTTPCookieProcessor(myjar)
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
tlurl="http://localhost:8081/webgoat/attack"
password_mgr.add_password(None,tlurl,user="guest",passwd="guest")
authhandler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(cookieHandler, authhandler)
data = [('Connection','keep-alive'),('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; da; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7')]
def write_f_to_f(fname,f):
f1 = open(fname,"w")
f1.write(f.read())
f1.close()
def gen_req(url,referer=None):
req = urllib2.Request(url)
print "url: %s"%url
mydata = data
if referer != None:
mydata.append( ('Referer',referer) )
[ req.add_header(k,v) for k,v in mydata ]
return req
sys.stdout.flush()
url = "http://localhost:8081/webgoat/attack"
req = gen_req(url)
f = opener.open(req)
write_f_to_f("f1.html",f)
f.close()
params = urllib.urlencode({'start':'Start WebGoat'})
qs = urllib.urlencode( {'Screen':107, 'menu':1200 } )
url = "http://localhost:8081/webgoat/attack"
req = gen_req(url,url)
f = opener.open(req, params)
write_f_to_f("f2.html",f)
f.close()
ourl = url
url = "http://localhost:8081/webgoat/attack?%s"%qs
req = gen_req(url,ourl)
f = opener.open(req)
write_f_to_f("f3.html",f)
f.close()
ourl = url
url = "http://localhost:8081/webgoat/attack?%s"%qs
req = gen_req(url,ourl)
f = opener.open(req)
write_f_to_f("f4.html",f)
f.close()
NB: I did the answer to the assignment "the hard way" and handed it in. Now I'm just curious what kind of mechanism is stopping the urllib script from accessing the content
I tried accessing my local tomcat with webgoat and the webgoat console says:
Sat Feb 13 12:31:14 CET 2010 | 127.0.0.1:127.0.0.1 | org.owasp.webgoat.session.ErrorScreen | [Screen=107,menu=1200]
errorscreen createContent Error:null message:Invalid screen requested. Try: http://localhost/WebGoat/attack
- WebGoat: Sat Feb 13 12:31:14 CET 2010 | 127.0.0.1:127.0.0.1 | org.owasp.webgoat.session.ErrorScreen | [Screen=107,menu=1200]
Sat Feb 13 12:31:14 CET 2010 | 127.0.0.1:127.0.0.1 | org.owasp.webgoat.session.ErrorScreen | [Screen=107,menu=1200]
It doesnt really help me as far as I can tell.
A:
Is the user agent being checked? I've had to specify a user agent for a typical browser before to get past checks like that. You have one listed in your "data" variable but it looks like you don't actually apply it in any way.
A:
Woohoo!
Found out
The ID of the page I'm trying to find is regenerated on every session. So i need to look at the data returned before choosing a screenId:
import urllib2
import urllib
import cookielib
import re
def write_f_to_f(fname,f):
f1 = open(fname,"w")
f1.write(f.read())
f1.close()
def gen_req(url,referer=None):
req = urllib2.Request(url)
return req
myjar = cookielib.FileCookieJar("cookies.txt");
cookieHandler = urllib2.HTTPCookieProcessor(myjar)
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
tlurl="http://127.0.0.1:8081/webgoat/attack"
password_mgr.add_password(None,tlurl,user="guest",passwd="guest")
find = "Blind Numeric."
authhandler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(authhandler,cookieHandler)
url = "http://127.0.0.1:8081/webgoat/attack"
req = gen_req(url,url)
f = opener.open(req)# Setup session and login.
params = urllib.urlencode({'start':'Start WebGoat'})
url = "http://127.0.0.1:8081/webgoat/attack"
req = gen_req(url,url)
f = opener.open(req,params) # Submit the "Start" form
dat = f.read() # Get the menu html from the firstpage.
f.close()
m = re.search("attack\?Screen=(\d+).*%s"%find,dat) # Try to find screen id for what i want
if not m is None:
scr= m.group(1)
qs = urllib.urlencode( {'Screen':scr, 'menu':1200 } )
ourl = url
url = "http://127.0.0.1:8081/webgoat/attack?%s"%qs
req = gen_req(url,ourl)
f = opener.open(req)
write_f_to_f("f4.html",f)
f.close()
print "Found the page and saved it to f4.html"
else:
print "Didnt find screen id for %s"%find
|
Script access to WebGoat urls?
|
I've been solving a couple of the WebGoat exampels for a uni-lab thing. In one of the exercises I tried to use a python script with urllib2 to do automated "tests" so I didnt manually have to used ascii(substr(first_name,3,1)) > 97 etc.
But I seem to get the same page eventhough I try different urls when using an urllib2 script aka f2, f3 and f4.html is all the basic first page and not the same page as if you access it in a browser:
import urllib2
import urllib
import cookielib
import sys
myjar = cookielib.FileCookieJar("cookies.txt");
cookieHandler = urllib2.HTTPCookieProcessor(myjar)
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
tlurl="http://localhost:8081/webgoat/attack"
password_mgr.add_password(None,tlurl,user="guest",passwd="guest")
authhandler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(cookieHandler, authhandler)
data = [('Connection','keep-alive'),('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; da; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7')]
def write_f_to_f(fname,f):
f1 = open(fname,"w")
f1.write(f.read())
f1.close()
def gen_req(url,referer=None):
req = urllib2.Request(url)
print "url: %s"%url
mydata = data
if referer != None:
mydata.append( ('Referer',referer) )
[ req.add_header(k,v) for k,v in mydata ]
return req
sys.stdout.flush()
url = "http://localhost:8081/webgoat/attack"
req = gen_req(url)
f = opener.open(req)
write_f_to_f("f1.html",f)
f.close()
params = urllib.urlencode({'start':'Start WebGoat'})
qs = urllib.urlencode( {'Screen':107, 'menu':1200 } )
url = "http://localhost:8081/webgoat/attack"
req = gen_req(url,url)
f = opener.open(req, params)
write_f_to_f("f2.html",f)
f.close()
ourl = url
url = "http://localhost:8081/webgoat/attack?%s"%qs
req = gen_req(url,ourl)
f = opener.open(req)
write_f_to_f("f3.html",f)
f.close()
ourl = url
url = "http://localhost:8081/webgoat/attack?%s"%qs
req = gen_req(url,ourl)
f = opener.open(req)
write_f_to_f("f4.html",f)
f.close()
NB: I did the answer to the assignment "the hard way" and handed it in. Now I'm just curious what kind of mechanism is stopping the urllib script from accessing the content
I tried accessing my local tomcat with webgoat and the webgoat console says:
Sat Feb 13 12:31:14 CET 2010 | 127.0.0.1:127.0.0.1 | org.owasp.webgoat.session.ErrorScreen | [Screen=107,menu=1200]
errorscreen createContent Error:null message:Invalid screen requested. Try: http://localhost/WebGoat/attack
- WebGoat: Sat Feb 13 12:31:14 CET 2010 | 127.0.0.1:127.0.0.1 | org.owasp.webgoat.session.ErrorScreen | [Screen=107,menu=1200]
Sat Feb 13 12:31:14 CET 2010 | 127.0.0.1:127.0.0.1 | org.owasp.webgoat.session.ErrorScreen | [Screen=107,menu=1200]
It doesnt really help me as far as I can tell.
|
[
"Is the user agent being checked? I've had to specify a user agent for a typical browser before to get past checks like that. You have one listed in your \"data\" variable but it looks like you don't actually apply it in any way.\n",
"Woohoo! \nFound out\nThe ID of the page I'm trying to find is regenerated on every session. So i need to look at the data returned before choosing a screenId:\nimport urllib2 \nimport urllib\nimport cookielib\nimport re\n\ndef write_f_to_f(fname,f):\n f1 = open(fname,\"w\")\n f1.write(f.read())\n f1.close()\n\ndef gen_req(url,referer=None):\n req = urllib2.Request(url)\n return req\n\n\n\nmyjar = cookielib.FileCookieJar(\"cookies.txt\");\ncookieHandler = urllib2.HTTPCookieProcessor(myjar)\n\npassword_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()\ntlurl=\"http://127.0.0.1:8081/webgoat/attack\"\n\npassword_mgr.add_password(None,tlurl,user=\"guest\",passwd=\"guest\")\nfind = \"Blind Numeric.\"\n\nauthhandler = urllib2.HTTPBasicAuthHandler(password_mgr)\nopener = urllib2.build_opener(authhandler,cookieHandler)\n\nurl = \"http://127.0.0.1:8081/webgoat/attack\"\nreq = gen_req(url,url)\nf = opener.open(req)# Setup session and login.\n\nparams = urllib.urlencode({'start':'Start WebGoat'})\nurl = \"http://127.0.0.1:8081/webgoat/attack\"\nreq = gen_req(url,url)\nf = opener.open(req,params) # Submit the \"Start\" form\ndat = f.read() # Get the menu html from the firstpage.\nf.close()\n\n\nm = re.search(\"attack\\?Screen=(\\d+).*%s\"%find,dat) # Try to find screen id for what i want\nif not m is None:\n scr= m.group(1)\n qs = urllib.urlencode( {'Screen':scr, 'menu':1200 } )\n ourl = url\n url = \"http://127.0.0.1:8081/webgoat/attack?%s\"%qs\n req = gen_req(url,ourl)\n f = opener.open(req)\n write_f_to_f(\"f4.html\",f)\n f.close()\n print \"Found the page and saved it to f4.html\"\nelse:\n print \"Didnt find screen id for %s\"%find\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"security"
] |
stackoverflow_0002255721_python_security.txt
|
Q:
How to copy data from one Tkinter Text widget to another?
from Tkinter import *
root = Tk()
root.title("Whois Tool")
text = Text()
text1 = Text()
text1.config(width=15, height=1)
text1.pack()
def button1():
text.insert(END, text1)
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.pack()
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=60, height=15)
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
root.mainloop()
How can I add the data from a text widget to another text widget?
For example, I'm trying to insert the data in text1 to text, but it is not working.
A:
You are trying to insert a Text reference at the end of another Text widget (does not make much sense), but what you actually want to do is to copy the contents of a Text widget to another:
def button1():
text.insert(INSERT, text1.get("1.0", "end-1c"))
Not an intuitive way to do it in my opinion. "1.0" means line 1, column 0. Yes, the lines are 1-indexed and the columns are 0-indexed.
Note that you may not want to import the entire Tkinter package, using from Tkinter import *. It will likely lead to confusion down the road. I would recommend using:
import Tkinter
text = Tkinter.Text()
Another option is:
import Tkinter as tk
text = tk.Text()
You can choose a short name (like "tk") of your choice. Regardless, you should stick to one import mechanism for the library.
|
How to copy data from one Tkinter Text widget to another?
|
from Tkinter import *
root = Tk()
root.title("Whois Tool")
text = Text()
text1 = Text()
text1.config(width=15, height=1)
text1.pack()
def button1():
text.insert(END, text1)
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.pack()
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=60, height=15)
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
root.mainloop()
How can I add the data from a text widget to another text widget?
For example, I'm trying to insert the data in text1 to text, but it is not working.
|
[
"You are trying to insert a Text reference at the end of another Text widget (does not make much sense), but what you actually want to do is to copy the contents of a Text widget to another:\ndef button1():\n text.insert(INSERT, text1.get(\"1.0\", \"end-1c\"))\n\nNot an intuitive way to do it in my opinion. \"1.0\" means line 1, column 0. Yes, the lines are 1-indexed and the columns are 0-indexed.\n\nNote that you may not want to import the entire Tkinter package, using from Tkinter import *. It will likely lead to confusion down the road. I would recommend using:\nimport Tkinter\ntext = Tkinter.Text()\n\nAnother option is:\nimport Tkinter as tk\ntext = tk.Text()\n\nYou can choose a short name (like \"tk\") of your choice. Regardless, you should stick to one import mechanism for the library.\n"
] |
[
5
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0002258097_python_tkinter.txt
|
Q:
Why do I get "expected an indented block" when I try to run my Python script?
I have an error which says "expected an indented block"
Could you please guide me on how to deal with this error. Thank you:)
Code example:
for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch)
A:
Editing answer to match the code example.
for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch)
is just not valid Python.
First, readability count. Your code is hard to read and so, is hard to debug. What's "ch" and "f" ? What's more, you can do one liner in Python but it's not recommended, so put the for in a separate line. Then indent.
for chunk in file:
( translatedToken = english_hindi_dict[chunk] ) if (chunk in english_hindi_dict) else (translatedToken = chunk)
Now we can see what's wrong. You make variable assignments in a conditional statement. This is not allowed in Python. I'm guessing you have a C/C++ background and are used to do that. In Python you can't, to prevent you from writing obfuscated code. So you end up with:
for chunk in file:
translatedToken = english_hindi_dict[chunk] if chunk in english_hindi_dict else chunk
This piece of code should work, provided you use Python 2.5+. But the ternary operator is not available in older Python version yet. Let's make it a bit friendlier:
for chunk in file:
translatedToken = chunk
if chunk in english_hindi_dict:
translatedToken = english_hindi_dict[chunk]
You may argue that it's longer to write, and you'd be right. But you spend more time reading code than writing it, so it make sense to make it easy to read. Or course, once you have the Python grip, you will try to make it work in a more pythonic way. Ever heard of EAFTP?
for chunk in file:
try:
translatedToken = english_hindi_dict[chunk]
except KeyError:
translatedToken = chunk
But Python is full of surprises, and you'll learn that most of these classic use cases have been already taken care of. The standard library often provides an elegant and short yet readable solution:
for chunk in file:
translatedToken = english_hindi_dict.get(chunk, chunk)
As a conclusion: don't try to write Python as you wrote C, or Java as you would write Perl. Other tool, other style.
To fix this problem, fire your editor "search and replace" feature and make a huge "replace all" to change all the tabs by 4 spaces, or the contrary. Then indent all your blocks, and finally align all the instructions in the same block.
Funny that didn't appear before on SO. After all, it's true it's not that obvious.
In Python, you separate blocks using spaces or tabs, not "{".
So any time you go down a block (a function, a loop, a class, etc), you have to indent your code. This is not just good practice, this is mandatory. Your program will crash if you don't.
Now, most of the time, you get this error because you did indent, but used tabs and spaces. In a Python program, you should use either tabs or spaces, but never both in the same files.
E.G:
if (age > 18)
{
printf("You can vote")
}
Becomes:
if age > 18:
print("You can vote")
In most languages, you could do:
if (age > 18)
{
printf("You can vote")
}
In Python you can't:
if age > 18:
print("You can vote")
raises an exception. What's more, you must align all the instruction of the same block, so:
if age > 18:
print("You can vote")
print("How cool is that ?")
Is fine, but:
if age > 18:
print("You can vote")
print("How cool is that ?")
raises an exception.
Eventually, you can't mix tab and spaces in the same block. So:
if age > 18:
print("You can vote")
print("How cool is that ?")
looks good, but will raises an exception. To avoid this problem, just stick to tabs or spaces. The PEP8, the text one most use as a reference for coding style recommend using 4 spaces.
Most editors have a global "search and replace" feature that let you fix any problem you can have with that. Some like Geany or Ulipad even have a "replace all tabs with spaces" feature.
A:
You are probably mixing tabs with spaces. It looks indented but it really isn't.
Your code gives me a different error:
for ch in f: \
( translatedToken = english_hindi_dict[ch] ) \
if (ch in english_hindi_dict) else (translatedToken = ch)
↑
SyntaxError: invalid syntax
Maybe you meant:
for ch in f:
if ch in english_hindi_dict:
translatedToken = english_hindi_dict[ch]
else:
translatedToken = ch
Maybe you meant instead:
for ch in f:
translatedToken = english_hindi_dict[ch] if ch in english_hindi_dict else ch
Both should run just fine, and I expect the second to be faster than the former
They both can be optimized into translated = str(english_hindi_dict.get(ch, ch) for ch in f) but that's not the point of the question.
A:
Python is a language that relies heavily on indentation to decide program structure unlike C and some other languages that use braces for this purpose.
When you have a statement like:
if true:
pass
it will complain because there's no indented statement for the if. You would need to fix it to be:
if true:
pass
That sounds like the sort of error you have, though it may have been more obvious had you posted the actual code. When stating a problem, it's a good idea to give the code and explain what the expected behaviour was and how that related to the actual behaviour. You'll make the lives of those trying to help you out that much easier :-)
Also keep in mind that you may get this problem even if your code looks right. Mixing spaces and tabs in your source code can often lead to this.
A:
IndentationErrors can be caused by a lot if different things. Off the top of my head:
Forgetting to indent at all.
Python uses indents to delimit syntactic blocks. For example:
if will_is_awesome:
print "You're right"
else:
print "You lie!"
You will get an IndentationError: expected an indented block error if you forget to indent. For example:
if will_is_awesome:
print "You're right"
else:
print "You lie!"
Commenting out an indented block.
For example:
if light_is_green:
go_now()
else:
# go_anyway()
do_something_else()
This will produce an IndentationError: expected an indented block because the comment makes the line after else: look empty to the parser. Adding a pass statement will fix the problem. Eg:
if light_is_green:
go_now()
else:
# go_anyway()
pass
do_something_else()
Mixed tabs and spaces in indents.
Tab stops can vary between different machines and editors. If you mix tabs and spaces just right, you can get your error, but it usually produces IndentationError: unindent does not match any outer indentation level, so it's unlikely to be your problem. It's worth knowing anyway. It is advisable to never use tabs in Python code.
A:
Python uses indentation (spaces/tabs in front of your code lines) to indicate where a block of code starts and ends, relative to what python statement precedes it.
So, taking PHP for example:
if ($blah == 'foo')
{
// this is line 1 of my code block
// this is line 2
}
Would, under python, be:
if blah == 'foo':
# this is line 1 of my code block
# this is line 2
pass
Could you please provide some code, together with the exact error?
A:
Python determines blocks by indentation, not by characters { and } like C/C++/Java/PHP/... does or by if/endif or begin/end pairs found in some other languages. So you have to be careful about indentation - also mixing tabs and spaces is not good.
|
Why do I get "expected an indented block" when I try to run my Python script?
|
I have an error which says "expected an indented block"
Could you please guide me on how to deal with this error. Thank you:)
Code example:
for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch)
|
[
"Editing answer to match the code example.\nfor ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch) \n\nis just not valid Python.\nFirst, readability count. Your code is hard to read and so, is hard to debug. What's \"ch\" and \"f\" ? What's more, you can do one liner in Python but it's not recommended, so put the for in a separate line. Then indent.\nfor chunk in file: \n ( translatedToken = english_hindi_dict[chunk] ) if (chunk in english_hindi_dict) else (translatedToken = chunk)\n\nNow we can see what's wrong. You make variable assignments in a conditional statement. This is not allowed in Python. I'm guessing you have a C/C++ background and are used to do that. In Python you can't, to prevent you from writing obfuscated code. So you end up with:\nfor chunk in file: \n translatedToken = english_hindi_dict[chunk] if chunk in english_hindi_dict else chunk\n\nThis piece of code should work, provided you use Python 2.5+. But the ternary operator is not available in older Python version yet. Let's make it a bit friendlier:\nfor chunk in file: \n translatedToken = chunk\n if chunk in english_hindi_dict:\n translatedToken = english_hindi_dict[chunk]\n\nYou may argue that it's longer to write, and you'd be right. But you spend more time reading code than writing it, so it make sense to make it easy to read. Or course, once you have the Python grip, you will try to make it work in a more pythonic way. Ever heard of EAFTP?\nfor chunk in file: \n try:\n translatedToken = english_hindi_dict[chunk]\n except KeyError:\n translatedToken = chunk\n\nBut Python is full of surprises, and you'll learn that most of these classic use cases have been already taken care of. The standard library often provides an elegant and short yet readable solution:\nfor chunk in file: \n translatedToken = english_hindi_dict.get(chunk, chunk)\n\nAs a conclusion: don't try to write Python as you wrote C, or Java as you would write Perl. Other tool, other style.\n\nTo fix this problem, fire your editor \"search and replace\" feature and make a huge \"replace all\" to change all the tabs by 4 spaces, or the contrary. Then indent all your blocks, and finally align all the instructions in the same block.\nFunny that didn't appear before on SO. After all, it's true it's not that obvious.\nIn Python, you separate blocks using spaces or tabs, not \"{\". \nSo any time you go down a block (a function, a loop, a class, etc), you have to indent your code. This is not just good practice, this is mandatory. Your program will crash if you don't.\nNow, most of the time, you get this error because you did indent, but used tabs and spaces. In a Python program, you should use either tabs or spaces, but never both in the same files. \nE.G:\nif (age > 18)\n{\n printf(\"You can vote\")\n}\n\nBecomes:\nif age > 18:\n print(\"You can vote\")\n\nIn most languages, you could do:\nif (age > 18)\n{\nprintf(\"You can vote\")\n}\n\nIn Python you can't:\nif age > 18:\nprint(\"You can vote\")\n\nraises an exception. What's more, you must align all the instruction of the same block, so:\nif age > 18:\n print(\"You can vote\")\n print(\"How cool is that ?\")\n\nIs fine, but:\nif age > 18:\n print(\"You can vote\")\n print(\"How cool is that ?\")\n\nraises an exception.\nEventually, you can't mix tab and spaces in the same block. So:\nif age > 18:\n print(\"You can vote\")\n print(\"How cool is that ?\")\n\nlooks good, but will raises an exception. To avoid this problem, just stick to tabs or spaces. The PEP8, the text one most use as a reference for coding style recommend using 4 spaces.\nMost editors have a global \"search and replace\" feature that let you fix any problem you can have with that. Some like Geany or Ulipad even have a \"replace all tabs with spaces\" feature.\n",
"You are probably mixing tabs with spaces. It looks indented but it really isn't.\n\nYour code gives me a different error:\nfor ch in f: \\\n ( translatedToken = english_hindi_dict[ch] ) \\\n if (ch in english_hindi_dict) else (translatedToken = ch)\n ↑\n\nSyntaxError: invalid syntax\n\nMaybe you meant:\nfor ch in f:\n if ch in english_hindi_dict:\n translatedToken = english_hindi_dict[ch]\n else:\n translatedToken = ch\n\nMaybe you meant instead:\nfor ch in f:\n translatedToken = english_hindi_dict[ch] if ch in english_hindi_dict else ch\n\nBoth should run just fine, and I expect the second to be faster than the former\nThey both can be optimized into translated = str(english_hindi_dict.get(ch, ch) for ch in f) but that's not the point of the question.\n",
"Python is a language that relies heavily on indentation to decide program structure unlike C and some other languages that use braces for this purpose.\nWhen you have a statement like:\nif true:\npass\n\nit will complain because there's no indented statement for the if. You would need to fix it to be:\nif true:\n pass\n\nThat sounds like the sort of error you have, though it may have been more obvious had you posted the actual code. When stating a problem, it's a good idea to give the code and explain what the expected behaviour was and how that related to the actual behaviour. You'll make the lives of those trying to help you out that much easier :-)\nAlso keep in mind that you may get this problem even if your code looks right. Mixing spaces and tabs in your source code can often lead to this.\n",
"IndentationErrors can be caused by a lot if different things. Off the top of my head:\n\nForgetting to indent at all.\nPython uses indents to delimit syntactic blocks. For example:\nif will_is_awesome:\n print \"You're right\"\nelse:\n print \"You lie!\"\n\nYou will get an IndentationError: expected an indented block error if you forget to indent. For example:\nif will_is_awesome:\nprint \"You're right\"\nelse:\nprint \"You lie!\"\n\nCommenting out an indented block.\nFor example:\nif light_is_green:\n go_now()\nelse:\n # go_anyway()\ndo_something_else()\n\nThis will produce an IndentationError: expected an indented block because the comment makes the line after else: look empty to the parser. Adding a pass statement will fix the problem. Eg:\nif light_is_green:\n go_now()\nelse:\n # go_anyway()\n pass\ndo_something_else()\n\nMixed tabs and spaces in indents.\nTab stops can vary between different machines and editors. If you mix tabs and spaces just right, you can get your error, but it usually produces IndentationError: unindent does not match any outer indentation level, so it's unlikely to be your problem. It's worth knowing anyway. It is advisable to never use tabs in Python code. \n\n",
"Python uses indentation (spaces/tabs in front of your code lines) to indicate where a block of code starts and ends, relative to what python statement precedes it.\nSo, taking PHP for example:\nif ($blah == 'foo')\n{\n // this is line 1 of my code block\n // this is line 2\n}\n\nWould, under python, be:\nif blah == 'foo':\n # this is line 1 of my code block\n # this is line 2\n pass\n\nCould you please provide some code, together with the exact error?\n",
"Python determines blocks by indentation, not by characters { and } like C/C++/Java/PHP/... does or by if/endif or begin/end pairs found in some other languages. So you have to be careful about indentation - also mixing tabs and spaces is not good.\n"
] |
[
14,
13,
11,
3,
2,
1
] |
[] |
[] |
[
"indentation",
"python"
] |
stackoverflow_0002257947_indentation_python.txt
|
Q:
Search and replace characters in a file with Python
I am trying to do transliteration where I need to replace every source character in English from a file with its equivalent from a dictionary I am using in the source code corresponding to another language in Unicode format. I am now able to read character by character from a file in English how do I search for its equivalent map in the dictionary I have defined in the source code and make sure that is printed in a new transliterated output file. Thank you:).
A:
The translate method of Unicode objects is the simplest and fastest way to perform the transliteration you require. (I assume you're using Unicode, not plain byte strings which would make it impossible to have characters such as 'पत्र'!).
All you have to do is layout your transliteration dictionary in a precise way, as specified in the docs to which I pointed you:
each key must be an integer, the codepoint of a Unicode character; for example, 0x0904 is the codepoint for ऄ, AKA "DEVANAGARI LETTER SHORT A", so for transliterating it you would use as the key in the dict the integer 0x0904 (equivalently, decimal 2308). (For a table with the codepoints for many South-Asian scripts, see this pdf).
the corresponding value can be a Unicode ordinal, a Unicode string (which is presumably what you'll use for your transliteration task, e.g. u'a' if you want to transliterate the Devanagari letter short A into the English letter 'a'), or None (if during the "transliteration" you want to simply remove instances of that Unicode character).
Characters that aren't found as keys in the dict are passed on untouched from the input to the output.
Once your dict is laid out like that, output_text = input_text.translate(thedict) does all the transliteration for you -- and pretty darn fast, too. You can apply this to blocks of Unicode text of any size that will fit comfortably in memory -- basically doing one text file as a time will be just fine on most machines (e.g., the wonderful -- and huge -- Mahabharata takes at most a few tens of megabytes in any of the freely downloadable forms -- Sanskrit [[cross-linked with both Devanagari and roman-transliterated forms]], English translation -- available from this site).
A:
Note: Updated after clarifications from questioner. Please read the comments from the OP attached to this answer.
Something like this:
for syllable in input_text.split_into_syllables():
output_file.write(d[syllable])
Here output_file is a file object, open for writing. d is a dictionary where the indexes are your source characters and the values are the output characters. You can also try to read your file line-by-line instead of reading it all in at once.
|
Search and replace characters in a file with Python
|
I am trying to do transliteration where I need to replace every source character in English from a file with its equivalent from a dictionary I am using in the source code corresponding to another language in Unicode format. I am now able to read character by character from a file in English how do I search for its equivalent map in the dictionary I have defined in the source code and make sure that is printed in a new transliterated output file. Thank you:).
|
[
"The translate method of Unicode objects is the simplest and fastest way to perform the transliteration you require. (I assume you're using Unicode, not plain byte strings which would make it impossible to have characters such as 'पत्र'!).\nAll you have to do is layout your transliteration dictionary in a precise way, as specified in the docs to which I pointed you:\n\neach key must be an integer, the codepoint of a Unicode character; for example, 0x0904 is the codepoint for ऄ, AKA \"DEVANAGARI LETTER SHORT A\", so for transliterating it you would use as the key in the dict the integer 0x0904 (equivalently, decimal 2308). (For a table with the codepoints for many South-Asian scripts, see this pdf).\nthe corresponding value can be a Unicode ordinal, a Unicode string (which is presumably what you'll use for your transliteration task, e.g. u'a' if you want to transliterate the Devanagari letter short A into the English letter 'a'), or None (if during the \"transliteration\" you want to simply remove instances of that Unicode character).\n\nCharacters that aren't found as keys in the dict are passed on untouched from the input to the output.\nOnce your dict is laid out like that, output_text = input_text.translate(thedict) does all the transliteration for you -- and pretty darn fast, too. You can apply this to blocks of Unicode text of any size that will fit comfortably in memory -- basically doing one text file as a time will be just fine on most machines (e.g., the wonderful -- and huge -- Mahabharata takes at most a few tens of megabytes in any of the freely downloadable forms -- Sanskrit [[cross-linked with both Devanagari and roman-transliterated forms]], English translation -- available from this site).\n",
"Note: Updated after clarifications from questioner. Please read the comments from the OP attached to this answer.\nSomething like this:\nfor syllable in input_text.split_into_syllables():\n output_file.write(d[syllable])\n\nHere output_file is a file object, open for writing. d is a dictionary where the indexes are your source characters and the values are the output characters. You can also try to read your file line-by-line instead of reading it all in at once.\n"
] |
[
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002257731_python.txt
|
Q:
Grid lines in parasitic axes in matplotlib
Can you draw the grid lines in a plot with parasitic axes in matplotlib?
I try this, based on the samples for grids and for parasitic axes, but grid drawing is not performed:
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
import matplotlib.pyplot as plt
fig = plt.figure(1)
host = SubplotHost(fig, 111)
fig.add_subplot(host)
par = host.twinx()
host.set_xlabel("Distance")
host.set_ylabel("Density")
par.set_ylabel("Temperature")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature")
host.axis["left"].label.set_color(p1.get_color())
par.axis["right"].label.set_color(p2.get_color())
host.grid(True)
host.legend()
plt.show()
A:
From the discussion here it looks like this is a bug in the .99 release.
(I'm not sure why it works for doug but no combination of rcParams works for me on version 0.99.1.1-r1.)
From that link the answer is to make a call to:
host.toggle_axisline(False)
What the toggle_axisline does is simply to make the xaxis and yaxis
(which are responsible for drawing ticks, ticklabels, etc in the
mainline mpl) visible again, and make axis["bottom"] and etc
invisible.
The whole program becomes:
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
import matplotlib.pyplot as plt
fig = plt.figure(1)
host = SubplotHost(fig, 111)
fig.add_subplot(host)
par = host.twinx()
host.set_xlabel("Distance")
host.set_ylabel("Density")
par.set_ylabel("Temperature")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature")
host.axis["left"].label.set_color(p1.get_color())
par.axis["right"].label.set_color(p2.get_color())
host.toggle_axisline(False)
host.grid(True)
host.legend()
plt.show()
A:
For plots of this type, it's not always easy to tell at a glance which object should make the call to 'grid'.
One way around this inconvenience--i.e., to get the grid lines on your plot without having to change any of your code and worry about whether you have the right object calling 'grid'--is to edit your config file. That might be enough for you to do exactly what you need to do, but just in case:
download the sample matplotlibrc file here or retrieve your copy at site-packages/matplotlib/mpl-data/;
at about line 195 or so of this file, look for a heading (as a comment) "### AXES";
five-six lines below that heading you'll see 'axes-grid'--uncomment this line and set the value to 'True';
now read down this file to about lines 235 or so where you will see the header '### GRIDS';
uncomment the next three lines ('grid.color', 'grid.linestyle', and grid.linewidth') and supply reasonable values for those three parameters (mine are: 'darkslategray', ':', and 0.7, respectively). (The ':' value means my grid lines will be dotted lines.)
save that file as: ~/.matplotlibrc/matplotlibrc (in other words, create a directory in your top level user directory called '.matplotlibrc', don't forget the leading '.', then name this file you've been editing 'matplotlibrc'.
That's it. (The downside is when you are creating plots for which you do not want grid lines--for those, i would keep this config file as is and create additional config files as needed and switch among them (see the relevant Matplotlib page for how to do that.)
Also, this config file is easy to edit using ipython--that's probably how most users do it, but that might have been confusing here.
|
Grid lines in parasitic axes in matplotlib
|
Can you draw the grid lines in a plot with parasitic axes in matplotlib?
I try this, based on the samples for grids and for parasitic axes, but grid drawing is not performed:
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
import matplotlib.pyplot as plt
fig = plt.figure(1)
host = SubplotHost(fig, 111)
fig.add_subplot(host)
par = host.twinx()
host.set_xlabel("Distance")
host.set_ylabel("Density")
par.set_ylabel("Temperature")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature")
host.axis["left"].label.set_color(p1.get_color())
par.axis["right"].label.set_color(p2.get_color())
host.grid(True)
host.legend()
plt.show()
|
[
"From the discussion here it looks like this is a bug in the .99 release. \n(I'm not sure why it works for doug but no combination of rcParams works for me on version 0.99.1.1-r1.)\nFrom that link the answer is to make a call to:\nhost.toggle_axisline(False)\n\n\nWhat the toggle_axisline does is simply to make the xaxis and yaxis\n (which are responsible for drawing ticks, ticklabels, etc in the\n mainline mpl) visible again, and make axis[\"bottom\"] and etc\n invisible.\n\nThe whole program becomes:\nfrom mpl_toolkits.axes_grid.parasite_axes import SubplotHost\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(1)\n\nhost = SubplotHost(fig, 111)\nfig.add_subplot(host)\n\npar = host.twinx()\n\nhost.set_xlabel(\"Distance\")\nhost.set_ylabel(\"Density\")\npar.set_ylabel(\"Temperature\")\n\np1, = host.plot([0, 1, 2], [0, 1, 2], label=\"Density\")\np2, = par.plot([0, 1, 2], [0, 3, 2], label=\"Temperature\")\n\nhost.axis[\"left\"].label.set_color(p1.get_color())\npar.axis[\"right\"].label.set_color(p2.get_color())\n\nhost.toggle_axisline(False)\nhost.grid(True)\n\nhost.legend()\n\nplt.show()\n\n\n",
"For plots of this type, it's not always easy to tell at a glance which object should make the call to 'grid'.\nOne way around this inconvenience--i.e., to get the grid lines on your plot without having to change any of your code and worry about whether you have the right object calling 'grid'--is to edit your config file. That might be enough for you to do exactly what you need to do, but just in case:\n\ndownload the sample matplotlibrc file here or retrieve your copy at site-packages/matplotlib/mpl-data/;\nat about line 195 or so of this file, look for a heading (as a comment) \"### AXES\"; \nfive-six lines below that heading you'll see 'axes-grid'--uncomment this line and set the value to 'True';\nnow read down this file to about lines 235 or so where you will see the header '### GRIDS';\nuncomment the next three lines ('grid.color', 'grid.linestyle', and grid.linewidth') and supply reasonable values for those three parameters (mine are: 'darkslategray', ':', and 0.7, respectively). (The ':' value means my grid lines will be dotted lines.)\nsave that file as: ~/.matplotlibrc/matplotlibrc (in other words, create a directory in your top level user directory called '.matplotlibrc', don't forget the leading '.', then name this file you've been editing 'matplotlibrc'.\n\nThat's it. (The downside is when you are creating plots for which you do not want grid lines--for those, i would keep this config file as is and create additional config files as needed and switch among them (see the relevant Matplotlib page for how to do that.)\nAlso, this config file is easy to edit using ipython--that's probably how most users do it, but that might have been confusing here.\n"
] |
[
5,
3
] |
[] |
[] |
[
"grid",
"matplotlib",
"python"
] |
stackoverflow_0002248118_grid_matplotlib_python.txt
|
Q:
Python - to check if a char is in dictionary and if not to deal with it
I am going about transliteration from one source language(input file) to a target language(target file) so I am checking for equivalent mappings in a dictionary in my source code, certain characters in the source code don't have an equivalent mapping like comma(,) and all other such special symbols. How do I check if the character belongs to the dictionary for which I have an equivalent mapping and to even take care of those special symbols to be printed in the target file which don't have an equivalent mapping in the dictionary. Thank you:).
A:
My recommendation, given that rules is a mapping of the characters to their transliterated equivalents:
results = []
for char in source_text:
results.append(rules.get(char, char))
return ''.join(results) # turns the list back into a string
A dict's get method will return either the value for a key or a default value if the key does not exist - normally the default value is None, but in this case, we gave the same character as the default value (the second argument) so that if the key is not found it will just return itself.
A more compact way to write this using generator expressions would be:
''.join((rules.get(char, char) for char in source_text))
A:
If you use the translate method of Unicode objects, as I recommended in answer to another question of yours, everything's done automatically for you exactly as you desire: each Unicode character c whose codepoints (ord(c)) is not in the transliteration dictionary is simply passed unchanged from input to output, just as you want. Why reinvent the wheel?
A:
I think you want something like this:
tokenMapping = {"&&" : "and"}
for token in source file: # <-- pseudocode
translatedToken = tokenMapping[token] if token in tokenMapping else "transliteration unknown"
If there's a translation in the dictionary (e.g. "&&" -> "and"), it will use that. Else it will translate to "transliteration unknown".
Hope that helped.
EDIT: As LeafStorm suggested, a dictionary's get function can be used to simplify the above code. The code line in the loop would become
translatedToken = tokenMapping.get(token, "transliteration unknown")
A:
dictx = {}
for itm in my_source :
dictx[itm] = dictx.get(itm, 0) + 1
I didn't completely understand the details of your question, but here's the simplest example i could think of that illustrates the pattern i think you are after.
The 'get' method i believe is what you want. It allows you to retrieve a key from a dictionary, but if the key is not there, you can set a default value--i.e., "i want dictx[itm] (the value assigned to the key 'itm') but if 'itm' is not in dictionary then create it and value of .'
This snippet will loop through your source document ('my_source') and count the frequency of the various items in it, adding those counts as values to the keys already in your dictionary, but when it reaches an item for which no key exists, no exception is thrown, a key is added and a value of '0' assigned.
A:
This seems pretty straightforward. If your dictionary is char to char, then you would do something like
outstr = ''
for ch in instr:
if ch in mydict:
outstr += mydict[ch]
else:
outstr += ch
Here, instr is your input string and mydict contains your mapping of chars to chars.
If you want to check parts of words, I would recommend using two dictionaries: one that contains the characters that are contained in any word, and one that contains the words. You could use it like this:
outstr = ''
word = ''
for ch in instr:
if ch in chardict:
word += ch
else:
if len(word):
if word in worddict:
outstr += worddict[word]
else:
outstr += word
word = ''
outstr += ch
if len(word):
outstr += worddict[word]
else:
outstr += word
chardict might contain all of the alphabet for instance. Of course, you might want to do some parts a little bit differently (like use something other than chardict to check if a char is to be considered part of a valid word - perhaps something with a binary search), but hopefully you get the idea.
|
Python - to check if a char is in dictionary and if not to deal with it
|
I am going about transliteration from one source language(input file) to a target language(target file) so I am checking for equivalent mappings in a dictionary in my source code, certain characters in the source code don't have an equivalent mapping like comma(,) and all other such special symbols. How do I check if the character belongs to the dictionary for which I have an equivalent mapping and to even take care of those special symbols to be printed in the target file which don't have an equivalent mapping in the dictionary. Thank you:).
|
[
"My recommendation, given that rules is a mapping of the characters to their transliterated equivalents:\nresults = []\nfor char in source_text:\n results.append(rules.get(char, char))\nreturn ''.join(results) # turns the list back into a string\n\nA dict's get method will return either the value for a key or a default value if the key does not exist - normally the default value is None, but in this case, we gave the same character as the default value (the second argument) so that if the key is not found it will just return itself.\nA more compact way to write this using generator expressions would be:\n''.join((rules.get(char, char) for char in source_text))\n\n",
"If you use the translate method of Unicode objects, as I recommended in answer to another question of yours, everything's done automatically for you exactly as you desire: each Unicode character c whose codepoints (ord(c)) is not in the transliteration dictionary is simply passed unchanged from input to output, just as you want. Why reinvent the wheel?\n",
"I think you want something like this:\ntokenMapping = {\"&&\" : \"and\"}\n\nfor token in source file: # <-- pseudocode\n translatedToken = tokenMapping[token] if token in tokenMapping else \"transliteration unknown\"\n\nIf there's a translation in the dictionary (e.g. \"&&\" -> \"and\"), it will use that. Else it will translate to \"transliteration unknown\".\nHope that helped.\nEDIT: As LeafStorm suggested, a dictionary's get function can be used to simplify the above code. The code line in the loop would become\n translatedToken = tokenMapping.get(token, \"transliteration unknown\")\n\n",
"dictx = {}\nfor itm in my_source :\n dictx[itm] = dictx.get(itm, 0) + 1\n\nI didn't completely understand the details of your question, but here's the simplest example i could think of that illustrates the pattern i think you are after. \nThe 'get' method i believe is what you want. It allows you to retrieve a key from a dictionary, but if the key is not there, you can set a default value--i.e., \"i want dictx[itm] (the value assigned to the key 'itm') but if 'itm' is not in dictionary then create it and value of .'\nThis snippet will loop through your source document ('my_source') and count the frequency of the various items in it, adding those counts as values to the keys already in your dictionary, but when it reaches an item for which no key exists, no exception is thrown, a key is added and a value of '0' assigned.\n",
"This seems pretty straightforward. If your dictionary is char to char, then you would do something like\noutstr = ''\nfor ch in instr:\n if ch in mydict:\n outstr += mydict[ch]\n else:\n outstr += ch\n\nHere, instr is your input string and mydict contains your mapping of chars to chars. \nIf you want to check parts of words, I would recommend using two dictionaries: one that contains the characters that are contained in any word, and one that contains the words. You could use it like this:\noutstr = ''\nword = ''\nfor ch in instr:\n if ch in chardict:\n word += ch\n else:\n if len(word):\n if word in worddict:\n outstr += worddict[word]\n else:\n outstr += word\n word = ''\n outstr += ch\nif len(word):\n outstr += worddict[word]\nelse:\n outstr += word\n\nchardict might contain all of the alphabet for instance. Of course, you might want to do some parts a little bit differently (like use something other than chardict to check if a char is to be considered part of a valid word - perhaps something with a binary search), but hopefully you get the idea. \n"
] |
[
3,
3,
1,
0,
0
] |
[] |
[] |
[
"python",
"transliteration"
] |
stackoverflow_0002257799_python_transliteration.txt
|
Q:
Modify entity data either transactionally or not (depending on the need)
What is the best way to keep code modular and decoupled but avoid entering a transaction twice?
Entities often have class methods to load, modify, and store data. Often, this must be transactional to be consistent with child/sibling/cousin entities. Here is the pattern:
class MyEntity(db.Model):
# ... some properties
@classmethod
def update_count(cls, my_key):
def txn():
me = db.get(my_key)
me.count += 23
me.put()
OtherEntity.update_descendants(ancestor=me)
return db.run_in_transaction(txn)
Usually, you should fetch entities, modify them, and store them in once block. That technique is more performant; but sometimes performance is less important than modularity and maintainability. The two updates should be decoupled. (Perhaps update_descendants is called often in isolation, and it's responsible for storing the data.)
But, the following code is a bug:
class OtherEntity(db.Model):
# ... some properties
@classmethod
def update_descendants(cls, ancestor):
def txn(): # XXX Bug!
descendants = cls.all().ancestor(ancestor).fetch(10)
for descendant in descendants:
descendant.update_yourself(ancestor.count)
db.put(descendants)
return db.run_in_transaction(txn)
That raises an exception:
>>> MyEntity.update_count(my_key=some_key_i_have)
Traceback (most recent call last):
...
BadRequestError: Nested transactions are not supported.
So how can I get the best of both worlds: modularity, and correctness?
A:
The pattern I use is to have a parameter indicating whether transactional behavior is required.
class OtherEntity(db.Model):
# ... some properties
@classmethod
def update_descendants(cls, ancestor, with_transaction=True):
if with_transaction:
return db.run_in_transaction(cls.update_descendants, ancestor,
with_transaction=False)
# Now I can assume I am in a transaction one way or another...
descendants = cls.all().ancestor(ancestor).fetch(10)
for descendant in descendants:
descendant.update_yourself(ancestor.count)
return db.put(descendants)
The same principle could be expanded to indicate whether to take responsibility for the put, or to leave it to the caller.
A:
I would suggest making the transaction functions top-level class methods. Then, you can call them directly or with db.run_in_transaction, as appropriate.
|
Modify entity data either transactionally or not (depending on the need)
|
What is the best way to keep code modular and decoupled but avoid entering a transaction twice?
Entities often have class methods to load, modify, and store data. Often, this must be transactional to be consistent with child/sibling/cousin entities. Here is the pattern:
class MyEntity(db.Model):
# ... some properties
@classmethod
def update_count(cls, my_key):
def txn():
me = db.get(my_key)
me.count += 23
me.put()
OtherEntity.update_descendants(ancestor=me)
return db.run_in_transaction(txn)
Usually, you should fetch entities, modify them, and store them in once block. That technique is more performant; but sometimes performance is less important than modularity and maintainability. The two updates should be decoupled. (Perhaps update_descendants is called often in isolation, and it's responsible for storing the data.)
But, the following code is a bug:
class OtherEntity(db.Model):
# ... some properties
@classmethod
def update_descendants(cls, ancestor):
def txn(): # XXX Bug!
descendants = cls.all().ancestor(ancestor).fetch(10)
for descendant in descendants:
descendant.update_yourself(ancestor.count)
db.put(descendants)
return db.run_in_transaction(txn)
That raises an exception:
>>> MyEntity.update_count(my_key=some_key_i_have)
Traceback (most recent call last):
...
BadRequestError: Nested transactions are not supported.
So how can I get the best of both worlds: modularity, and correctness?
|
[
"The pattern I use is to have a parameter indicating whether transactional behavior is required.\nclass OtherEntity(db.Model):\n# ... some properties\n\n@classmethod\ndef update_descendants(cls, ancestor, with_transaction=True):\n if with_transaction:\n return db.run_in_transaction(cls.update_descendants, ancestor,\n with_transaction=False)\n\n # Now I can assume I am in a transaction one way or another...\n descendants = cls.all().ancestor(ancestor).fetch(10)\n for descendant in descendants:\n descendant.update_yourself(ancestor.count)\n return db.put(descendants)\n\nThe same principle could be expanded to indicate whether to take responsibility for the put, or to leave it to the caller.\n",
"I would suggest making the transaction functions top-level class methods. Then, you can call them directly or with db.run_in_transaction, as appropriate.\n"
] |
[
2,
1
] |
[] |
[] |
[
"google_app_engine",
"python",
"transactions"
] |
stackoverflow_0002257946_google_app_engine_python_transactions.txt
|
Q:
Disable cache in Pylons app under development mode
I'm using @beaker_cache() decorator in my Pylons application.
How can I disable the cache under development mode?
A:
You could write your own decorator which looks at pylons.config["debug"], and depending on that either returns function unchanged or decorated with beaker_cache. Something along these lines (completely untested!):
from pylons import config
def my_cache(*args, **kwargs):
if config["debug"]:
decorate = lambda f: f
else:
decorate = beaker_cache(*args, **kwargs)
return decorate
|
Disable cache in Pylons app under development mode
|
I'm using @beaker_cache() decorator in my Pylons application.
How can I disable the cache under development mode?
|
[
"You could write your own decorator which looks at pylons.config[\"debug\"], and depending on that either returns function unchanged or decorated with beaker_cache. Something along these lines (completely untested!):\nfrom pylons import config\n\ndef my_cache(*args, **kwargs):\n if config[\"debug\"]:\n decorate = lambda f: f\n else: \n decorate = beaker_cache(*args, **kwargs)\n\n return decorate\n\n"
] |
[
1
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0002243470_pylons_python.txt
|
Q:
Pylons and Flex 3
Has anyone used Python/Pylons as the server backend for a Flex 3 application? Does anyone have any thoughts on how well this would work? I read Bruce Eckel's article about tying Flex 3 to Twisted, and I've done Twisted programming, but for just a web service I think Pylons is simpler to use.
Thanks in advance,
Doug
A:
I'm working on webapp which has client-side UI coded in Flex 3 and backend is Pylons app. Our client communicates with backend using HTTP GET and POST requests, POST request bodies and all response bodies carry data in JSON format. Works well, just few gotchas:
Flex apps cannot do PUT and DELETE requests. We work around this by doing POST requests and specifying the "real" intended method in X-HTTP-Method-Override header. Then we have some extra routes in routing configuration that handle these requests and treat them as normal PUTs and GETs.
Flex apps can send custom HTTP headers but cannot read custom headers received from server (well they can on IE, but cannot on Firefox and Chrome, IIRC).
|
Pylons and Flex 3
|
Has anyone used Python/Pylons as the server backend for a Flex 3 application? Does anyone have any thoughts on how well this would work? I read Bruce Eckel's article about tying Flex 3 to Twisted, and I've done Twisted programming, but for just a web service I think Pylons is simpler to use.
Thanks in advance,
Doug
|
[
"I'm working on webapp which has client-side UI coded in Flex 3 and backend is Pylons app. Our client communicates with backend using HTTP GET and POST requests, POST request bodies and all response bodies carry data in JSON format. Works well, just few gotchas:\n\nFlex apps cannot do PUT and DELETE requests. We work around this by doing POST requests and specifying the \"real\" intended method in X-HTTP-Method-Override header. Then we have some extra routes in routing configuration that handle these requests and treat them as normal PUTs and GETs.\nFlex apps can send custom HTTP headers but cannot read custom headers received from server (well they can on IE, but cannot on Firefox and Chrome, IIRC). \n\n"
] |
[
0
] |
[] |
[] |
[
"apache_flex",
"pylons",
"python",
"twisted"
] |
stackoverflow_0002185329_apache_flex_pylons_python_twisted.txt
|
Q:
How do I handle Python XML-RPC output and exceptions?
I have created a simple Python XML-RPC implementation, largely based on the examples.
However, it sends output like this:
foo.bar.com - - [13/Feb/2010 17:55:47] "POST /RPC2 HTTP/1.0" 200 -
... to the terminal, even if I redirect standard out and standard error to a file using >> or >. I'm doing this with the following line:
python foobar 2>&1 >> foobar.log
It seems almost like it's not sending to standard out, but somewhere else.
Also, when an exception occurs on recieving a request, the whole application crashes with this error:
----------------------------------------
Exception happened during processing of request from ('1.2.3.4', 51284)
How can I handle this exception? I need to recover gracefully, and just log the exception message rather than the server crashing.
A:
I guess you're using the SimpleXMLRPCServer class from the examples. In that case, simply provide the parameter logRequests when creating it:
server = SimpleXMLRPCServer(("localhost", 8000), logRequests = False)
That will suppress request logging.
As for the exceptions, they're logged in BaseServer (cf. source code of "SocketServer.py"):
def handle_error(self, request, client_address):
"""Handle an error gracefully. May be overridden.
The default is to print a traceback and continue.
"""
print '-'*40
print 'Exception happened during processing of request from',
print client_address
import traceback
traceback.print_exc() # XXX But this goes to stderr!
print '-'*40
As you can see, the first part is written to stdout, which is why &2>1 didn't work completely. If you want to suppress them, override or overwrite that method.
A:
This is really a shell redirection problem, not a python problem.
When you say
python foobar 2>&1 >> foobar.log
You are first redirecting stderr to stdout, and then second redirecting stdout to foobar.log.
stderr does not get automatically redirected to foobar.log. stderr still points to the original stdout.
So instead do this:
python foobar >> foobar.log 2>&1
See also http://bash-hackers.org/wiki/doku.php/syntax/redirection (search for "Multiple redirections")
|
How do I handle Python XML-RPC output and exceptions?
|
I have created a simple Python XML-RPC implementation, largely based on the examples.
However, it sends output like this:
foo.bar.com - - [13/Feb/2010 17:55:47] "POST /RPC2 HTTP/1.0" 200 -
... to the terminal, even if I redirect standard out and standard error to a file using >> or >. I'm doing this with the following line:
python foobar 2>&1 >> foobar.log
It seems almost like it's not sending to standard out, but somewhere else.
Also, when an exception occurs on recieving a request, the whole application crashes with this error:
----------------------------------------
Exception happened during processing of request from ('1.2.3.4', 51284)
How can I handle this exception? I need to recover gracefully, and just log the exception message rather than the server crashing.
|
[
"I guess you're using the SimpleXMLRPCServer class from the examples. In that case, simply provide the parameter logRequests when creating it:\nserver = SimpleXMLRPCServer((\"localhost\", 8000), logRequests = False)\n\nThat will suppress request logging.\nAs for the exceptions, they're logged in BaseServer (cf. source code of \"SocketServer.py\"):\ndef handle_error(self, request, client_address):\n \"\"\"Handle an error gracefully. May be overridden.\n\n The default is to print a traceback and continue.\n\n \"\"\"\n print '-'*40\n print 'Exception happened during processing of request from',\n print client_address\n import traceback\n traceback.print_exc() # XXX But this goes to stderr!\n print '-'*40\n\nAs you can see, the first part is written to stdout, which is why &2>1 didn't work completely. If you want to suppress them, override or overwrite that method.\n",
"This is really a shell redirection problem, not a python problem. \nWhen you say\npython foobar 2>&1 >> foobar.log\n\nYou are first redirecting stderr to stdout, and then second redirecting stdout to foobar.log.\nstderr does not get automatically redirected to foobar.log. stderr still points to the original stdout.\nSo instead do this:\npython foobar >> foobar.log 2>&1 \n\nSee also http://bash-hackers.org/wiki/doku.php/syntax/redirection (search for \"Multiple redirections\")\n"
] |
[
5,
0
] |
[] |
[] |
[
"python",
"xml_rpc"
] |
stackoverflow_0002258514_python_xml_rpc.txt
|
Q:
Using TinyMCE for sites with a dark background
I'm using django-tinymce in my Django website. Through the admin interface one can edit a SimplePage object which has a tinymce.models.HTMLField. The website visitor will then see the html rendered in the content area of the page.
Problem is, the website itself has a dark background, and the TinyMCE textarea has a white one. By default the text seems to have no color, which is okay (It appears as black in TinyMCE and as white in the website) but sometimes a black color is assigned to it and then it appears as black in the website, which makes it unreadable.
What's a good way to solve this?
A:
You can customize the CSS of the editable area with the content_css setting, see: http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/content_css
This also works with django-tinymce, simply adjust TINYMCE_DEFAULT_CONFIG in your django settings:
TINYMCE_DEFAULT_CONFIG = {
# your other settings
'content_css': '/media/css/main.css',
}
A:
Usually in a Rich Text Editor, you would specify a style sheet (the original page's style sheet or a variation of it) as the style sheet for the editor. That way, all the basic text characteristics (size, family, colour and background colour) are really What You See Is What You Get.
I think this is it:
Option: content_css
This option enables you to specify a custom CSS file that extends the theme content CSS. This CSS file is the one used within the editor (the editable area). This option can also be a comma separated list of URLs.
If you specify a relative path, it is resolved in relation to the URL of the (HTML) file that includes TinyMCE, NOT relative to TinyMCE itself.
|
Using TinyMCE for sites with a dark background
|
I'm using django-tinymce in my Django website. Through the admin interface one can edit a SimplePage object which has a tinymce.models.HTMLField. The website visitor will then see the html rendered in the content area of the page.
Problem is, the website itself has a dark background, and the TinyMCE textarea has a white one. By default the text seems to have no color, which is okay (It appears as black in TinyMCE and as white in the website) but sometimes a black color is assigned to it and then it appears as black in the website, which makes it unreadable.
What's a good way to solve this?
|
[
"You can customize the CSS of the editable area with the content_css setting, see: http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/content_css\nThis also works with django-tinymce, simply adjust TINYMCE_DEFAULT_CONFIG in your django settings:\nTINYMCE_DEFAULT_CONFIG = {\n # your other settings\n 'content_css': '/media/css/main.css',\n}\n\n",
"Usually in a Rich Text Editor, you would specify a style sheet (the original page's style sheet or a variation of it) as the style sheet for the editor. That way, all the basic text characteristics (size, family, colour and background colour) are really What You See Is What You Get.\nI think this is it:\n\nOption: content_css\nThis option enables you to specify a custom CSS file that extends the theme content CSS. This CSS file is the one used within the editor (the editable area). This option can also be a comma separated list of URLs.\nIf you specify a relative path, it is resolved in relation to the URL of the (HTML) file that includes TinyMCE, NOT relative to TinyMCE itself.\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_tinymce",
"html",
"python",
"tinymce"
] |
stackoverflow_0002258678_django_django_tinymce_html_python_tinymce.txt
|
Q:
More than 1 docstrings for a single module/function etc.?
I'm using python 3.1.
Is it possible to create more than 1 docstring for a single module or function?
I'm creating a program, and I'm intending to have multiple docstrings with a category for each. I intend to give other people the program so they can use it, and to make things easy for programmers and non-programmers alike, I'm putting a reference to the docstring for documentation within the program itself.
To be more specific, I have a menu in the program/module as an interface, and one of the options will allow access to the module docstring for documentation on the program. Thus, if it's possible, I want to make multiple docstrings to categorise different types of documentation. So it would be easier on the users if they want to see some part of the documentation.
eg. first docstring contains instructions on how to use the program. Second docstring contains information on how one part of the program works. Third docstring contains info on how another part works. etc.
Is this possible? And if so, how do you reference them?
Updates: Added a comment.
My original thought was to actually have more than one docstring in the sense of:
def foo():
"""docstring1: blah blah blah"""
"""docstring2: blah blah blah"""
pass # Insert code here
Then there would be some code that I could use to allow me to reference each of these docstrings.
So, I'm guessing that this isn't possible then?
A:
I don't recommend trying to do something complicated with the docstrings. Best to keep the docstrings simple, and do something else if you want to make a bunch of different documentation options available.
If you really want to do what you described, I suggest you use tags to delimit sections within docstrings. Like so:
def foo(bar, baz):
"""Function foo()
* Summary:
Function foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them.
* Developers:
When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.
* Testers:
When you test foo, be sure to try negative values for baz.
"""
pass # code would go here
Then you can pretty easily split your string into chunks, and when the user chooses a menu item, show just the appropriate chunks.
s = foo.__doc__ # s now refers to the docstring
lst = s.split("\n* ")
section = [section for section in lst if section.startswith("Developers")][0]
print(section) # prints the "Developers" section
This way, when you are working in the interactive Python shell, you can say "help(foo)" and you will see all the docstrings. And, you are not changing the fundamental behavior of a basic part of Python, which would freak out other people trying to study your code.
You could also do something even simpler: just make a big global dictionary of docstrings for different purposes, and update it from the source code for each new thing.
doc_developers = {}
doc_testers = {}
def foo(bar, baz):
"""Function foo()
Function foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them."
pass # code goes here
doc_developers["foo"] = "When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests."
doc_testers["foo"] = "When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests."
The biggest thing I don't like about this is that, if you change the name of function foo, you would need to change it in multiple places: once in the actual def and once per dictionary update line. But you could mostly fix that by writing a function:
def doc_dict = {} # this will be a dict of dicts
doc_dict["developers"] = {}
doc_dict["testers"] = {}
def doc_update(fn, d):
name = fn.__name__
for key, value in d.items():
doc_dict[key][name] = value
def foo(bar, baz):
"""Function foo()
Function foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them."
pass # code goes here
d = { "developers": "When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.",
"testers": " When you test foo, be sure to try negative values for baz."}
doc_update(foo, d)
There is probably a way to turn doc_update() into a decorator, but I'm out of time right now.
A:
You want to consider using decorators to cleanly do what ~unutbu is proposing for functions: adding a separate field per each. For example:
def human_desc(description):
def add_field(function):
function.human_desc = description
return function
return add_field
This is what human_desc in action would look like:
@human_desc('This function eggfoobars its spam.')
def eggfoobar(spam):
"Apply egg, foo and bar to our spam metaclass object stuff."
print spam
Explaination
As the doc explains, that bit of code is equivalent to the following:
def eggfoobar(spam):
"Apply egg, foo and bar to our spam metaclass object stuff."
print spam
eggfoobar = human_desc('This function eggfoobars its spam.')(eggfoobar)
and human_desc('This function eggfoobars its spam.') returns the following function:
def add_field(function):
function.human_desc = 'This function eggfoobars its spam.'
return function
As you can see human_desc is a function that generates the above decorator for the value of description you pass as an argument. The decorator itself is a function that accepts a function to be decorated (modified) and returns it decorated (in this case, that is, with the addition of that bit of extra metadata). In short this is equivalent to:
def eggfoobar(spam):
"Apply egg, foo and bar to our spam metaclass object stuff."
print spam
eggfoobar.human_desc = 'This function eggfoobars its spam.'
The syntax, however, is far cleaner and less error prone.
Obviously, in either way, what you get is:
>>> print eggfoobar.human_desc
This function eggfoobars its spam.
A:
Instead of using a function, you could use a class with usage and extra attributes defined. For example,
class Foo(object):
'''Here is the function's official docstring'''
usage='All about the usage'
extra='How another part works'
def __call__(self):
# Put the foo function code here
pass
foo=Foo()
You'd call it as usual: foo(),
and you can get the official docstring, and alternate doc string like this:
print foo.__doc__
print foo.usage
print foo.extra
You can also attach extra attributes to plain functions (instead of using a class as I did above), but I think the syntax is a little uglier:
def foo():
pass
foo.usage='Usage string'
foo.extra='Extra string'
And, modules are objects too. They can have extra attributes just as easily:
If you define module constants
USAGE='''blah blah'''
EXTRA='''meow'''
Then when you import the module:
import mymodule
You can access the official and alternate docstrings with
mymodule.__doc__
mymodule.USAGE
mymodule.EXTRA
A:
You can replace the __doc__ attribute if you want to have more than one possible docstring, but please consider making the initial docstring flexible enough for all types.
A:
Module is a collection of classes/functions/modules. So its docstring gives the intro about what it contains.
Class docstring tells what the class is about and its methods docstrings tell what the methods so. A class serves one purpose and a methods does a single thing so they should have single docstring.
Functions do one thing so one doctring should suffice for them.
I can't see what purpose will multiple docstrings suffice. Maybe your module is big. Divide into sub-modules and in the docstring for the module mention sub-modules.
|
More than 1 docstrings for a single module/function etc.?
|
I'm using python 3.1.
Is it possible to create more than 1 docstring for a single module or function?
I'm creating a program, and I'm intending to have multiple docstrings with a category for each. I intend to give other people the program so they can use it, and to make things easy for programmers and non-programmers alike, I'm putting a reference to the docstring for documentation within the program itself.
To be more specific, I have a menu in the program/module as an interface, and one of the options will allow access to the module docstring for documentation on the program. Thus, if it's possible, I want to make multiple docstrings to categorise different types of documentation. So it would be easier on the users if they want to see some part of the documentation.
eg. first docstring contains instructions on how to use the program. Second docstring contains information on how one part of the program works. Third docstring contains info on how another part works. etc.
Is this possible? And if so, how do you reference them?
Updates: Added a comment.
My original thought was to actually have more than one docstring in the sense of:
def foo():
"""docstring1: blah blah blah"""
"""docstring2: blah blah blah"""
pass # Insert code here
Then there would be some code that I could use to allow me to reference each of these docstrings.
So, I'm guessing that this isn't possible then?
|
[
"I don't recommend trying to do something complicated with the docstrings. Best to keep the docstrings simple, and do something else if you want to make a bunch of different documentation options available.\nIf you really want to do what you described, I suggest you use tags to delimit sections within docstrings. Like so:\ndef foo(bar, baz):\n \"\"\"Function foo()\n\n* Summary:\n Function foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them.\n\n* Developers:\n When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.\n\n* Testers:\n When you test foo, be sure to try negative values for baz.\n\"\"\"\n pass # code would go here\n\nThen you can pretty easily split your string into chunks, and when the user chooses a menu item, show just the appropriate chunks.\ns = foo.__doc__ # s now refers to the docstring\n\nlst = s.split(\"\\n* \")\nsection = [section for section in lst if section.startswith(\"Developers\")][0]\nprint(section) # prints the \"Developers\" section\n\nThis way, when you are working in the interactive Python shell, you can say \"help(foo)\" and you will see all the docstrings. And, you are not changing the fundamental behavior of a basic part of Python, which would freak out other people trying to study your code.\nYou could also do something even simpler: just make a big global dictionary of docstrings for different purposes, and update it from the source code for each new thing.\ndoc_developers = {}\ndoc_testers = {}\ndef foo(bar, baz):\n \"\"\"Function foo()\n\nFunction foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them.\"\n pass # code goes here\n\ndoc_developers[\"foo\"] = \"When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.\"\n\ndoc_testers[\"foo\"] = \"When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.\"\n\nThe biggest thing I don't like about this is that, if you change the name of function foo, you would need to change it in multiple places: once in the actual def and once per dictionary update line. But you could mostly fix that by writing a function:\ndef doc_dict = {} # this will be a dict of dicts\ndoc_dict[\"developers\"] = {}\ndoc_dict[\"testers\"] = {}\n\ndef doc_update(fn, d):\n name = fn.__name__\n for key, value in d.items():\n doc_dict[key][name] = value\n\ndef foo(bar, baz):\n \"\"\"Function foo()\n\nFunction foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them.\"\n pass # code goes here\n\nd = { \"developers\": \"When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.\",\n\"testers\": \" When you test foo, be sure to try negative values for baz.\"}\n\ndoc_update(foo, d)\n\nThere is probably a way to turn doc_update() into a decorator, but I'm out of time right now.\n",
"You want to consider using decorators to cleanly do what ~unutbu is proposing for functions: adding a separate field per each. For example:\ndef human_desc(description):\n def add_field(function):\n function.human_desc = description\n return function\n return add_field\n\nThis is what human_desc in action would look like:\n@human_desc('This function eggfoobars its spam.')\ndef eggfoobar(spam):\n \"Apply egg, foo and bar to our spam metaclass object stuff.\"\n print spam\n\n\nExplaination\nAs the doc explains, that bit of code is equivalent to the following:\ndef eggfoobar(spam):\n \"Apply egg, foo and bar to our spam metaclass object stuff.\"\n print spam\neggfoobar = human_desc('This function eggfoobars its spam.')(eggfoobar)\n\nand human_desc('This function eggfoobars its spam.') returns the following function:\ndef add_field(function):\n function.human_desc = 'This function eggfoobars its spam.'\n return function\n\nAs you can see human_desc is a function that generates the above decorator for the value of description you pass as an argument. The decorator itself is a function that accepts a function to be decorated (modified) and returns it decorated (in this case, that is, with the addition of that bit of extra metadata). In short this is equivalent to:\ndef eggfoobar(spam):\n \"Apply egg, foo and bar to our spam metaclass object stuff.\"\n print spam\neggfoobar.human_desc = 'This function eggfoobars its spam.'\n\nThe syntax, however, is far cleaner and less error prone.\nObviously, in either way, what you get is:\n>>> print eggfoobar.human_desc\nThis function eggfoobars its spam.\n\n",
"Instead of using a function, you could use a class with usage and extra attributes defined. For example,\nclass Foo(object):\n '''Here is the function's official docstring'''\n usage='All about the usage'\n extra='How another part works'\n def __call__(self):\n # Put the foo function code here\n pass\nfoo=Foo()\n\nYou'd call it as usual: foo(),\nand you can get the official docstring, and alternate doc string like this:\nprint foo.__doc__\nprint foo.usage\nprint foo.extra\n\nYou can also attach extra attributes to plain functions (instead of using a class as I did above), but I think the syntax is a little uglier:\ndef foo():\n pass\nfoo.usage='Usage string'\nfoo.extra='Extra string'\n\nAnd, modules are objects too. They can have extra attributes just as easily:\nIf you define module constants\nUSAGE='''blah blah'''\nEXTRA='''meow'''\n\nThen when you import the module:\nimport mymodule\n\nYou can access the official and alternate docstrings with\nmymodule.__doc__\nmymodule.USAGE\nmymodule.EXTRA\n\n",
"You can replace the __doc__ attribute if you want to have more than one possible docstring, but please consider making the initial docstring flexible enough for all types.\n",
"Module is a collection of classes/functions/modules. So its docstring gives the intro about what it contains.\nClass docstring tells what the class is about and its methods docstrings tell what the methods so. A class serves one purpose and a methods does a single thing so they should have single docstring.\nFunctions do one thing so one doctring should suffice for them.\nI can't see what purpose will multiple docstrings suffice. Maybe your module is big. Divide into sub-modules and in the docstring for the module mention sub-modules.\n"
] |
[
5,
4,
3,
1,
1
] |
[] |
[] |
[
"docstring",
"python"
] |
stackoverflow_0002258696_docstring_python.txt
|
Q:
How to force an ImportError on development machine? (pwd module)
I'm trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils):
try:
import pwd
do stuff
except ImportError:
do other stuff
I want the import to fail, as it will on the actual GAE server, but the problem is that it doesn't fail on my development box (ubuntu). How to make it fail, given that the import is not in my own code?
A:
Even easier than messing with __import__ is just inserting None in the sys.modules dict:
>>> import sys
>>> sys.modules['pwd'] = None
>>> import pwd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pwd
A:
In your testing framework, before you cause docutils to be imported, you can perform this setup task:
import __builtin__
self.savimport = __builtin__.__import__
def myimport(name, *a):
if name=='pwd': raise ImportError
return self.savimport(name, *a)
__builtin__.__import__ = myimport
and of course in teardown put things back to normal:
__builtin__.__import__ = self.savimport
Explanation: all import operations go through __builtin__.__import__, and you can reassign that name to have such operations use your own code (alternatives such as import hooks are better for such purposes as performing import from non-filesystem sources, but for purposes such as yours, overriding __builtin__.__import__, as you see above, affords truly simple code).
|
How to force an ImportError on development machine? (pwd module)
|
I'm trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils):
try:
import pwd
do stuff
except ImportError:
do other stuff
I want the import to fail, as it will on the actual GAE server, but the problem is that it doesn't fail on my development box (ubuntu). How to make it fail, given that the import is not in my own code?
|
[
"Even easier than messing with __import__ is just inserting None in the sys.modules dict:\n>>> import sys\n>>> sys.modules['pwd'] = None\n>>> import pwd\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nImportError: No module named pwd\n\n",
"In your testing framework, before you cause docutils to be imported, you can perform this setup task:\nimport __builtin__\nself.savimport = __builtin__.__import__\ndef myimport(name, *a):\n if name=='pwd': raise ImportError\n return self.savimport(name, *a)\n__builtin__.__import__ = myimport\n\nand of course in teardown put things back to normal:\n__builtin__.__import__ = self.savimport\n\nExplanation: all import operations go through __builtin__.__import__, and you can reassign that name to have such operations use your own code (alternatives such as import hooks are better for such purposes as performing import from non-filesystem sources, but for purposes such as yours, overriding __builtin__.__import__, as you see above, affords truly simple code).\n"
] |
[
12,
4
] |
[] |
[] |
[
"google_app_engine",
"import",
"pwd",
"python",
"ubuntu"
] |
stackoverflow_0002258100_google_app_engine_import_pwd_python_ubuntu.txt
|
Q:
Extending a PIL decoder
I have a file which contains a single image of a specific format at a
specific offset. I can already get a file-like for the embedded image
which supports read(), seek(), and tell(). I want to take advantage
of an existing PIL decoder to handle the embedded image, but be able to
treat the entire file as an "image file" in its own right.
I have not been able to figure out how to do this given the
documentation
available and was wondering if anyone had any insights as to how I could
do this.
A:
The relevant chapter of the docs is this one and I think it's fairly clear: if for example you want to decode image files in the new .zap-format, you write a ZapImagePlugin.py module which must perform a couple things:
have a class ZapImageFile(ImageFile.ImageFile): with string attributes format and format_description, and a hook-method def _open(self) (of which more later);
at module level, Image.register_open('zap', ZapImageFile) and Image.register_extension('ZAP', '.zap')
The specs for the _open method are very clearly laid out in the chapter -- it must read image data and metadata from open binary file-like object self.fp, raise SyntaxError (or another exception) ASAP if it detects that the file's not actually in the right format, set at least self.size and self.mode attributes, and in order to allow reading the image, also self.tile, a list of tile descriptors again in the format specified in that chapter (including the file-offset, which you say you know, and a decoder -- if the raw or bit decoders, documented in the chapter, don't meet your needs, the chapter recommends studying the sources of some of the many supplied decoders, such as JPEG, PNG, etc).
A:
What I did to solve this was to derive from the ImageFile.ImageFile child belonging to the embedded format instead of ImageFile.ImageFile directly. Then in _open() I replaced self.fp with the file-like to the embedded image, and called the parent's _open(). I can't say that I'm particularly happy doing it this way, but it seems to have worked.
|
Extending a PIL decoder
|
I have a file which contains a single image of a specific format at a
specific offset. I can already get a file-like for the embedded image
which supports read(), seek(), and tell(). I want to take advantage
of an existing PIL decoder to handle the embedded image, but be able to
treat the entire file as an "image file" in its own right.
I have not been able to figure out how to do this given the
documentation
available and was wondering if anyone had any insights as to how I could
do this.
|
[
"The relevant chapter of the docs is this one and I think it's fairly clear: if for example you want to decode image files in the new .zap-format, you write a ZapImagePlugin.py module which must perform a couple things:\n\nhave a class ZapImageFile(ImageFile.ImageFile): with string attributes format and format_description, and a hook-method def _open(self) (of which more later);\nat module level, Image.register_open('zap', ZapImageFile) and Image.register_extension('ZAP', '.zap')\n\nThe specs for the _open method are very clearly laid out in the chapter -- it must read image data and metadata from open binary file-like object self.fp, raise SyntaxError (or another exception) ASAP if it detects that the file's not actually in the right format, set at least self.size and self.mode attributes, and in order to allow reading the image, also self.tile, a list of tile descriptors again in the format specified in that chapter (including the file-offset, which you say you know, and a decoder -- if the raw or bit decoders, documented in the chapter, don't meet your needs, the chapter recommends studying the sources of some of the many supplied decoders, such as JPEG, PNG, etc).\n",
"What I did to solve this was to derive from the ImageFile.ImageFile child belonging to the embedded format instead of ImageFile.ImageFile directly. Then in _open() I replaced self.fp with the file-like to the embedded image, and called the parent's _open(). I can't say that I'm particularly happy doing it this way, but it seems to have worked.\n"
] |
[
9,
4
] |
[] |
[] |
[
"python",
"python_imaging_library"
] |
stackoverflow_0002257318_python_python_imaging_library.txt
|
Q:
How to execute some code when a file is modified using python?
I want to execute one function each time a file gets written with new data (gets modified) and I'm using Python.
How can I do it?
A:
If you want to monitor for changes in the file system using Python, see this article for pointers to libraries which can help you achieve this on different platforms.
Short summary of available libraries for different platforms:
Windows: pywin32
OS X: pyKQueue
Linux: Gamin
Remember that your program needs to be running to handle file system events.
A:
I'm assuming that it's not necessarily your Python program that's modifying the file. I don't know if there's an OS-independent method. On Linux you can use pyinotify.
|
How to execute some code when a file is modified using python?
|
I want to execute one function each time a file gets written with new data (gets modified) and I'm using Python.
How can I do it?
|
[
"If you want to monitor for changes in the file system using Python, see this article for pointers to libraries which can help you achieve this on different platforms.\nShort summary of available libraries for different platforms:\n\nWindows: pywin32\nOS X: pyKQueue\nLinux: Gamin\n\nRemember that your program needs to be running to handle file system events.\n",
"I'm assuming that it's not necessarily your Python program that's modifying the file. I don't know if there's an OS-independent method. On Linux you can use pyinotify.\n"
] |
[
5,
2
] |
[] |
[] |
[
"execute",
"file",
"function",
"python"
] |
stackoverflow_0002259336_execute_file_function_python.txt
|
Q:
How can I know the path of the running script in Python?
My script.py creates a temporary file using a relative path.
When running it as:
python script.py
it works as expected.
But it doesn't work when you run it like:
python /path/to/script.py
The problem is that I don't know which path it will be running in. How can I get the absolute path to the script folder (the "/path/to") so the temporary file can be created in the same directory as the script?
What about the following?
os.path.abspath(os.path.dirname(__file__))
A:
Per the great Dive Into Python:
import sys, os
print 'sys.argv[0] =', sys.argv[0] 1
pathname = os.path.dirname(sys.argv[0]) 2
print 'path =', pathname
print 'full path =', os.path.abspath(pathname)
A:
The two current answers reflect the ambiguity of your question.
When you've run python /path/to/script.py, where do you want your tempfile? In the current directory (./tempfile.txt) or in /path/to/tempfile.txt?
If the former, you can simply use the relative path (or, for weird and arcane purposes, get the absolute path equivalent to the current directory as @Desintegr suggests, with os.getcwd).
If the latter, you can learn exactly how the script was invoked with sys.argv[0], as @Jonathan suggests, and manipulate that path with the functions in os.path (of course you can also apply those functions to what os.getcwd returns, if the former case applies), or work with os.path.dirname(__file__) and the like (the latter's necessary if you want this latter behavior also when the script is imported as a module, not just when it's run as a main script).
A:
You can use the os.getcwd() method to know the current working directory.
Return a string representing the current working directory.
Availability: Unix, Windows.
You can use the os.chdir(path) method to change the current working directory.
Change the current working directory to path.
Availability: Unix, Windows.
|
How can I know the path of the running script in Python?
|
My script.py creates a temporary file using a relative path.
When running it as:
python script.py
it works as expected.
But it doesn't work when you run it like:
python /path/to/script.py
The problem is that I don't know which path it will be running in. How can I get the absolute path to the script folder (the "/path/to") so the temporary file can be created in the same directory as the script?
What about the following?
os.path.abspath(os.path.dirname(__file__))
|
[
"Per the great Dive Into Python:\nimport sys, os\n\nprint 'sys.argv[0] =', sys.argv[0] 1\npathname = os.path.dirname(sys.argv[0]) 2\nprint 'path =', pathname\nprint 'full path =', os.path.abspath(pathname)\n\n",
"The two current answers reflect the ambiguity of your question.\nWhen you've run python /path/to/script.py, where do you want your tempfile? In the current directory (./tempfile.txt) or in /path/to/tempfile.txt?\nIf the former, you can simply use the relative path (or, for weird and arcane purposes, get the absolute path equivalent to the current directory as @Desintegr suggests, with os.getcwd).\nIf the latter, you can learn exactly how the script was invoked with sys.argv[0], as @Jonathan suggests, and manipulate that path with the functions in os.path (of course you can also apply those functions to what os.getcwd returns, if the former case applies), or work with os.path.dirname(__file__) and the like (the latter's necessary if you want this latter behavior also when the script is imported as a module, not just when it's run as a main script).\n",
"You can use the os.getcwd() method to know the current working directory.\n\nReturn a string representing the current working directory. \nAvailability: Unix, Windows.\n\nYou can use the os.chdir(path) method to change the current working directory.\n\nChange the current working directory to path. \nAvailability: Unix, Windows.\n\n"
] |
[
12,
8,
0
] |
[] |
[] |
[
"path",
"python"
] |
stackoverflow_0002259503_path_python.txt
|
Q:
Problem using cPickle
Could you helpme to make this exmaple work?
I'd like to load a serialized dict if it exists, modify it and dump it again. I think I have a problem with the mode I'm using to open the file but I don't know the correct way.
import os
import cPickle as pickle
if os.path.isfile('file.txt'):
cache_file = open('file.txt', 'rwb')
cache = pickle.load(cache_file)
else:
cache_file = open('file.txt', 'wb')
cache = dict.fromkeys([1,2,3])
# modifications of cache
pickle.dump(cache, cache_file)
cache_file.close()
Run it twice to see the error:
Traceback (most recent call last):
File "example.py", line 11, in <module>
pickle.dump(cache, cache_file)
IOError: [Errno 9] Bad file descriptor
A:
'rwb' is not correct file open mode for open(). Try 'r+b'.
And after you have read from file, you have cursor positioned at the end of file, so pickle.dump(cache, cache_file) will append to the file (which is probably not what you want). Try cache_file.seek(0) after pickle.load(cache_file).
A:
For each load, you need to open(with mode='rb'), load, and close the file handle.
For each dump, you need to open(with mode='wb'), dump, and close the file handle.
A:
You have opened the file for reading and writing - i.e. random access. When you initially read the file you leave the file index position at the end of the file, so when you later write the data back you are appending to the same file.
You should open the file in read mode, read the data, close it, then reopen in write mode.
|
Problem using cPickle
|
Could you helpme to make this exmaple work?
I'd like to load a serialized dict if it exists, modify it and dump it again. I think I have a problem with the mode I'm using to open the file but I don't know the correct way.
import os
import cPickle as pickle
if os.path.isfile('file.txt'):
cache_file = open('file.txt', 'rwb')
cache = pickle.load(cache_file)
else:
cache_file = open('file.txt', 'wb')
cache = dict.fromkeys([1,2,3])
# modifications of cache
pickle.dump(cache, cache_file)
cache_file.close()
Run it twice to see the error:
Traceback (most recent call last):
File "example.py", line 11, in <module>
pickle.dump(cache, cache_file)
IOError: [Errno 9] Bad file descriptor
|
[
"'rwb' is not correct file open mode for open(). Try 'r+b'.\nAnd after you have read from file, you have cursor positioned at the end of file, so pickle.dump(cache, cache_file) will append to the file (which is probably not what you want). Try cache_file.seek(0) after pickle.load(cache_file).\n",
"For each load, you need to open(with mode='rb'), load, and close the file handle.\nFor each dump, you need to open(with mode='wb'), dump, and close the file handle. \n",
"You have opened the file for reading and writing - i.e. random access. When you initially read the file you leave the file index position at the end of the file, so when you later write the data back you are appending to the same file.\nYou should open the file in read mode, read the data, close it, then reopen in write mode.\n"
] |
[
5,
4,
1
] |
[] |
[] |
[
"pickle",
"python"
] |
stackoverflow_0002259636_pickle_python.txt
|
Q:
Tool to convert python indentation from spaces to tabs?
I have a some .py files that use spaces for indentation, and I'd like to convert them to tabs.
I could easily hack together something using regexes, but I can think of several edge cases where this approach could fail. Is there a tool that does this by parsing the file and determining the indentation level the same way the python interpreter does?
A:
If there are not many files to convert, you can open them in vim, and use the :retab command.
See the vim documentation for more information.
A:
Python includes a script for the opposite (tabs to spaces). It's C:\Python24\Tools\Scripts\reindent.py for me
A:
:retab will swap tab with spaces, and :retab! will swap spaces with tab. 1 tab = 4 spaces, 4 spaces = 1 tab, depending on your tab setting.
A:
If you use Linux, you might also play around with unexpand:
Convert blanks in each FILE to tabs,
writing to standard output. With no
FILE, or when FILE is -, read standard
input.
A:
In emacs, M-x tabify will convert spaces to tabs where possible. You'll probably want to set the tab-width variable appropriately.
I don't know if this addresses your concern that spaces be interpreted in the same way as the python interpreter, but you could always load up python-mode and use M-x indent-region.
|
Tool to convert python indentation from spaces to tabs?
|
I have a some .py files that use spaces for indentation, and I'd like to convert them to tabs.
I could easily hack together something using regexes, but I can think of several edge cases where this approach could fail. Is there a tool that does this by parsing the file and determining the indentation level the same way the python interpreter does?
|
[
"If there are not many files to convert, you can open them in vim, and use the :retab command.\nSee the vim documentation for more information.\n",
"Python includes a script for the opposite (tabs to spaces). It's C:\\Python24\\Tools\\Scripts\\reindent.py for me\n",
":retab will swap tab with spaces, and :retab! will swap spaces with tab. 1 tab = 4 spaces, 4 spaces = 1 tab, depending on your tab setting.\n",
"If you use Linux, you might also play around with unexpand:\n\nConvert blanks in each FILE to tabs,\n writing to standard output. With no\n FILE, or when FILE is -, read standard\n input.\n\n",
"In emacs, M-x tabify will convert spaces to tabs where possible. You'll probably want to set the tab-width variable appropriately.\nI don't know if this addresses your concern that spaces be interpreted in the same way as the python interpreter, but you could always load up python-mode and use M-x indent-region.\n"
] |
[
17,
16,
12,
4,
3
] |
[] |
[] |
[
"indentation",
"python"
] |
stackoverflow_0000338767_indentation_python.txt
|
Q:
Request-Aware Code in Google App Engine -- os.environ?
In GAE, you can say users.get_current_user() to get the currently logged-in user implicit to the current request. This works even if multiple requests are being processed simultaneously -- the users module is somehow aware of which request the get_current_user function is being called on behalf of. I took a look into the code of the module in the development server, and it seems to be using os.environ to get the user email and other values associated to the current request.
Does this mean that every request gets an independent os.environ object?
I need to implement a service similar to users.get_current_user() that would return different values depending on the request being handled by the calling code. Assuming os.environ is the way to go, how do I know which variable names are already being used (or reserved) by GAE?
Also, is there a way to add a hook (or event handler) that gets called before every request?
A:
As the docs say,
A Python web app interacts with the
App Engine web server using the CGI
protocol.
This basically means exactly one request is being served at one time within any given process (although, differently from real CGI, one process can be serially reused for multiple requests, one after the other, if it defines main functions in the various modules to which app.yaml dispatches). See also this page, and this one for documentation of the environment variables CGI defines and uses.
The hooks App Engine defines are around calls at the RPC layer, not the HTTP requests. To intercept each request before it gets served, you could use app.yaml to redirect all requests to a single .py file and perform your interception in that file's main function before redirecting (or, you could call your hook at the start of the main in every module you're using app.yaml to dispatch to).
|
Request-Aware Code in Google App Engine -- os.environ?
|
In GAE, you can say users.get_current_user() to get the currently logged-in user implicit to the current request. This works even if multiple requests are being processed simultaneously -- the users module is somehow aware of which request the get_current_user function is being called on behalf of. I took a look into the code of the module in the development server, and it seems to be using os.environ to get the user email and other values associated to the current request.
Does this mean that every request gets an independent os.environ object?
I need to implement a service similar to users.get_current_user() that would return different values depending on the request being handled by the calling code. Assuming os.environ is the way to go, how do I know which variable names are already being used (or reserved) by GAE?
Also, is there a way to add a hook (or event handler) that gets called before every request?
|
[
"As the docs say, \n\nA Python web app interacts with the\n App Engine web server using the CGI\n protocol.\n\nThis basically means exactly one request is being served at one time within any given process (although, differently from real CGI, one process can be serially reused for multiple requests, one after the other, if it defines main functions in the various modules to which app.yaml dispatches). See also this page, and this one for documentation of the environment variables CGI defines and uses.\nThe hooks App Engine defines are around calls at the RPC layer, not the HTTP requests. To intercept each request before it gets served, you could use app.yaml to redirect all requests to a single .py file and perform your interception in that file's main function before redirecting (or, you could call your hook at the start of the main in every module you're using app.yaml to dispatch to).\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"python",
"request"
] |
stackoverflow_0002259727_google_app_engine_python_request.txt
|
Q:
Should I use the same url to login admins and other registred users in Django?
I am quite new to Django, so it may be a stupid question, but, nevertheless:
I need Django admin part to edit contents on the site, and also I want to have authentification, that will allow registred users to leave comments.
I have the following idea of implementation it: have 2 different tables(admins and other registred users) and use the /admin url to login in admin area and /login to login other users for leaving comments, etc.
Is this nice scheme? Or should I use the same url for all users, that will redirect admins to admin area?? What is the most simple way to implement this?
Examples of nice Django code are highly appreciated.
Thanks!
A:
"have 2 different tables(admins and other registred users)"
Bad idea. Django auth module has one user table. You can easily assign users to groups. Some groups have admin access to anything. Other groups can only leave comments. Read up on the auth module before you do anything more.
http://docs.djangoproject.com/en/dev/topics/auth/
"use the /admin url to login in admin area and /login to login other users for leaving comments, etc."
That's fine. Turns out, both with use the same authentication mechanism. Read this: http://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator
All view functions will use decorators to determine who's allowed to perform those functions.
|
Should I use the same url to login admins and other registred users in Django?
|
I am quite new to Django, so it may be a stupid question, but, nevertheless:
I need Django admin part to edit contents on the site, and also I want to have authentification, that will allow registred users to leave comments.
I have the following idea of implementation it: have 2 different tables(admins and other registred users) and use the /admin url to login in admin area and /login to login other users for leaving comments, etc.
Is this nice scheme? Or should I use the same url for all users, that will redirect admins to admin area?? What is the most simple way to implement this?
Examples of nice Django code are highly appreciated.
Thanks!
|
[
"\"have 2 different tables(admins and other registred users)\"\nBad idea. Django auth module has one user table. You can easily assign users to groups. Some groups have admin access to anything. Other groups can only leave comments. Read up on the auth module before you do anything more.\nhttp://docs.djangoproject.com/en/dev/topics/auth/\n\"use the /admin url to login in admin area and /login to login other users for leaving comments, etc.\" \nThat's fine. Turns out, both with use the same authentication mechanism. Read this: http://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator\nAll view functions will use decorators to determine who's allowed to perform those functions.\n"
] |
[
4
] |
[] |
[] |
[
"admin",
"architecture",
"authentication",
"django",
"python"
] |
stackoverflow_0002259747_admin_architecture_authentication_django_python.txt
|
Q:
Recommended Django Deployment
Short version: How do you deploy your Django servers? What application server, front-end (if any, and by front-end I mean reverse proxy), and OS do you run it on? Any input would be greatly appreciated, I'm quite a novice when it comes to Python and even more as a server administrator.
Long version:
I'm migrating between server hosts, so much for weekends... it's not all bad, though. I have the opportunity to move to a different, possibly better "deployment" of Django.
Currently I'm using Django through Tornado's WSGI interface with an nginx front-end on Debian Lenny. I'm looking to move into the Rackspace Cloud so I've been given quite a few choices when it comes to OS:
Debian 5.0 (Lenny)
FC 11 or 12
Ubuntu 9.10 or 8.04 (LTS)
CentOS 5.4
Gentoo 10.1
Arch Linux 2009.02
What I've gathered is this:
Linux Distributions
Debian and CentOS are very slow to release non-bugfix updates of software, since they focus mainly on stability. Is this good or bad? I can see stability being a good thing, but the fact that I can't get Python 2.6 without quite a headache of replacing Python 2.4 is kind of a turn-off--and if I do, then I'm stuck when it comes to ever hoping to use apt/yum to install a Python library (it'll try to reinstall Python 2.4).
Ubuntu and Fedora seem very... ready to go. Almost too ready to go, it's like everything it already done. I like to tinker with things and I prefer to know what's installed and how it's configured versus hitting the ground running with a "cookie-cutter" setup (no offense intended, it's just the best way to describe what I'm trying to say). I've been playing around with Fedora and I was pleasently surprised to find that pycurl, simplejson and a bunch of other libraries were already installed; that raised the question, though, what else is installed? I run a tight ship on a very small VPS, I prefer to run only what I need.
Then there's Gentoo... I've managed to install Gentoo on my desktop (took a week, almost) and ended up throwing it out after quite a few events where I wanted to do something and had to spend 45 minutes recompiling software with new USE flags so I can parse PNG's through PIL. I've wondered though, is Gentoo good for something "static" like a server? I know exactly what I'm going to be doing on my server, so USE flags will change next to never. It optimizes compiles to fit the needs of what you tell it to, and nothing more--something I could appreciate running on minimal RAM and HDD space. I've heard, though, that Gentoo has a tendency to break when you attempt to update the software on it... that more than anything else has kept me away from it for now.
I don't know anything about Arch Linux. Any opinions on this distro would be appreciated.
Web Server
I've been using Tornado and I can safely say it's been the biggest hassle to get running. I had to write my own script to prefork it since, at the time I setup this server, I was probably around 10% of Tornado's user-base (not counting FriendFeed). I have to then setup another "watchdog" program to make sure those forks don't misbehave. The good part is, though, it uses around 40MB of RAM to run all 7 of my Django powered sites; I liked that, I liked that a lot.
I've been using nginx as a front-end to Tornado, I could run nginx right in front of Django FastCGI workers, but those don't have the reliability of Tornado when you crank up the concurrency level. This isn't really an option for me, but I figured I might as well list it.
There's also Apache, which Django recommends you use through mod_wsgi. I personally don't like Apache that much, I understand it's very, very, very mature and what not, but it just seems so... fat, compared to nginx and lighttpd. Apache/mod_python isn't even an option, as I have very limited RAM.
Segue to Lighttpd! Not much to say here, I've never used it. I've heard you can run it in front of Apache/mod_wsgi or run it in front of Django FastCGI workers, also. I've heard it has minor memory leaking issues, I'm sure that could be solved with a cron job, though.
What I'm looking for is what you have seen as the "best" deployment of Django for your needs. Any input or clarifications of what I've said above would be more than welcome.
A:
Update your question to remove the choices that don't work. If it has Python 2.4, and an installation is a headache, just take it off the list, and update the question to list the real candidates. Only list the ones that actually fit your requirements. (You don't say what your requirements are, but minimal upgrades appears to be important.)
Toss a coin.
When choosing between two platforms which meet your requirements (which you haven't identified) tossing a coin is the absolute best way to choose.
If you're not sure if something matches your requirements, it's often good to enumerate what you value. So far, the only thing in the question that you seem to value is "no installations". Beyond that, I can only guess at what requirements you actually have.
Once you've identified the set of features you're looking for, feel free to toss a coin.
Note that Linux distributions all have more-or-less the same open-source code base. Choosing among them is a preference for packaging, support and selection of pre-integrated elements of the existing Linux code base. Just toss a coin.
Choosing among web front-ends is entirely a question of what features you require. Find all the web front-ends that meet your requirements and toss a coin to choose among them.
None of these are "lock-in" decisions. If you don't like the linux distro you chose initially, you can simply chose another. They all have the same basic suite of apps and the same API's. The choice is merely a matter of preference.
Don't like the web server you chose? At the end of the mod_wsgi pipe, they all appear the same to your Django app (plus or minus a few config changes). Don't like lighttpd? Switch to nginx or Apache -- your Django app doesn't change. So there's no lock-in and no negative consequences to making a sub-optimal choice.
When there's no down-side risk, just toss a coin.
A:
At the place I rent server, they have shaved down the Ubuntu images to bare minimum. Presumably because they had to make a special image anyway with just the right drivers and such in it, but I don't know exactly.
They have even removed wget and nano. So you get all the apt-get goodness and not a whole lot of "cookie-cutter" OS.
Just saying this because I would imagine that this is the way it is done almost everywhere and therefore playing around with a normal Ubuntu-server install will not provide you with the right information to make your decision.
Other than that, I agree with the others, that it is not much of a lock-in so you could just try something.
On the webserver-side I would suggest taking a look at cherokee, if have not done so already.
It might not be your cup of joe, but there is no harm in trying it.
I prefer the easy setup of both Ubuntu and Cherokee. Although I play around with a lot of things for fun, I prefer these for my business. I have other things to do than manage servers, so any solution that helps me do it faster, is just good. If these projects are mostly for fun then this will most likely not apply since you won't get a whole lot of experience from these easy-setup-with-nice-gui-and-very-helpfull-wizards
A:
If you want a lightweight alternative to Tornado, I'd suggest spawning. It's very good at code reloading and seems to have good performance - though of course best you try it out yourself.
I'd also recommend supervisord regardless of OS, for keeping Tornado or spawning instances up and running as well as any other essential services.
However 9 times out of 10 it's the database that's the bottleneck and choice of web server is not really going to impact site performance and scalability.
A:
Personally I find one of the BSD systems far superior to Linux distros for server related tasks. Give OpenBSD or perhaps FreeBSD a chance. Once you do you´ll never go back.
|
Recommended Django Deployment
|
Short version: How do you deploy your Django servers? What application server, front-end (if any, and by front-end I mean reverse proxy), and OS do you run it on? Any input would be greatly appreciated, I'm quite a novice when it comes to Python and even more as a server administrator.
Long version:
I'm migrating between server hosts, so much for weekends... it's not all bad, though. I have the opportunity to move to a different, possibly better "deployment" of Django.
Currently I'm using Django through Tornado's WSGI interface with an nginx front-end on Debian Lenny. I'm looking to move into the Rackspace Cloud so I've been given quite a few choices when it comes to OS:
Debian 5.0 (Lenny)
FC 11 or 12
Ubuntu 9.10 or 8.04 (LTS)
CentOS 5.4
Gentoo 10.1
Arch Linux 2009.02
What I've gathered is this:
Linux Distributions
Debian and CentOS are very slow to release non-bugfix updates of software, since they focus mainly on stability. Is this good or bad? I can see stability being a good thing, but the fact that I can't get Python 2.6 without quite a headache of replacing Python 2.4 is kind of a turn-off--and if I do, then I'm stuck when it comes to ever hoping to use apt/yum to install a Python library (it'll try to reinstall Python 2.4).
Ubuntu and Fedora seem very... ready to go. Almost too ready to go, it's like everything it already done. I like to tinker with things and I prefer to know what's installed and how it's configured versus hitting the ground running with a "cookie-cutter" setup (no offense intended, it's just the best way to describe what I'm trying to say). I've been playing around with Fedora and I was pleasently surprised to find that pycurl, simplejson and a bunch of other libraries were already installed; that raised the question, though, what else is installed? I run a tight ship on a very small VPS, I prefer to run only what I need.
Then there's Gentoo... I've managed to install Gentoo on my desktop (took a week, almost) and ended up throwing it out after quite a few events where I wanted to do something and had to spend 45 minutes recompiling software with new USE flags so I can parse PNG's through PIL. I've wondered though, is Gentoo good for something "static" like a server? I know exactly what I'm going to be doing on my server, so USE flags will change next to never. It optimizes compiles to fit the needs of what you tell it to, and nothing more--something I could appreciate running on minimal RAM and HDD space. I've heard, though, that Gentoo has a tendency to break when you attempt to update the software on it... that more than anything else has kept me away from it for now.
I don't know anything about Arch Linux. Any opinions on this distro would be appreciated.
Web Server
I've been using Tornado and I can safely say it's been the biggest hassle to get running. I had to write my own script to prefork it since, at the time I setup this server, I was probably around 10% of Tornado's user-base (not counting FriendFeed). I have to then setup another "watchdog" program to make sure those forks don't misbehave. The good part is, though, it uses around 40MB of RAM to run all 7 of my Django powered sites; I liked that, I liked that a lot.
I've been using nginx as a front-end to Tornado, I could run nginx right in front of Django FastCGI workers, but those don't have the reliability of Tornado when you crank up the concurrency level. This isn't really an option for me, but I figured I might as well list it.
There's also Apache, which Django recommends you use through mod_wsgi. I personally don't like Apache that much, I understand it's very, very, very mature and what not, but it just seems so... fat, compared to nginx and lighttpd. Apache/mod_python isn't even an option, as I have very limited RAM.
Segue to Lighttpd! Not much to say here, I've never used it. I've heard you can run it in front of Apache/mod_wsgi or run it in front of Django FastCGI workers, also. I've heard it has minor memory leaking issues, I'm sure that could be solved with a cron job, though.
What I'm looking for is what you have seen as the "best" deployment of Django for your needs. Any input or clarifications of what I've said above would be more than welcome.
|
[
"\nUpdate your question to remove the choices that don't work. If it has Python 2.4, and an installation is a headache, just take it off the list, and update the question to list the real candidates. Only list the ones that actually fit your requirements. (You don't say what your requirements are, but minimal upgrades appears to be important.)\nToss a coin. \n\nWhen choosing between two platforms which meet your requirements (which you haven't identified) tossing a coin is the absolute best way to choose.\nIf you're not sure if something matches your requirements, it's often good to enumerate what you value. So far, the only thing in the question that you seem to value is \"no installations\". Beyond that, I can only guess at what requirements you actually have.\nOnce you've identified the set of features you're looking for, feel free to toss a coin. \nNote that Linux distributions all have more-or-less the same open-source code base. Choosing among them is a preference for packaging, support and selection of pre-integrated elements of the existing Linux code base. Just toss a coin.\nChoosing among web front-ends is entirely a question of what features you require. Find all the web front-ends that meet your requirements and toss a coin to choose among them.\nNone of these are \"lock-in\" decisions. If you don't like the linux distro you chose initially, you can simply chose another. They all have the same basic suite of apps and the same API's. The choice is merely a matter of preference.\nDon't like the web server you chose? At the end of the mod_wsgi pipe, they all appear the same to your Django app (plus or minus a few config changes). Don't like lighttpd? Switch to nginx or Apache -- your Django app doesn't change. So there's no lock-in and no negative consequences to making a sub-optimal choice.\nWhen there's no down-side risk, just toss a coin.\n",
"At the place I rent server, they have shaved down the Ubuntu images to bare minimum. Presumably because they had to make a special image anyway with just the right drivers and such in it, but I don't know exactly.\nThey have even removed wget and nano. So you get all the apt-get goodness and not a whole lot of \"cookie-cutter\" OS.\nJust saying this because I would imagine that this is the way it is done almost everywhere and therefore playing around with a normal Ubuntu-server install will not provide you with the right information to make your decision.\nOther than that, I agree with the others, that it is not much of a lock-in so you could just try something.\nOn the webserver-side I would suggest taking a look at cherokee, if have not done so already.\nIt might not be your cup of joe, but there is no harm in trying it.\nI prefer the easy setup of both Ubuntu and Cherokee. Although I play around with a lot of things for fun, I prefer these for my business. I have other things to do than manage servers, so any solution that helps me do it faster, is just good. If these projects are mostly for fun then this will most likely not apply since you won't get a whole lot of experience from these easy-setup-with-nice-gui-and-very-helpfull-wizards\n",
"If you want a lightweight alternative to Tornado, I'd suggest spawning. It's very good at code reloading and seems to have good performance - though of course best you try it out yourself. \nI'd also recommend supervisord regardless of OS, for keeping Tornado or spawning instances up and running as well as any other essential services.\nHowever 9 times out of 10 it's the database that's the bottleneck and choice of web server is not really going to impact site performance and scalability. \n",
"Personally I find one of the BSD systems far superior to Linux distros for server related tasks. Give OpenBSD or perhaps FreeBSD a chance. Once you do you´ll never go back.\n"
] |
[
4,
3,
3,
0
] |
[] |
[] |
[
"deployment",
"django",
"linux",
"python",
"webserver"
] |
stackoverflow_0002256987_deployment_django_linux_python_webserver.txt
|
Q:
How should I display a constantly updating timer using PyGTK?
I am writing a timer program in Python using PyGTK. It is precise to the hundredths place. Right now, I am using a constantly updated label. This is a problem, because if I resize the window while the timer is running, Pango more often than not throws some crazy error and my program terminates. It's not always the same error, but different ones that I assume are some form of failed draw. Also, the label updates slower and slower as I increase the font size.
So, I am wondering if there is a more correct way to display the timer. Is there a more stable method than constantly updating a label?
A:
Updating a label should work perfectly reliably, so I suspect you're doing something else wrong. Are you using threads? What does your code look like? How small can you condense your program (by removing functionality, not by obfuscating the code), without making the problem go away?
A:
I figured out the problem. It was indeed a problem with the threads. I never would've guessed that myself. The trick is to use gobject.timeout_add() to create a timer instead of a threaded loop. Here is some information about gobject.timeout_add():
http://faq.pygtk.org/index.py?req=show&file=faq01.021.htp
Don't forget to have your function return True, or the timer will stop.
|
How should I display a constantly updating timer using PyGTK?
|
I am writing a timer program in Python using PyGTK. It is precise to the hundredths place. Right now, I am using a constantly updated label. This is a problem, because if I resize the window while the timer is running, Pango more often than not throws some crazy error and my program terminates. It's not always the same error, but different ones that I assume are some form of failed draw. Also, the label updates slower and slower as I increase the font size.
So, I am wondering if there is a more correct way to display the timer. Is there a more stable method than constantly updating a label?
|
[
"Updating a label should work perfectly reliably, so I suspect you're doing something else wrong. Are you using threads? What does your code look like? How small can you condense your program (by removing functionality, not by obfuscating the code), without making the problem go away?\n",
"I figured out the problem. It was indeed a problem with the threads. I never would've guessed that myself. The trick is to use gobject.timeout_add() to create a timer instead of a threaded loop. Here is some information about gobject.timeout_add():\n\nhttp://faq.pygtk.org/index.py?req=show&file=faq01.021.htp\n\nDon't forget to have your function return True, or the timer will stop.\n"
] |
[
2,
2
] |
[] |
[] |
[
"gtk",
"pango",
"pygtk",
"python"
] |
stackoverflow_0002259386_gtk_pango_pygtk_python.txt
|
Q:
sqlalchemy backref slow
Hi have have the following tables
nfiletable = Table(
'NFILE', base.metadata,
Column('fileid', Integer, primary_key=True),
Column('path', String(300)),
Column('filename', String(50)),
Column('filesize', Integer),
schema='NATIVEFILES')#,autoload=True,autoload_with=engine)
sheetnames_table=Table(
'SHEETNAMES', base.metadata, schema='NATIVEFILES',
autoload=True, autoload_with=engine)
nfile_sheet_table=Table(
'NFILE_SHEETNAME',base.metadata,
Column('fileid', Integer, ForeignKey(nfiletable.c.fileid)),
Column('sheetid', Integer, ForeignKey(sheetnames_table.c.sheet_id)),
schema='NATIVEFILES')
and mappers:
nfile_mapper=mapper(Nfile,nfiletable)
mapper(Sheet, sheetnames_table, properties={
'files': relation(
Nfile, secondary=nfile_sheet_table,
primaryjoin=(sheetnames_table.c.sheet_id==nfile_sheet_table.c.sheetid),
secondaryjoin=(nfile_sheet_table.c.fileid==nfiletable.c.fileid),
foreign_keys=[nfile_sheet_table.c.sheetid,nfile_sheet_table.c.fileid],
backref='sheets')
})
when i do the following
upl = Session.query(Nfile).filter_by(fileid=k).one()
sheetdb=[]
for sheet in sheetstoadd:
s = sheetcache[sheetname]
sheetdb.append(s)
upl.sheets = sheetdb
Session.save(upl)
Session.flush()
the line upl.sheets = sheetdb takes forever.
It seems that all files for each sheet in sheetdb are loaded from the db.
How can I prevent this?
A:
if NFile.sheets references a huge collection, put "lazy='dynamic'" on the backref:
mapper(Sheet, sheetnames_table, properties={
'files': relation(
Nfile, secondary=nfile_sheet_table,
backref=backref('sheets', lazy='dynamic'))
})
All the primaryjoin/secondaryjoin/foreign_keys stuff is also not needed since your nfile_sheet_table has ForeignKey constructs on it.
|
sqlalchemy backref slow
|
Hi have have the following tables
nfiletable = Table(
'NFILE', base.metadata,
Column('fileid', Integer, primary_key=True),
Column('path', String(300)),
Column('filename', String(50)),
Column('filesize', Integer),
schema='NATIVEFILES')#,autoload=True,autoload_with=engine)
sheetnames_table=Table(
'SHEETNAMES', base.metadata, schema='NATIVEFILES',
autoload=True, autoload_with=engine)
nfile_sheet_table=Table(
'NFILE_SHEETNAME',base.metadata,
Column('fileid', Integer, ForeignKey(nfiletable.c.fileid)),
Column('sheetid', Integer, ForeignKey(sheetnames_table.c.sheet_id)),
schema='NATIVEFILES')
and mappers:
nfile_mapper=mapper(Nfile,nfiletable)
mapper(Sheet, sheetnames_table, properties={
'files': relation(
Nfile, secondary=nfile_sheet_table,
primaryjoin=(sheetnames_table.c.sheet_id==nfile_sheet_table.c.sheetid),
secondaryjoin=(nfile_sheet_table.c.fileid==nfiletable.c.fileid),
foreign_keys=[nfile_sheet_table.c.sheetid,nfile_sheet_table.c.fileid],
backref='sheets')
})
when i do the following
upl = Session.query(Nfile).filter_by(fileid=k).one()
sheetdb=[]
for sheet in sheetstoadd:
s = sheetcache[sheetname]
sheetdb.append(s)
upl.sheets = sheetdb
Session.save(upl)
Session.flush()
the line upl.sheets = sheetdb takes forever.
It seems that all files for each sheet in sheetdb are loaded from the db.
How can I prevent this?
|
[
"if NFile.sheets references a huge collection, put \"lazy='dynamic'\" on the backref:\nmapper(Sheet, sheetnames_table, properties={\n 'files': relation(\n Nfile, secondary=nfile_sheet_table,\n backref=backref('sheets', lazy='dynamic'))\n})\n\nAll the primaryjoin/secondaryjoin/foreign_keys stuff is also not needed since your nfile_sheet_table has ForeignKey constructs on it.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0002231324_python_sqlalchemy.txt
|
Q:
SQLAlchemy getting column data types of query results
from sqlalchemy import create_engine, MetaData, ForeignKey
engine = create_engine("mysql://user:passwd@localhost/shema", echo=False)
meta = MetaData(engine, True)
conn = engine.connect()
tb_list = meta.tables["tb_list"]
tb_data = meta.tables["tb_data"]
tb_list.c.i_data.append_foreign_key( ForeignKey(tb_data.c.i_id) )
q = tb_list.outerjoin(tb_data).select()
res = conn.execute(q)
And now, how can I get columns type of query result res
One of decisions:
res._key_cache[ col_name ][0]
Do you know something else ?
A:
you'd say:
types = [col.type for col in q.columns]
the (compiled) statement is on the result too if you feel like digging:
types = [col.type for col in res.context.compiled.statement.columns]
if you want the DBAPI version of the types, which is a little more varied based on DBAPI:
types = [elem[1] for elem in res.cursor.description]
maybe we'll look into adding this kind of metadata more directly to the ResultProxy.
|
SQLAlchemy getting column data types of query results
|
from sqlalchemy import create_engine, MetaData, ForeignKey
engine = create_engine("mysql://user:passwd@localhost/shema", echo=False)
meta = MetaData(engine, True)
conn = engine.connect()
tb_list = meta.tables["tb_list"]
tb_data = meta.tables["tb_data"]
tb_list.c.i_data.append_foreign_key( ForeignKey(tb_data.c.i_id) )
q = tb_list.outerjoin(tb_data).select()
res = conn.execute(q)
And now, how can I get columns type of query result res
One of decisions:
res._key_cache[ col_name ][0]
Do you know something else ?
|
[
"you'd say:\ntypes = [col.type for col in q.columns]\n\nthe (compiled) statement is on the result too if you feel like digging:\ntypes = [col.type for col in res.context.compiled.statement.columns]\n\nif you want the DBAPI version of the types, which is a little more varied based on DBAPI:\ntypes = [elem[1] for elem in res.cursor.description]\n\nmaybe we'll look into adding this kind of metadata more directly to the ResultProxy.\n"
] |
[
17
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0002258072_python_sqlalchemy.txt
|
Q:
Issue with links Embedding the app engine's shell app within my own app, for help coding
In my own App Engine App, at the browser, I wanted to mess around with new code by simulating having access to the python interpretor's >> within a browser window by embedding this app --> http://shell.appspot.com/ .
One can get shell_20091112.tar.gz at http://code.google.com/p/google-app-engine-samples/downloads/detail?name=shell_20091112.tar.gz&can=2&q=
So I moved the key files and folder from the shell app into my own app directory.
When I launch my app from the SDK I can see in the browser the shell app at
http://dwms.appspot.com/shell
in my app but after I hit 'enter' after writing something say >>a=1...
then nothing happens , so assume my handler link from the form to my app is wrong? (sorry if I am getting the jargon incorrect).
The form I am supposed to be receiving information from is within shell.html as looks like below:
<form id="form" action="shell.do" method="get">
<nobr>
<textarea class="prompt" id="caret" readonly="readonly" rows="4"
onfocus="document.getElementById('statement').focus()"
>>>></textarea>
<textarea class="prompt" name="statement" id="statement" rows="4"
onkeypress="return shell.onPromptKeyPress(event);"></textarea>
</nobr>
<input type="hidden" name="session" value="{{ session }}" />
<input type="submit" style="display: none" />
</form>
so I am thinking the problem is that my app is no responding when the server gets 'shell.do' from the client because of changes I made or didnt make or made incorrectly....
on the old shell.py that I copied off the web into my app's directory I commented out all the lines from the main() function:
#def main():
#application = webapp.WSGIApplication(
#[('/shell', FrontPageHandler),
#('/shell/shell.do', StatementHandler)], debug=_DEBUG)
#wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
#main()
and replaced the linking or plumbing information by adding those similar links to my own main.py as follows:
application = webapp.WSGIApplication(
[('/', MainPage),
('/shell',shell.FrontPageHandler),
('shell.do', shell.StatementHandler),
('/sign', Guestbook),
('/zxy/.*', PNGserver) ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
again -- so right now the issue is that I see a shell app when I go to
http://dwms.appspot.com/shell
and type
>> a=10
but nothing happens after I enter statements into the form after >>a=10
In case it is relevant...Below you will notice that I also commented out some lines I copied from the the old shell's app handlers app.yaml into the app.yaml of my app..NOTE: After experimenting by uncommenting the below lines it made no difference in how the shell doesn't work in my app...The reason for the comments below is that I thought this might be needed for the shell to know what's is going on with all global variables in the entire app not just where the shell is running? (I might be confused about this?)
My app.yaml is below:
application: dwms
version: 1
runtime: python
api_version: 1
handlers:
- url: /stylesheets
static_dir: stylesheets
- url: /.*
script: main.py
- url: /static
static_dir: static
expiration: 1d
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
# if you're adding the shell to your own app, change this regex url to the URL
# endpoint where you want the shell to run, e.g. /shell . You'll also probably
# want to add login: admin to restrict to admins only.
#
#- url: /shell
# script: shell.py
A:
The answer to my own question is to install the following shell console, very easy, and looks very helpful:
http://con.appspot.com/console/help/about
|
Issue with links Embedding the app engine's shell app within my own app, for help coding
|
In my own App Engine App, at the browser, I wanted to mess around with new code by simulating having access to the python interpretor's >> within a browser window by embedding this app --> http://shell.appspot.com/ .
One can get shell_20091112.tar.gz at http://code.google.com/p/google-app-engine-samples/downloads/detail?name=shell_20091112.tar.gz&can=2&q=
So I moved the key files and folder from the shell app into my own app directory.
When I launch my app from the SDK I can see in the browser the shell app at
http://dwms.appspot.com/shell
in my app but after I hit 'enter' after writing something say >>a=1...
then nothing happens , so assume my handler link from the form to my app is wrong? (sorry if I am getting the jargon incorrect).
The form I am supposed to be receiving information from is within shell.html as looks like below:
<form id="form" action="shell.do" method="get">
<nobr>
<textarea class="prompt" id="caret" readonly="readonly" rows="4"
onfocus="document.getElementById('statement').focus()"
>>>></textarea>
<textarea class="prompt" name="statement" id="statement" rows="4"
onkeypress="return shell.onPromptKeyPress(event);"></textarea>
</nobr>
<input type="hidden" name="session" value="{{ session }}" />
<input type="submit" style="display: none" />
</form>
so I am thinking the problem is that my app is no responding when the server gets 'shell.do' from the client because of changes I made or didnt make or made incorrectly....
on the old shell.py that I copied off the web into my app's directory I commented out all the lines from the main() function:
#def main():
#application = webapp.WSGIApplication(
#[('/shell', FrontPageHandler),
#('/shell/shell.do', StatementHandler)], debug=_DEBUG)
#wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
#main()
and replaced the linking or plumbing information by adding those similar links to my own main.py as follows:
application = webapp.WSGIApplication(
[('/', MainPage),
('/shell',shell.FrontPageHandler),
('shell.do', shell.StatementHandler),
('/sign', Guestbook),
('/zxy/.*', PNGserver) ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
again -- so right now the issue is that I see a shell app when I go to
http://dwms.appspot.com/shell
and type
>> a=10
but nothing happens after I enter statements into the form after >>a=10
In case it is relevant...Below you will notice that I also commented out some lines I copied from the the old shell's app handlers app.yaml into the app.yaml of my app..NOTE: After experimenting by uncommenting the below lines it made no difference in how the shell doesn't work in my app...The reason for the comments below is that I thought this might be needed for the shell to know what's is going on with all global variables in the entire app not just where the shell is running? (I might be confused about this?)
My app.yaml is below:
application: dwms
version: 1
runtime: python
api_version: 1
handlers:
- url: /stylesheets
static_dir: stylesheets
- url: /.*
script: main.py
- url: /static
static_dir: static
expiration: 1d
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
# if you're adding the shell to your own app, change this regex url to the URL
# endpoint where you want the shell to run, e.g. /shell . You'll also probably
# want to add login: admin to restrict to admins only.
#
#- url: /shell
# script: shell.py
|
[
"The answer to my own question is to install the following shell console, very easy, and looks very helpful:\nhttp://con.appspot.com/console/help/about\n"
] |
[
1
] |
[] |
[] |
[
"google_app_engine",
"httphandler",
"python"
] |
stackoverflow_0002235080_google_app_engine_httphandler_python.txt
|
Q:
How can I preserve or identify a caller's stack frame?
My brain feels slow today.
I'm writing pre/post/invariants in Python using decorators. Currently, I need each call to specify the locals and globals for context, and this feels ugly. Is there a way to get the locals and globals from the decorator application level even though it's an arbitrary depth.
That is, I'm trying to make this ugly code:
from dectools import invariant, pre, post, call_if
@invariant("self.price >= 0 and self.inventory >= 0 and Item.tax_rate >= 0")
class Item(object):
tax_rate = 0.10 # California. No property taxes on old property.
@post("ItemDB.fetch(self) = (name, price)", locals(), globals())
def __init__(self, name, price):
self.name = name
self.price = price
self.total_sold = 0
self.inventory = 0
@call_if(check_level, "manager")
@post("self.total_sold > 0", locals(), globals())
@pre("discount > 0 and discount <= self.price * 0.50", locals(), globals())
def adjust_price(self, adjustment):
....
into the same ugly code without all the "locals(), globals()". I run into problems where the nested decorators give me arbitrary stack depths, so my implementation of dectools.pre couldn't grab from a constant depth sys._getframe(). The stack is not something I've played with much, and would appreciate it if someone has a trick. (Yes, I'm hacking the local variables into the locals by assuming self will be in the right stack frame. It's the Item.tax_rate that is always out of scope, and self, and ItemDB.)
Thank you in advance,
Charles
A:
If you can access self.total_sold, you can access self.tax_rate (which is the same thing as Item.tax_rate unless you stomp on it -- so you just don't stomp of it, keep the tax rate as a pristine class variable, and access it through self.!-). That would be much more solid than mucking through the stack, especially with nested decorators in the picture, which more or less guarantees fragile, specific-version-dependent code (stack introspection is meant to be used for debugging purposes, essentially, not for production purposes).
|
How can I preserve or identify a caller's stack frame?
|
My brain feels slow today.
I'm writing pre/post/invariants in Python using decorators. Currently, I need each call to specify the locals and globals for context, and this feels ugly. Is there a way to get the locals and globals from the decorator application level even though it's an arbitrary depth.
That is, I'm trying to make this ugly code:
from dectools import invariant, pre, post, call_if
@invariant("self.price >= 0 and self.inventory >= 0 and Item.tax_rate >= 0")
class Item(object):
tax_rate = 0.10 # California. No property taxes on old property.
@post("ItemDB.fetch(self) = (name, price)", locals(), globals())
def __init__(self, name, price):
self.name = name
self.price = price
self.total_sold = 0
self.inventory = 0
@call_if(check_level, "manager")
@post("self.total_sold > 0", locals(), globals())
@pre("discount > 0 and discount <= self.price * 0.50", locals(), globals())
def adjust_price(self, adjustment):
....
into the same ugly code without all the "locals(), globals()". I run into problems where the nested decorators give me arbitrary stack depths, so my implementation of dectools.pre couldn't grab from a constant depth sys._getframe(). The stack is not something I've played with much, and would appreciate it if someone has a trick. (Yes, I'm hacking the local variables into the locals by assuming self will be in the right stack frame. It's the Item.tax_rate that is always out of scope, and self, and ItemDB.)
Thank you in advance,
Charles
|
[
"If you can access self.total_sold, you can access self.tax_rate (which is the same thing as Item.tax_rate unless you stomp on it -- so you just don't stomp of it, keep the tax rate as a pristine class variable, and access it through self.!-). That would be much more solid than mucking through the stack, especially with nested decorators in the picture, which more or less guarantees fragile, specific-version-dependent code (stack introspection is meant to be used for debugging purposes, essentially, not for production purposes).\n"
] |
[
2
] |
[] |
[] |
[
"decorator",
"python",
"stack"
] |
stackoverflow_0002260029_decorator_python_stack.txt
|
Q:
Simple Python Regex Find pattern
I have a sentence. I want to find all occurrences of a word that start with a specific character in that sentence. I am very new to programming and Python, but from the little I know, this sounds like a Regex question.
What is the pattern match code that will let me find all words that match my pattern?
Many thanks in advance,
Brock
A:
import re
print re.findall(r'\bv\w+', thesentence)
will print every word in the sentence that starts with 'v', for example.
Using the split method of strings, as another answer suggests, would not identify words, but space-separated chunks that may include punctuation. This re-based solution does identify words (letters and digits, net of punctuation).
A:
I second the Dive Into Python recommendation. But it's basically:
m = re.findall(r'\bf.*?\b', 'a fast and friendly dog')
print(m)
\b means word boundary, and .*? ensures we store the whole word, but back off to avoid going too far (technically, ? is called a lazy operator).
A:
>>> sentence="a quick brown fox for you"
>>> pattern="fo"
>>> for word in sentence.split():
... if word.startswith(pattern):
... print word
...
fox
for
Split the sentence on spaces, use a loop to search for the pattern and print them out.
A:
You could do (doesn't use re though):
matching_words = [x for x in sentence.split() if x.startswith(CHAR_TO_FIND)]
Regular expressions work too (see the other answers) but I think this solution will be a little more readable, and as a beginner learning Python, you'll find list comprehensions (like the solution above) important to gain a comfort level with.
A:
import re
s = "Your sentence that contains the word ROAD"
s = re.sub(r'\bROAD', 'RD.', s)
print s
Read: http://diveintopython3.org/regular-expressions.html
|
Simple Python Regex Find pattern
|
I have a sentence. I want to find all occurrences of a word that start with a specific character in that sentence. I am very new to programming and Python, but from the little I know, this sounds like a Regex question.
What is the pattern match code that will let me find all words that match my pattern?
Many thanks in advance,
Brock
|
[
"import re\nprint re.findall(r'\\bv\\w+', thesentence)\n\nwill print every word in the sentence that starts with 'v', for example.\nUsing the split method of strings, as another answer suggests, would not identify words, but space-separated chunks that may include punctuation. This re-based solution does identify words (letters and digits, net of punctuation).\n",
"I second the Dive Into Python recommendation. But it's basically:\nm = re.findall(r'\\bf.*?\\b', 'a fast and friendly dog')\nprint(m)\n\n\\b means word boundary, and .*? ensures we store the whole word, but back off to avoid going too far (technically, ? is called a lazy operator).\n",
">>> sentence=\"a quick brown fox for you\"\n>>> pattern=\"fo\"\n>>> for word in sentence.split():\n... if word.startswith(pattern):\n... print word\n...\nfox\nfor\n\nSplit the sentence on spaces, use a loop to search for the pattern and print them out.\n",
"You could do (doesn't use re though):\nmatching_words = [x for x in sentence.split() if x.startswith(CHAR_TO_FIND)]\n\nRegular expressions work too (see the other answers) but I think this solution will be a little more readable, and as a beginner learning Python, you'll find list comprehensions (like the solution above) important to gain a comfort level with.\n",
"import re\n\ns = \"Your sentence that contains the word ROAD\"\ns = re.sub(r'\\bROAD', 'RD.', s)\n\nprint s\n\nRead: http://diveintopython3.org/regular-expressions.html\n"
] |
[
21,
3,
2,
2,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002260105_python_regex.txt
|
Q:
python mapping with strings
I implemented a version of the str_replace function available in php using python. Here is my original code that didn't work
def replacer(items,str,repl):
return "".join(map(lambda x:repl if x in items else x,str))
test = "hello world"
print test
test = replacer(test,['e','l','o'],'?')
print test
but this prints out
hello world
???
the code i got to do as expected is
def replacer(str,items,repl):
x = "".join(map(lambda x:repl if x in items else x,str))
return x
test = "hello world"
print test
test = replacer(test,['e','l','o'],'?')
print test
which prints out
hello world
h???? w?r?d
just like I wanted it to.
Aside from the fact that there is probably a way using builtins that i haven't seen yet, why does the first way fail and the second way do what I need it to?
A:
The ordering of the arguments to replacer is what makes the difference between the two. If you changed the argument ordering in the first version it'd behave like the second version.
A:
Don't use built-in names such as str for your own identifiers, that's just asking for trouble and has no benefit whatsoever.
Apart from that, your first version is looping on str, the second argument -- the list ['e', 'l', 'o'] -- so of course it will return a string of exactly three items -- how could you expect it to return a string of any other length?! Using str to name a list argument is particularly perverse and bug-prone.
The second version loops on str, the first argument -- the string 'hello world' so of course it's returning a string of that length.
A:
You're passing it in backwards in the first one. It should be should be
test = replacer(['e','l','o'], test, '?')
|
python mapping with strings
|
I implemented a version of the str_replace function available in php using python. Here is my original code that didn't work
def replacer(items,str,repl):
return "".join(map(lambda x:repl if x in items else x,str))
test = "hello world"
print test
test = replacer(test,['e','l','o'],'?')
print test
but this prints out
hello world
???
the code i got to do as expected is
def replacer(str,items,repl):
x = "".join(map(lambda x:repl if x in items else x,str))
return x
test = "hello world"
print test
test = replacer(test,['e','l','o'],'?')
print test
which prints out
hello world
h???? w?r?d
just like I wanted it to.
Aside from the fact that there is probably a way using builtins that i haven't seen yet, why does the first way fail and the second way do what I need it to?
|
[
"The ordering of the arguments to replacer is what makes the difference between the two. If you changed the argument ordering in the first version it'd behave like the second version.\n",
"Don't use built-in names such as str for your own identifiers, that's just asking for trouble and has no benefit whatsoever.\nApart from that, your first version is looping on str, the second argument -- the list ['e', 'l', 'o'] -- so of course it will return a string of exactly three items -- how could you expect it to return a string of any other length?! Using str to name a list argument is particularly perverse and bug-prone.\nThe second version loops on str, the first argument -- the string 'hello world' so of course it's returning a string of that length.\n",
"You're passing it in backwards in the first one. It should be should be \ntest = replacer(['e','l','o'], test, '?')\n\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"lambda",
"map",
"python",
"string"
] |
stackoverflow_0002260148_lambda_map_python_string.txt
|
Q:
wxPython - PaintDC not refreshing
import wx
class TestDraw(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id)
self.SetBackgroundColour("#FFFFFF")
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self, event):
event.Skip()
dc=wx.PaintDC(self)
dc.BeginDrawing()
width=dc.GetSize()[0]
height=dc.GetSize()[1]
if height<width:
self.drawTestRects(dc)
else:
dc.Clear()
dc.EndDrawing()
def drawTestRects(self,dc):
dc.SetBrush(wx.Brush("#000000",style=wx.SOLID))
dc.DrawRectangle(50,50,50,50)
dc.DrawRectangle(100,100,100,100)
class TestFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=TestDraw(self,-1)
self.Show(True)
app = wx.App(False)
frame = TestFrame(None,"Test App")
app.MainLoop()
This code should draw the test rectangles only when the height is less than the width, and otherwise the window should remain clear. However, if you mess with resizing the window, the panel isn't actually redrawn unless it is moved off the window. What am I doing wrong?
A:
You can bind a method to handle wx.EVT_SIZE or the panel and invalidate it there. Alternatively simply use the wx.FULL_REPAINT_ON_RESIZE for the panel.
A:
The documentation for a SizeEvent claims that there may be some complications when drawing depends on the dimensions of the window. I do not know exactly what is going on behind the scenes. I followed the suggestion on the link and added the call self.Refresh() to the top of onPaint() and this seems to give the desired behavior. See mghie's answer for a more efficient example of working code.
|
wxPython - PaintDC not refreshing
|
import wx
class TestDraw(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id)
self.SetBackgroundColour("#FFFFFF")
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self, event):
event.Skip()
dc=wx.PaintDC(self)
dc.BeginDrawing()
width=dc.GetSize()[0]
height=dc.GetSize()[1]
if height<width:
self.drawTestRects(dc)
else:
dc.Clear()
dc.EndDrawing()
def drawTestRects(self,dc):
dc.SetBrush(wx.Brush("#000000",style=wx.SOLID))
dc.DrawRectangle(50,50,50,50)
dc.DrawRectangle(100,100,100,100)
class TestFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=TestDraw(self,-1)
self.Show(True)
app = wx.App(False)
frame = TestFrame(None,"Test App")
app.MainLoop()
This code should draw the test rectangles only when the height is less than the width, and otherwise the window should remain clear. However, if you mess with resizing the window, the panel isn't actually redrawn unless it is moved off the window. What am I doing wrong?
|
[
"You can bind a method to handle wx.EVT_SIZE or the panel and invalidate it there. Alternatively simply use the wx.FULL_REPAINT_ON_RESIZE for the panel. \n",
"The documentation for a SizeEvent claims that there may be some complications when drawing depends on the dimensions of the window. I do not know exactly what is going on behind the scenes. I followed the suggestion on the link and added the call self.Refresh() to the top of onPaint() and this seems to give the desired behavior. See mghie's answer for a more efficient example of working code.\n"
] |
[
2,
0
] |
[] |
[] |
[
"graphics",
"python",
"user_interface",
"wxpython"
] |
stackoverflow_0002260142_graphics_python_user_interface_wxpython.txt
|
Q:
Django/Python: < comes up as < when I import it from the model object
Revised question:
In my dbms, I'm storing the literal <<<firefox-image>>>, I confirmed in Navicat and Mysql CLI that its <<<firefox-image>>>. When I use the Python shell and try to grab the same article entry, the outer <>'s get converted to < and <, respectively.
Snippet of me testing:
>>> entry = Entry.objects.filter( pub_date__lte = datetime.datetime.now() ).filter(featured=1)[0].excerpt_html
>>> entry
u'<p>\u0432\u0430\u043d.\n<<<firefox-image>>></p>'
How can I get it to use the literal < and >?
Original question:
In my template I did this:
{{ entry.excerpt_html|safe|render_uploads }}
it complained at the render_uploads because I didnt load adminfiles, so I prepended
{% load adminfiles_tags %}
The error went away, but in my article excerpt it still renders <<<firefox-image>>> as <<firefox-image>>.
A:
I'm a dumbass - I forgot to invoke render_uploads before storing it.
return markdown(render_uploads(markup))
A:
I can't duplicate that symptom; the fact that you have only two less-than and greater-thans on each side makes me wonder if your inline syntax is wrong? Are there definitely three on either side in your content area?
Otherwise, I think I'd need to see more of the relevant code.
|
Django/Python: < comes up as < when I import it from the model object
|
Revised question:
In my dbms, I'm storing the literal <<<firefox-image>>>, I confirmed in Navicat and Mysql CLI that its <<<firefox-image>>>. When I use the Python shell and try to grab the same article entry, the outer <>'s get converted to < and <, respectively.
Snippet of me testing:
>>> entry = Entry.objects.filter( pub_date__lte = datetime.datetime.now() ).filter(featured=1)[0].excerpt_html
>>> entry
u'<p>\u0432\u0430\u043d.\n<<<firefox-image>>></p>'
How can I get it to use the literal < and >?
Original question:
In my template I did this:
{{ entry.excerpt_html|safe|render_uploads }}
it complained at the render_uploads because I didnt load adminfiles, so I prepended
{% load adminfiles_tags %}
The error went away, but in my article excerpt it still renders <<<firefox-image>>> as <<firefox-image>>.
|
[
"I'm a dumbass - I forgot to invoke render_uploads before storing it.\nreturn markdown(render_uploads(markup))\n\n",
"I can't duplicate that symptom; the fact that you have only two less-than and greater-thans on each side makes me wonder if your inline syntax is wrong? Are there definitely three on either side in your content area?\nOtherwise, I think I'd need to see more of the relevant code.\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"python",
"unicode"
] |
stackoverflow_0002259844_django_python_unicode.txt
|
Q:
Regex try and match until hitting end tag in python
I'm looking for a bit of help with a regex in python and google is failing me. Basically I'm searching some html and there is a certain type of table I'm searching for, specifically any table that includes a background tag in it (i.e. BGCOLOR). Some tables have this tag and some do not. Could someone help me out with how to write a regex that searches for the start of the table, then searches for the BGCOLOR but if it hits the end of the table then it stops and moves on?
Here's a very simplified example that will server the purpose:
`<TABLE>
<B>Item 1.</B>
</TABLE>
<TABLE>
BGCOLOR
</TABLE>
<TABLE>
<B>Item 2.</B>
</TABLE>`
So we have three tables but I'm only interested in finding the middle table that contains 'BGCOLOR'
The problem with my regex at the moment is that it searches for the starting table tag then looks for 'BGCOLOR' and doesn't care if it passes the table end tag:
tables = re.findall('\<table.*?BGCOLOR=".*?".*?\<\/table\>', text, re.I|re.S)
So it would find the first two tables instead of just the second table. Let me know if anyone knows how to handle this situation.
Thanks,
Michael
A:
Don't use a regular expression to parse HTML. Use lxml or BeautifulSoup.
A:
Don't use regular expressions to parse HTML -- use an HTML parser, such as BeautifulSoup.
Specifically, your situation is basically one of having to deal with "nested parentheses" (where an open "parens" is an opening <table> tag and the corresponding closed parens is the matching </table>) -- exactly the kind of parsing tasks that regular expressions can't perform well. Lots of the work in parsing HTML is exactly connected with this "matched parentheses" issue, which makes regular expressions a perfectly horrible choice for the purpose.
You mention in a comment to another answer that you've had unspecified problems with BS -- I suspect you were trying the latest, 3.1 release (which has gone downhill) instead of the right one; try 3.0.8 instead, as BS's own docs recommend, and you could be better off.
If you've made some kind of pact with Evil never to use the right tool for the job, your task might not be totally impossible if you don't need to deal with nesting (just matching), i.e., there is never a table inside another table. In this case you can identify one table with r'<\s*TABLE(.*?)<\s*/\s*TABLE' (with suitable flags such as re.DOTALL and re.I); loop over all such matches with the finditer method of regular expressions; and in the loop's body check whether BGCOLOR (in a case-insensitive sense) happens to be inside the body of the current match. It's still going to be more fragile, and more work, than using an HTML parser, but while definitely an inferior choice it needs not be a desperate situation.
If you do have nested tables to contend with, then it is a desperate situation.
A:
if your task is just this simple, here's a way. split on <TABLE> then iterate the items and find the required pattern you want.
myhtml="""
<TABLE>
<B>Item 1.</B>
</TABLE>
some text1
some text2
some text3
<TABLE>
blah
BGCOLOR
blah
</TABLE>
some texet
<TABLE>
<B>Item 2.</B>
</TABLE>
"""
for tab in myhtml.split("</TABLE>"):
if "<TABLE>" in tab and "BGCOLOR" in tab:
print ''.join(tab.split("<TABLE>")[1:])
output
$ ./python.py
blah
BGCOLOR
blah
A:
Here's the code that ended up working for me. It finds the correct table and adds more tagging around it so that it is identified from the group with open and close tags of 'realTable'.
soup = BeautifulSoup(''.join(text))
for p in soup.findAll('table'):
pattern = '.*BGCOLOR.*'
if (re.match(pattern, str(p), re.S|re.I)):
tags = Tag(soup, "realTable")
p.replaceWith(tags)
text = NavigableString(str(p))
tags.insert(0, text)
print soup
prints this out:
<table><b>Item 1.</b></table>
<realTable><table>blah BGCOLOR blah</table></realTable>
<table><b>Item 2.</b></table>
|
Regex try and match until hitting end tag in python
|
I'm looking for a bit of help with a regex in python and google is failing me. Basically I'm searching some html and there is a certain type of table I'm searching for, specifically any table that includes a background tag in it (i.e. BGCOLOR). Some tables have this tag and some do not. Could someone help me out with how to write a regex that searches for the start of the table, then searches for the BGCOLOR but if it hits the end of the table then it stops and moves on?
Here's a very simplified example that will server the purpose:
`<TABLE>
<B>Item 1.</B>
</TABLE>
<TABLE>
BGCOLOR
</TABLE>
<TABLE>
<B>Item 2.</B>
</TABLE>`
So we have three tables but I'm only interested in finding the middle table that contains 'BGCOLOR'
The problem with my regex at the moment is that it searches for the starting table tag then looks for 'BGCOLOR' and doesn't care if it passes the table end tag:
tables = re.findall('\<table.*?BGCOLOR=".*?".*?\<\/table\>', text, re.I|re.S)
So it would find the first two tables instead of just the second table. Let me know if anyone knows how to handle this situation.
Thanks,
Michael
|
[
"Don't use a regular expression to parse HTML. Use lxml or BeautifulSoup.\n",
"Don't use regular expressions to parse HTML -- use an HTML parser, such as BeautifulSoup.\nSpecifically, your situation is basically one of having to deal with \"nested parentheses\" (where an open \"parens\" is an opening <table> tag and the corresponding closed parens is the matching </table>) -- exactly the kind of parsing tasks that regular expressions can't perform well. Lots of the work in parsing HTML is exactly connected with this \"matched parentheses\" issue, which makes regular expressions a perfectly horrible choice for the purpose.\nYou mention in a comment to another answer that you've had unspecified problems with BS -- I suspect you were trying the latest, 3.1 release (which has gone downhill) instead of the right one; try 3.0.8 instead, as BS's own docs recommend, and you could be better off.\nIf you've made some kind of pact with Evil never to use the right tool for the job, your task might not be totally impossible if you don't need to deal with nesting (just matching), i.e., there is never a table inside another table. In this case you can identify one table with r'<\\s*TABLE(.*?)<\\s*/\\s*TABLE' (with suitable flags such as re.DOTALL and re.I); loop over all such matches with the finditer method of regular expressions; and in the loop's body check whether BGCOLOR (in a case-insensitive sense) happens to be inside the body of the current match. It's still going to be more fragile, and more work, than using an HTML parser, but while definitely an inferior choice it needs not be a desperate situation.\nIf you do have nested tables to contend with, then it is a desperate situation.\n",
"if your task is just this simple, here's a way. split on <TABLE> then iterate the items and find the required pattern you want.\nmyhtml=\"\"\"\n<TABLE>\n<B>Item 1.</B>\n</TABLE>\n\nsome text1\nsome text2\nsome text3\n\n<TABLE>\nblah\nBGCOLOR\nblah\n</TABLE>\n\nsome texet\n<TABLE>\n<B>Item 2.</B>\n</TABLE>\n\"\"\"\n\nfor tab in myhtml.split(\"</TABLE>\"):\n if \"<TABLE>\" in tab and \"BGCOLOR\" in tab:\n print ''.join(tab.split(\"<TABLE>\")[1:])\n\noutput\n$ ./python.py\n\nblah\nBGCOLOR\nblah\n\n",
"Here's the code that ended up working for me. It finds the correct table and adds more tagging around it so that it is identified from the group with open and close tags of 'realTable'.\nsoup = BeautifulSoup(''.join(text))\nfor p in soup.findAll('table'):\n pattern = '.*BGCOLOR.*'\n if (re.match(pattern, str(p), re.S|re.I)):\n tags = Tag(soup, \"realTable\")\n p.replaceWith(tags)\n text = NavigableString(str(p))\n tags.insert(0, text)\nprint soup\n\nprints this out:\n<table><b>Item 1.</b></table>\n<realTable><table>blah BGCOLOR blah</table></realTable>\n<table><b>Item 2.</b></table>\n\n"
] |
[
4,
3,
0,
0
] |
[] |
[] |
[
"parsing",
"python",
"regex"
] |
stackoverflow_0002259694_parsing_python_regex.txt
|
Q:
Deleting the most recently received email via Python script?
I use Gmail and an application that notifies me if I've received a new email, containing its title in a tooltip. (GmailNotifier with Miranda-IM) Most of the emails I receive are ones I don't want to read, and it's annoying having to login to Gmail on a slow connection just to delete said email. I believe plugin is closed source.
I've been (unsuccessfully) trying to write a script that will login and delete the 'top' email (the one most recently received). However this is not as easy I thought it would be.
I first tried using imaplib, but discovered that it doesn't contain any of the methods I hoped it would. It's a bit like the dbapi spec, containing only minimal functionality incase the imap spec is changed. I then tried reading the imap RFC (rfc3501). Halfway through it, I realized I didn't want to write an entire mail client, so decided to try using pop3 instead.
poplib is also minimal but seemingly has what I need. However pop3 doesn't appear to sort the messages in any order I'm familiar with. I have to either call top() or retr() on every single email to read the headers if I want to see the date received.
I could probably iterate through every single message header, searching for the most recent date, but that's ugly. I want to avoid parsing my entire mailbox if possible. I also don't want to 'pop' the mailbox and download any other messages.
It's been 6 hours now and I feel no closer to a solution than when I started. Am I overlooking something simple? Is there another library I could try? (I found a 'chilkat' one, but it's bloated to hell, and I was hoping to do this with the standard library)
A:
import poplib
#connect to server
mailserver = poplib.POP3_SSL('pop.gmail.com')
mailserver.user('recent:YOURUSERNAME') #use 'recent mode'
mailserver.pass_('YOURPASSWORD') #consider not storing in plaintext!
#newest email has the highest message number
numMessages = len(mailserver.list()[1])
#confirm this is the right one, can comment these out later
newestEmail = mailserver.retr(numMessages)
print newestEmail
#most servers will not delete until you quit
mailserver.dele(numMessages)
mailserver.quit()
I worked with the poplib recently, writing a very primitive email client. I tested this with my email server (not gmail) on some test emails and it seemed to work correctly. I would send yourself a few dummy emails to test it out first.
Caveats:
Make sure you are using 'recent
mode':
http://mail.google.com/support/bin/answer.py?answer=47948
Make sure your Gmail account has POP3
enabled: Gmail > Settings >
Forwarding and POP/IMAP > "Enable POP
for all mail"
Hope this helps, it should be enough to get you going!
|
Deleting the most recently received email via Python script?
|
I use Gmail and an application that notifies me if I've received a new email, containing its title in a tooltip. (GmailNotifier with Miranda-IM) Most of the emails I receive are ones I don't want to read, and it's annoying having to login to Gmail on a slow connection just to delete said email. I believe plugin is closed source.
I've been (unsuccessfully) trying to write a script that will login and delete the 'top' email (the one most recently received). However this is not as easy I thought it would be.
I first tried using imaplib, but discovered that it doesn't contain any of the methods I hoped it would. It's a bit like the dbapi spec, containing only minimal functionality incase the imap spec is changed. I then tried reading the imap RFC (rfc3501). Halfway through it, I realized I didn't want to write an entire mail client, so decided to try using pop3 instead.
poplib is also minimal but seemingly has what I need. However pop3 doesn't appear to sort the messages in any order I'm familiar with. I have to either call top() or retr() on every single email to read the headers if I want to see the date received.
I could probably iterate through every single message header, searching for the most recent date, but that's ugly. I want to avoid parsing my entire mailbox if possible. I also don't want to 'pop' the mailbox and download any other messages.
It's been 6 hours now and I feel no closer to a solution than when I started. Am I overlooking something simple? Is there another library I could try? (I found a 'chilkat' one, but it's bloated to hell, and I was hoping to do this with the standard library)
|
[
"import poplib\n\n#connect to server\nmailserver = poplib.POP3_SSL('pop.gmail.com')\nmailserver.user('recent:YOURUSERNAME') #use 'recent mode'\nmailserver.pass_('YOURPASSWORD') #consider not storing in plaintext!\n\n#newest email has the highest message number\nnumMessages = len(mailserver.list()[1])\n\n#confirm this is the right one, can comment these out later\nnewestEmail = mailserver.retr(numMessages)\nprint newestEmail\n\n#most servers will not delete until you quit\nmailserver.dele(numMessages)\nmailserver.quit()\n\nI worked with the poplib recently, writing a very primitive email client. I tested this with my email server (not gmail) on some test emails and it seemed to work correctly. I would send yourself a few dummy emails to test it out first.\nCaveats:\n\nMake sure you are using 'recent\nmode':\nhttp://mail.google.com/support/bin/answer.py?answer=47948\nMake sure your Gmail account has POP3\nenabled: Gmail > Settings >\nForwarding and POP/IMAP > \"Enable POP\nfor all mail\"\n\nHope this helps, it should be enough to get you going!\n"
] |
[
4
] |
[] |
[] |
[
"email",
"imap",
"pop3",
"python"
] |
stackoverflow_0002260316_email_imap_pop3_python.txt
|
Q:
How can I write a Nokia application with pyqt?
I have seen questions on my Facebook group about 'Can I write Nokia apps with pyqt', but no one has answered. I am curious, can it be done?
A:
The short answer is yes.
You might like to look at http://wiki.forum.nokia.com/index.php/Getting_started_with_PyQt_for_Maemo,
Because of issues with PyQT being available only for GPL applications without money, Nokia released their own Python/QT bindings: http://developers.slashdot.org/story/09/08/30/0823206/Nokia-Makes-LGPL-Version-of-PyQt
Most Nokia development is still done in C++. Nokia provides a free IDE for this route.
|
How can I write a Nokia application with pyqt?
|
I have seen questions on my Facebook group about 'Can I write Nokia apps with pyqt', but no one has answered. I am curious, can it be done?
|
[
"The short answer is yes.\nYou might like to look at http://wiki.forum.nokia.com/index.php/Getting_started_with_PyQt_for_Maemo, \nBecause of issues with PyQT being available only for GPL applications without money, Nokia released their own Python/QT bindings: http://developers.slashdot.org/story/09/08/30/0823206/Nokia-Makes-LGPL-Version-of-PyQt\nMost Nokia development is still done in C++. Nokia provides a free IDE for this route.\n"
] |
[
3
] |
[] |
[] |
[
"nokia",
"pyqt",
"python"
] |
stackoverflow_0002260434_nokia_pyqt_python.txt
|
Q:
How to approach Google groups discussions crawler
as an exercise in RSS I would like to be able to search through pretty much all Unix discussions on this group.
comp.unix.shell
I know enough Python and understand basic RSS, but I am stuck on ... how do I grab all messages between particular dates, or at least all messages between Nth recent and Mth recent?
High level descriptions, pseudo-code is welcome.
Thank you!
EDIT:
I would like to be able to go back more than 100 messages, but do not grabbing like parsing 10 messages at a time such as using this URL:
http://groups.google.com/group/comp.unix.shell/topics?hl=en&start=2000&sa=N
There must be a better way.
A:
Crawling google groups violates the Google's Terms of Service, specifically the phrase:
use any robot, spider, site search/retrieval application, or other device to retrieve or index any portion of the Service or collect information about users for any unauthorized purpose
Are you sure you want to announce that you're doing that so openly? And are you blind to the consequences of your result?
A:
For N recent, seems like you could pass parameter ?num=50 or something in the feed url
For example, 50 new messages from comp.unix.shell group
http://groups.google.com/group/comp.unix.shell/feed/atom_v1_0_msgs.xml?num=50
and then pick up a feedparser program like Universal Feed Parser
There is .update_parsed option in feedparser, you could use that to check the msg within particular date range
>>> e.updated_parsed # parses all date formats
(2005, 11, 9, 11, 56, 34, 2, 313, 0)
A:
Have you thought about yahoos YQL? It's not too bad and can access a lot of APIs. http://developer.yahoo.com/yql/
I don't know if groups is suported but u can access rss feeds. Could be helpful.
A:
As Randal mentioned, this violates Google's ToS -- however, as a hypothetical or for use on another site without these restrictions you could pretty easily rig something up with urllib and BeautifulSoup. Use urllib to open the page and then use BeautifulSoup to grab all the thread topics (and links if you want to crawl deeper). You can then programmatically find the link to the next page of results and then make another urllib to go to page 2 -- then repeat the process.
At this point you should have all the raw data, then it is just a matter of manipulating the data and implementing your searching functionality.
|
How to approach Google groups discussions crawler
|
as an exercise in RSS I would like to be able to search through pretty much all Unix discussions on this group.
comp.unix.shell
I know enough Python and understand basic RSS, but I am stuck on ... how do I grab all messages between particular dates, or at least all messages between Nth recent and Mth recent?
High level descriptions, pseudo-code is welcome.
Thank you!
EDIT:
I would like to be able to go back more than 100 messages, but do not grabbing like parsing 10 messages at a time such as using this URL:
http://groups.google.com/group/comp.unix.shell/topics?hl=en&start=2000&sa=N
There must be a better way.
|
[
"Crawling google groups violates the Google's Terms of Service, specifically the phrase:\n\nuse any robot, spider, site search/retrieval application, or other device to retrieve or index any portion of the Service or collect information about users for any unauthorized purpose\n\nAre you sure you want to announce that you're doing that so openly? And are you blind to the consequences of your result?\n",
"For N recent, seems like you could pass parameter ?num=50 or something in the feed url\nFor example, 50 new messages from comp.unix.shell group\nhttp://groups.google.com/group/comp.unix.shell/feed/atom_v1_0_msgs.xml?num=50\nand then pick up a feedparser program like Universal Feed Parser\nThere is .update_parsed option in feedparser, you could use that to check the msg within particular date range\n>>> e.updated_parsed # parses all date formats\n(2005, 11, 9, 11, 56, 34, 2, 313, 0)\n\n",
"Have you thought about yahoos YQL? It's not too bad and can access a lot of APIs. http://developer.yahoo.com/yql/\nI don't know if groups is suported but u can access rss feeds. Could be helpful.\n",
"As Randal mentioned, this violates Google's ToS -- however, as a hypothetical or for use on another site without these restrictions you could pretty easily rig something up with urllib and BeautifulSoup. Use urllib to open the page and then use BeautifulSoup to grab all the thread topics (and links if you want to crawl deeper). You can then programmatically find the link to the next page of results and then make another urllib to go to page 2 -- then repeat the process.\nAt this point you should have all the raw data, then it is just a matter of manipulating the data and implementing your searching functionality.\n"
] |
[
4,
3,
1,
1
] |
[] |
[] |
[
"google_groups",
"python",
"web_crawler"
] |
stackoverflow_0002211887_google_groups_python_web_crawler.txt
|
Q:
SCons - convert all images in a directory
I'd like to write an SConstruct file that will convert (e.g.) all the JPEG files in a directory into PNGs.
I think I have the Builder alright:
ConvToPNG = Builder(action = 'convert $SOURCE $TARGET',
suffix = '.png',
src_suffix = '.jpg')
env['BUILDERS']['ConvToPNG'] = ConvToPNG
But then I'm not sure how to make a list of all the targets that need to be built. I can do it in a Python-y way like this:
pix_conversions = [env.ConvToPNG(jpg_src) for jpg_src in Glob('pix/img_*.jpg')]
And then maybe I'll use an Alias for those:
env.Alias('convert_all', pix_conversions)
Or else make a Node by hand and have it Depends on the conversions.
The thing is, this seems like it's something that Scanners are sorta made for. But I couldn't get that to work well. I tried making a Builder that would work on a directory and call a Scanner that would add a bunch of targets, but it didn't work because the SCons internals expect a Builder to run on a file. (or at least, that's what I gleaned from the error messages).
Is there a more SCons-y way of doing this?
A:
Your steps seems fine, but Alias node you need to pass to the AlwaysBuild function:
env.AlwaysBuild(env.Alias('convert_all', pix_conversions))
So the end result would be:
ConvToPNG = Builder(action = 'convert $SOURCE $TARGET',
suffix = '.png',
src_suffix = '.jpg')
env['BUILDERS']['ConvToPNG'] = ConvToPNG
pix_conversions = [env.ConvToPNG(jpg_src) for jpg_src in Glob('pix/img_*.jpg')]
env.AlwaysBuild(env.Alias('convert_all', pix_conversions))
It will work fine without any scanners. SCons will check MD5 hash of your JPEG files and if some file changed since last conversion then builder will be launched again.
A:
Scanners are for implicit dependencies.
e.g. you want to build foo which depends on foo.c which does a #include of bar.c. Thus, when you tell SCons to build foo with dependency foo.c, the C scanner will automatically pick up implicit dependency bar.c based on the explicit dependency foo.c.
|
SCons - convert all images in a directory
|
I'd like to write an SConstruct file that will convert (e.g.) all the JPEG files in a directory into PNGs.
I think I have the Builder alright:
ConvToPNG = Builder(action = 'convert $SOURCE $TARGET',
suffix = '.png',
src_suffix = '.jpg')
env['BUILDERS']['ConvToPNG'] = ConvToPNG
But then I'm not sure how to make a list of all the targets that need to be built. I can do it in a Python-y way like this:
pix_conversions = [env.ConvToPNG(jpg_src) for jpg_src in Glob('pix/img_*.jpg')]
And then maybe I'll use an Alias for those:
env.Alias('convert_all', pix_conversions)
Or else make a Node by hand and have it Depends on the conversions.
The thing is, this seems like it's something that Scanners are sorta made for. But I couldn't get that to work well. I tried making a Builder that would work on a directory and call a Scanner that would add a bunch of targets, but it didn't work because the SCons internals expect a Builder to run on a file. (or at least, that's what I gleaned from the error messages).
Is there a more SCons-y way of doing this?
|
[
"Your steps seems fine, but Alias node you need to pass to the AlwaysBuild function:\nenv.AlwaysBuild(env.Alias('convert_all', pix_conversions))\n\nSo the end result would be:\nConvToPNG = Builder(action = 'convert $SOURCE $TARGET',\n suffix = '.png',\n src_suffix = '.jpg')\nenv['BUILDERS']['ConvToPNG'] = ConvToPNG\npix_conversions = [env.ConvToPNG(jpg_src) for jpg_src in Glob('pix/img_*.jpg')]\nenv.AlwaysBuild(env.Alias('convert_all', pix_conversions))\n\nIt will work fine without any scanners. SCons will check MD5 hash of your JPEG files and if some file changed since last conversion then builder will be launched again.\n",
"Scanners are for implicit dependencies. \ne.g. you want to build foo which depends on foo.c which does a #include of bar.c. Thus, when you tell SCons to build foo with dependency foo.c, the C scanner will automatically pick up implicit dependency bar.c based on the explicit dependency foo.c.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"scons"
] |
stackoverflow_0002254707_python_scons.txt
|
Q:
In PyObjC how do you get a sheet to end after using runModalForWindow_?
I have a secondary window (a sheet) for a dialog controlled by a secondard WindowController. For some reason, the actions never get called in NSObject subclass after the sheet is displayed. I have confirmed and re-linked the actions. The code runs to runModalForWindow_ but then never receives the ok or cancel actions. So the sheet never goes away. What am I missing here? I cant seem to find any pyobjc examples on thier website that does a runModalForWindow_...
@objc.IBAction
def okSelected(self, sender):
self.dialogResult = objc.YES
NSLog("OK")
#NSApp.endSheet_(self.newTurnWindowOutlet)
NSApp.stopModalWithCode_(objc.OK)
@objc.IBAction
def cancelSelected(self, sender):
self.dialogResult = objc.NO
#NSApp.endSheet_(self.newTurnWindowOutlet)
NSApp.stopModalWithCode_(objc.NO)
def runSheet(self, parent):
NSApp.beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(
self.newTurnWindowOutlet, parent, None,
self.sheetDidEnd_returnCode_contextInfo_, None)
NSLog("runModelForWindow")
result = NSApp.runModalForWindow_(self.newTurnWindowOutlet)
NSLog(str(result))
NSApp.endSheet_(self.newTurnWindowOutlet)
self.newTurnWindowOutlet.orderOut_(self)
return self.dialogResult
A:
Your lines
@objc.IBAction
def okSelected(self, sender):
should be
@objc.IBAction
def okSelected_(self, sender):
etc. Remember, every colon in an Objective-C selector becomes an _ in Python!
|
In PyObjC how do you get a sheet to end after using runModalForWindow_?
|
I have a secondary window (a sheet) for a dialog controlled by a secondard WindowController. For some reason, the actions never get called in NSObject subclass after the sheet is displayed. I have confirmed and re-linked the actions. The code runs to runModalForWindow_ but then never receives the ok or cancel actions. So the sheet never goes away. What am I missing here? I cant seem to find any pyobjc examples on thier website that does a runModalForWindow_...
@objc.IBAction
def okSelected(self, sender):
self.dialogResult = objc.YES
NSLog("OK")
#NSApp.endSheet_(self.newTurnWindowOutlet)
NSApp.stopModalWithCode_(objc.OK)
@objc.IBAction
def cancelSelected(self, sender):
self.dialogResult = objc.NO
#NSApp.endSheet_(self.newTurnWindowOutlet)
NSApp.stopModalWithCode_(objc.NO)
def runSheet(self, parent):
NSApp.beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(
self.newTurnWindowOutlet, parent, None,
self.sheetDidEnd_returnCode_contextInfo_, None)
NSLog("runModelForWindow")
result = NSApp.runModalForWindow_(self.newTurnWindowOutlet)
NSLog(str(result))
NSApp.endSheet_(self.newTurnWindowOutlet)
self.newTurnWindowOutlet.orderOut_(self)
return self.dialogResult
|
[
"Your lines \n @objc.IBAction\n def okSelected(self, sender):\n\nshould be\n @objc.IBAction\n def okSelected_(self, sender):\n\netc. Remember, every colon in an Objective-C selector becomes an _ in Python!\n"
] |
[
2
] |
[] |
[] |
[
"cocoa",
"pyobjc",
"python"
] |
stackoverflow_0002259377_cocoa_pyobjc_python.txt
|
Q:
GAE datastore viewer - editing lists
Is it possible to somehow enable editing lists in GAE datastore viewer?
I'm using Python version of SDK.
Basically I want to avoid, as much as possible, writing own CRUD as it
wouldn't be necessary if only I could edit lists in datastore viewer..
A:
That's not built in to the datastore viewer, no. With the 1.3.1 release of the SDK, it is possible to add custom pages to the Admin console, but that wouldn't really save you from having to write the list editing page yourself.
AppEnngine Custom Pages Documentation
|
GAE datastore viewer - editing lists
|
Is it possible to somehow enable editing lists in GAE datastore viewer?
I'm using Python version of SDK.
Basically I want to avoid, as much as possible, writing own CRUD as it
wouldn't be necessary if only I could edit lists in datastore viewer..
|
[
"That's not built in to the datastore viewer, no. With the 1.3.1 release of the SDK, it is possible to add custom pages to the Admin console, but that wouldn't really save you from having to write the list editing page yourself.\nAppEnngine Custom Pages Documentation\n"
] |
[
2
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002260804_google_app_engine_google_cloud_datastore_python.txt
|
Q:
How can I resize the root window in Tkinter?
from Tkinter import *
import socket, sys
from PIL import Image, ImageTk
root = Tk()
root.title("Whois Tool")
root.resizable(0, 0)
text = Text()
text1 = Text()
image = Image.open("hacker2.png")
photo = ImageTk.PhotoImage(image)
label = Label(root, image=photo)
label.pack()
text1.config(width=15, height=1)
text1.pack()
def button1():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("com.whois-servers.net", 43))
s.send(text1.get("1.0", END) + "\r\n")
response = ''
while True:
a = s.recv(4096)
response += a
if a == '':
break
s.close()
text.insert(END, response)
def clear():
text.delete("1.0", END)
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.pack()
c = Button(root, text="Clear", width=10, height=2, command=clear)
c.pack()
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=60, height=15)
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
root.mainloop()
How can I resize the root window, or how can I resize an image to fit with the root window or button or lable and ect.. thanks
A:
For a 500x500 window you would use
root.geometry("500x500")
As for image resizing, I do not believe Tkinter supports it. You would have to use a library such as PIL to resize the image to the window resolution. -example resize code-
|
How can I resize the root window in Tkinter?
|
from Tkinter import *
import socket, sys
from PIL import Image, ImageTk
root = Tk()
root.title("Whois Tool")
root.resizable(0, 0)
text = Text()
text1 = Text()
image = Image.open("hacker2.png")
photo = ImageTk.PhotoImage(image)
label = Label(root, image=photo)
label.pack()
text1.config(width=15, height=1)
text1.pack()
def button1():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("com.whois-servers.net", 43))
s.send(text1.get("1.0", END) + "\r\n")
response = ''
while True:
a = s.recv(4096)
response += a
if a == '':
break
s.close()
text.insert(END, response)
def clear():
text.delete("1.0", END)
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.pack()
c = Button(root, text="Clear", width=10, height=2, command=clear)
c.pack()
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=60, height=15)
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
root.mainloop()
How can I resize the root window, or how can I resize an image to fit with the root window or button or lable and ect.. thanks
|
[
"For a 500x500 window you would use\nroot.geometry(\"500x500\")\n\nAs for image resizing, I do not believe Tkinter supports it. You would have to use a library such as PIL to resize the image to the window resolution. -example resize code-\n"
] |
[
35
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0002261011_python_tkinter.txt
|
Q:
Google Wave gadget configure / set properties
How can you configure or mutate a Google Wave gadget after creating one in Python? The following code will load the gadget via XML:
from waveapi import document
gadget = document.Gadget('http://domain.com/gadget.xml')
The API reference says you can pass a dictionary of initial properties, but I can't find any information on where the gadget would specify those initial properties. There are mentions of a getField/setField pair of methods to mutate gadget properties, but I can't find an API reference of them or again find where the gadget would specify these properties.
This came up because I am adding a Wave gadget as part of the response by a Wave robot, as described in the Wave Extension FAQ.
A:
Gadget is derived from Element which states:
Although a Robot can query the properties of an element it can only interact with the specific types that the element represents.
The API does mention SubmitDelta() and get() , which seem like wrappers for setattr and getattr.
Discussion of (similar) issue here
|
Google Wave gadget configure / set properties
|
How can you configure or mutate a Google Wave gadget after creating one in Python? The following code will load the gadget via XML:
from waveapi import document
gadget = document.Gadget('http://domain.com/gadget.xml')
The API reference says you can pass a dictionary of initial properties, but I can't find any information on where the gadget would specify those initial properties. There are mentions of a getField/setField pair of methods to mutate gadget properties, but I can't find an API reference of them or again find where the gadget would specify these properties.
This came up because I am adding a Wave gadget as part of the response by a Wave robot, as described in the Wave Extension FAQ.
|
[
"Gadget is derived from Element which states:\n\nAlthough a Robot can query the properties of an element it can only interact with the specific types that the element represents.\n\nThe API does mention SubmitDelta() and get() , which seem like wrappers for setattr and getattr. \nDiscussion of (similar) issue here\n"
] |
[
1
] |
[] |
[] |
[
"google_wave",
"python"
] |
stackoverflow_0002258985_google_wave_python.txt
|
Q:
Prevent a console app from closing when not invoked from an existing terminal?
There are many variants on this kind of question. However I am specifically after a way to prevent a console application in Python from closing when it is not invoked from a terminal (or other console, as it may be called on Windows). An example where this could occur is double clicking a .py file from the Windows explorer.
Typically I use something like the following code snippet, but it has the unfortunate side effect of operating even if the application is invoked from an existing terminal:
def press_any_key():
if os.name == "nt":
os.system("pause")
atexit.register(press_any_key)
It's also making the assumption that all Windows users are invoking the application from the Windows "shell", and that only Windows users can execute the program from a location other than an existing terminal.
Is there a (preferably cross platform) way to detect if my application has been invoked from a terminal, and/or whether it is necessary to provide a "press any key..." functionality for the currently running instance? Note that resorting to batch, bash or any other "wrapper process" workarounds are highly undesirable.
Update0
Using Alex Martelli's answer below, I've produced this function:
def register_pause_before_closing_console():
import atexit, os
if os.name == 'nt':
from win32api import GetConsoleTitle
if not GetConsoleTitle().startswith(os.environ["COMSPEC"]):
atexit.register(lambda: os.system("pause"))
if __name__ == '__main__':
register_pause_before_closing_console()
If other suitable answers arise, I'll append more code for other platforms and desktop environments.
Update1
In the vein of using pywin32, I've produced this function, which improves on the one above, using the accepted answer. The commented out code is an alternative implementation as originating in Update0. If using pywin32 is not an option, follow the link in the accepted answer. Pause or getch() to taste.
def _current_process_owns_console():
#import os, win32api
#return not win32api.GetConsoleTitle().startswith(os.environ["COMSPEC"])
import win32console, win32process
conswnd = win32console.GetConsoleWindow()
wndpid = win32process.GetWindowThreadProcessId(conswnd)[1]
curpid = win32process.GetCurrentProcessId()
return curpid == wndpid
def register_pause_before_closing_console():
import atexit, os, pdb
if os.name == 'nt':
if _current_process_owns_console():
atexit.register(lambda: os.system("pause"))
if __name__ == '__main__':
register_pause_before_closing_console()
A:
First, an attempt to disuade you from clever hacks. It's perfectly appropriate to have a seperate shortcut designed to be run from Explorer that does slightly different things (like holding the console open) from the script to be used from the commandline. As Alex has already pointed out, this is not an issue on nix, and the right thing to do there is always exit cleanly or your users will complain.
If you still want a workaround, here's code to detect when the console needs to be prevented from closing that's reasonably clean. Requires Windows 2000 or later, the logic is contained in this function:
def owns_console():
wnd = GetConsoleWindow()
if wnd is None:
return False
return GetCurrentProcessId() == GetWindowThreadProcessId(wnd)
Basically, it gets the PIDs of the process that owns the console Python is using, and of our process. If they are the same, then when we exit the console will go away, so it needs to be held open. If they are different, or if there's no console attached, Python should exit normally.
A:
On Unix, sys.stdin.isatty() reliably tells you whether standard input is coming from a terminal-like device (or is otherwise redirected), and similarly for the same method on sys.stdout and sys.stderr -- so you can use those calls to determine whether the application is being executed interactively or in some non-interactive environment (such as a cron job). Exactly how you want to use them depends on what you want to do if (for example) both standard input and output are redirected to a non-terminal but standard error is going to a terminal -- consider each of the 8 possibilities, from all of them redirected to non-terminals to none of them, and decide what you want to do in each case.
On Windows the situation is different since executing a .py file (as opposed to a .pyw file) will create a new transient console (there's no exactly equivalent situation in Unix); I assume that's the case you want to deal with? (Or is it just about redirection of standard I/O streams to files, which is possible in Windows roughly just like in Unix?). I think the best approach in Windows might be to use win32api.SetConsoleCtrlHandler to set a handler for such events as CTRL_CLOSE_EVENT -- this way the handler should be invoked (in this case, when the console closes) if there is a console for the process, but not otherwise. Or, if all you care about is whether a console is there at all or not (and prefer to handle things your way otherwise), try calling win32api.GetConsoleTitle in the try leg of a try/except statement -- it will generate an exception (which you catch and respond to by setting a boolean variable of yours to False) if there's no console, and just work (in which case you set that boolean variable to True) if there is a console.
|
Prevent a console app from closing when not invoked from an existing terminal?
|
There are many variants on this kind of question. However I am specifically after a way to prevent a console application in Python from closing when it is not invoked from a terminal (or other console, as it may be called on Windows). An example where this could occur is double clicking a .py file from the Windows explorer.
Typically I use something like the following code snippet, but it has the unfortunate side effect of operating even if the application is invoked from an existing terminal:
def press_any_key():
if os.name == "nt":
os.system("pause")
atexit.register(press_any_key)
It's also making the assumption that all Windows users are invoking the application from the Windows "shell", and that only Windows users can execute the program from a location other than an existing terminal.
Is there a (preferably cross platform) way to detect if my application has been invoked from a terminal, and/or whether it is necessary to provide a "press any key..." functionality for the currently running instance? Note that resorting to batch, bash or any other "wrapper process" workarounds are highly undesirable.
Update0
Using Alex Martelli's answer below, I've produced this function:
def register_pause_before_closing_console():
import atexit, os
if os.name == 'nt':
from win32api import GetConsoleTitle
if not GetConsoleTitle().startswith(os.environ["COMSPEC"]):
atexit.register(lambda: os.system("pause"))
if __name__ == '__main__':
register_pause_before_closing_console()
If other suitable answers arise, I'll append more code for other platforms and desktop environments.
Update1
In the vein of using pywin32, I've produced this function, which improves on the one above, using the accepted answer. The commented out code is an alternative implementation as originating in Update0. If using pywin32 is not an option, follow the link in the accepted answer. Pause or getch() to taste.
def _current_process_owns_console():
#import os, win32api
#return not win32api.GetConsoleTitle().startswith(os.environ["COMSPEC"])
import win32console, win32process
conswnd = win32console.GetConsoleWindow()
wndpid = win32process.GetWindowThreadProcessId(conswnd)[1]
curpid = win32process.GetCurrentProcessId()
return curpid == wndpid
def register_pause_before_closing_console():
import atexit, os, pdb
if os.name == 'nt':
if _current_process_owns_console():
atexit.register(lambda: os.system("pause"))
if __name__ == '__main__':
register_pause_before_closing_console()
|
[
"First, an attempt to disuade you from clever hacks. It's perfectly appropriate to have a seperate shortcut designed to be run from Explorer that does slightly different things (like holding the console open) from the script to be used from the commandline. As Alex has already pointed out, this is not an issue on nix, and the right thing to do there is always exit cleanly or your users will complain.\nIf you still want a workaround, here's code to detect when the console needs to be prevented from closing that's reasonably clean. Requires Windows 2000 or later, the logic is contained in this function:\ndef owns_console():\n wnd = GetConsoleWindow()\n if wnd is None:\n return False\n return GetCurrentProcessId() == GetWindowThreadProcessId(wnd)\n\nBasically, it gets the PIDs of the process that owns the console Python is using, and of our process. If they are the same, then when we exit the console will go away, so it needs to be held open. If they are different, or if there's no console attached, Python should exit normally.\n",
"On Unix, sys.stdin.isatty() reliably tells you whether standard input is coming from a terminal-like device (or is otherwise redirected), and similarly for the same method on sys.stdout and sys.stderr -- so you can use those calls to determine whether the application is being executed interactively or in some non-interactive environment (such as a cron job). Exactly how you want to use them depends on what you want to do if (for example) both standard input and output are redirected to a non-terminal but standard error is going to a terminal -- consider each of the 8 possibilities, from all of them redirected to non-terminals to none of them, and decide what you want to do in each case.\nOn Windows the situation is different since executing a .py file (as opposed to a .pyw file) will create a new transient console (there's no exactly equivalent situation in Unix); I assume that's the case you want to deal with? (Or is it just about redirection of standard I/O streams to files, which is possible in Windows roughly just like in Unix?). I think the best approach in Windows might be to use win32api.SetConsoleCtrlHandler to set a handler for such events as CTRL_CLOSE_EVENT -- this way the handler should be invoked (in this case, when the console closes) if there is a console for the process, but not otherwise. Or, if all you care about is whether a console is there at all or not (and prefer to handle things your way otherwise), try calling win32api.GetConsoleTitle in the try leg of a try/except statement -- it will generate an exception (which you catch and respond to by setting a boolean variable of yours to False) if there's no console, and just work (in which case you set that boolean variable to True) if there is a console.\n"
] |
[
6,
3
] |
[] |
[] |
[
"console",
"console_application",
"persistence",
"python",
"terminal"
] |
stackoverflow_0002258771_console_console_application_persistence_python_terminal.txt
|
Q:
Python: How to make multiple HTTP POST queries in one moment?
How to make multiple HTTP POST queries in one moment using Python?
Using an external library with an example can be a good solution.
A:
External lib? Maybe an internal one would do the trick...
http://docs.python.org/library/httplib.html#examples
specifically:
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
If you wanted to process multiple HTTP POST queries (asynchronous) you could cycle through them in a loop, opening subprocesses using subprocess.Popen. Although a better solution would probably be asyncore. This site has an example of using asyncore for http requests (like POST).
A:
You should consider using threading (or maybe multiprocessing, but here the GIL is not a problem) to enable concurrent execution.
|
Python: How to make multiple HTTP POST queries in one moment?
|
How to make multiple HTTP POST queries in one moment using Python?
Using an external library with an example can be a good solution.
|
[
"External lib? Maybe an internal one would do the trick...\nhttp://docs.python.org/library/httplib.html#examples\nspecifically: \nparams = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})\n\nIf you wanted to process multiple HTTP POST queries (asynchronous) you could cycle through them in a loop, opening subprocesses using subprocess.Popen. Although a better solution would probably be asyncore. This site has an example of using asyncore for http requests (like POST). \n",
"You should consider using threading (or maybe multiprocessing, but here the GIL is not a problem) to enable concurrent execution.\n"
] |
[
1,
0
] |
[] |
[] |
[
"concurrency",
"http",
"python"
] |
stackoverflow_0002261035_concurrency_http_python.txt
|
Q:
How can I put 2 buttons next to each other?
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.config()
b.pack(side=LEFT)
c = Button(root, text="Clear", width=10, height=2, command=clear)
c.pack(side=LEFT)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=35, height=15)
text.pack(side=RIGHT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
How can I put these 2 buttons next to each other ontop of the text widget? when I set "side=LEFT" it just puts the 2 buttons next to the text widget
A:
There are typically two solutions to this type of problem. Neither is better than the other in all circumstances, or in this particular example. Both solutions are perfectly acceptable.
Solution 1: use two containers (typically, frames). One to hold horizontal items, one to hold vertical items. In this case the root window can serve as the container for the vertically stacked items. Place the two buttons in the horizontal frame (using pack(side=LEFT)), then put that frame above the text widget (using pack(side=TOP)).
Solution 2: use the grid geometry manager, which lays out your UI in a grid. Place the buttons in cells 0,1 and 0,2, and the text widget in 1,1 spanning two columns.
Typically, using grid requires a bit more up-front planning. You have to figure out which items need to span columns or rows, which columns or rows should grow and shrink as the widget is re-sized, etc. The pack solution is "easiest" (for some definitions of "easy", anyway) for very simple layouts such as this.
The general technique of using frames to contain groups of widgets is a good one. It makes it easy to manage whole sets of widgets as a group. and to mix and match left-to-right groups of widgets and top-to-bottom groups of widgets.
This is how I would do it using the multiple-frames technique. Notice how I create the widgets as children of root rather than children of the inner frames. This makes it a bit easier to modify the layout in the future, since all you have to do is create or remove various frames without having to modify the widget hierarchy.
# create the main sections of the layout,
# and lay them out
top = Frame(root)
bottom = Frame(root)
top.pack(side=TOP)
bottom.pack(side=BOTTOM, fill=BOTH, expand=True)
# create the widgets for the top part of the GUI,
# and lay them out
b = Button(root, text="Enter", width=10, height=2, command=button1)
c = Button(root, text="Clear", width=10, height=2, command=clear)
b.pack(in_=top, side=LEFT)
c.pack(in_=top, side=LEFT)
# create the widgets for the bottom part of the GUI,
# and lay them out
text = Text(root, width=35, height=15)
scrollbar = Scrollbar(root)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
scrollbar.pack(in_=bottom, side=RIGHT, fill=Y)
text.pack(in_=bottom, side=LEFT, fill=BOTH, expand=True)
A naive implementation using grid is below. It has a different resize behavior which may or may not be what you want. It really depends on the resize behavior that you desire. Usually I'll manage a row of controls with a frame, then use grid to lay it out along with the other widgets. In this example I'll just use grid for everything.
Notice how in addition to managing which row(s) and column(s) a widget is in, you have to decide on a weighting factor for rows and columns. At a minimum you need to pick one row and one column to "pick up the slack", which usually means whatever column your primary widget is in (read: usually a text, canvas, or another frame) is in.
b = Button(root, text="Enter", width=10, height=2, command=button1)
c = Button(root, text="Clear", width=10, height=2, command=clear)
b.grid(row=0,column=0, sticky=W)
c.grid(row=0,column=1, sticky=W)
textframe = Frame(root)
textframe.grid(in_=root, row=1, column=0, columnspan=3, sticky=NSEW)
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
text = Text(root, width=35, height=15)
scrollbar = Scrollbar(root)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
scrollbar.pack(in_=textframe, side=RIGHT, fill=Y)
text.pack(in_=textframe, side=LEFT, fill=BOTH, expand=True)
In this specific case I'd choose the first method, the one with pack. For more complex designs I'll almost always use a mix of both grid and pack. Use pack for items that naturally stack either horizontally or vertically (such as toolbars). Use grid for more complex layouts (such as the whole app, widgets with scrollbars, dialogs, etc). You can't use both grid and pack for the same container, but you can use pack for one container, grid for another, etc.
|
How can I put 2 buttons next to each other?
|
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.config()
b.pack(side=LEFT)
c = Button(root, text="Clear", width=10, height=2, command=clear)
c.pack(side=LEFT)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=35, height=15)
text.pack(side=RIGHT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
How can I put these 2 buttons next to each other ontop of the text widget? when I set "side=LEFT" it just puts the 2 buttons next to the text widget
|
[
"There are typically two solutions to this type of problem. Neither is better than the other in all circumstances, or in this particular example. Both solutions are perfectly acceptable.\nSolution 1: use two containers (typically, frames). One to hold horizontal items, one to hold vertical items. In this case the root window can serve as the container for the vertically stacked items. Place the two buttons in the horizontal frame (using pack(side=LEFT)), then put that frame above the text widget (using pack(side=TOP)).\nSolution 2: use the grid geometry manager, which lays out your UI in a grid. Place the buttons in cells 0,1 and 0,2, and the text widget in 1,1 spanning two columns.\nTypically, using grid requires a bit more up-front planning. You have to figure out which items need to span columns or rows, which columns or rows should grow and shrink as the widget is re-sized, etc. The pack solution is \"easiest\" (for some definitions of \"easy\", anyway) for very simple layouts such as this.\nThe general technique of using frames to contain groups of widgets is a good one. It makes it easy to manage whole sets of widgets as a group. and to mix and match left-to-right groups of widgets and top-to-bottom groups of widgets. \nThis is how I would do it using the multiple-frames technique. Notice how I create the widgets as children of root rather than children of the inner frames. This makes it a bit easier to modify the layout in the future, since all you have to do is create or remove various frames without having to modify the widget hierarchy.\n# create the main sections of the layout, \n# and lay them out\ntop = Frame(root)\nbottom = Frame(root)\ntop.pack(side=TOP)\nbottom.pack(side=BOTTOM, fill=BOTH, expand=True)\n\n# create the widgets for the top part of the GUI,\n# and lay them out\nb = Button(root, text=\"Enter\", width=10, height=2, command=button1)\nc = Button(root, text=\"Clear\", width=10, height=2, command=clear)\nb.pack(in_=top, side=LEFT)\nc.pack(in_=top, side=LEFT)\n\n# create the widgets for the bottom part of the GUI,\n# and lay them out\ntext = Text(root, width=35, height=15)\nscrollbar = Scrollbar(root)\nscrollbar.config(command=text.yview)\ntext.config(yscrollcommand=scrollbar.set)\nscrollbar.pack(in_=bottom, side=RIGHT, fill=Y)\ntext.pack(in_=bottom, side=LEFT, fill=BOTH, expand=True)\n\nA naive implementation using grid is below. It has a different resize behavior which may or may not be what you want. It really depends on the resize behavior that you desire. Usually I'll manage a row of controls with a frame, then use grid to lay it out along with the other widgets. In this example I'll just use grid for everything.\nNotice how in addition to managing which row(s) and column(s) a widget is in, you have to decide on a weighting factor for rows and columns. At a minimum you need to pick one row and one column to \"pick up the slack\", which usually means whatever column your primary widget is in (read: usually a text, canvas, or another frame) is in.\nb = Button(root, text=\"Enter\", width=10, height=2, command=button1)\nc = Button(root, text=\"Clear\", width=10, height=2, command=clear)\nb.grid(row=0,column=0, sticky=W)\nc.grid(row=0,column=1, sticky=W)\n\ntextframe = Frame(root)\ntextframe.grid(in_=root, row=1, column=0, columnspan=3, sticky=NSEW)\nroot.columnconfigure(0, weight=1)\nroot.rowconfigure(1, weight=1)\n\ntext = Text(root, width=35, height=15)\nscrollbar = Scrollbar(root)\nscrollbar.config(command=text.yview)\ntext.config(yscrollcommand=scrollbar.set)\nscrollbar.pack(in_=textframe, side=RIGHT, fill=Y)\ntext.pack(in_=textframe, side=LEFT, fill=BOTH, expand=True)\n\nIn this specific case I'd choose the first method, the one with pack. For more complex designs I'll almost always use a mix of both grid and pack. Use pack for items that naturally stack either horizontally or vertically (such as toolbars). Use grid for more complex layouts (such as the whole app, widgets with scrollbars, dialogs, etc). You can't use both grid and pack for the same container, but you can use pack for one container, grid for another, etc.\n"
] |
[
33
] |
[] |
[] |
[
"button",
"python",
"tkinter"
] |
stackoverflow_0002261191_button_python_tkinter.txt
|
Q:
PyRo and python
I use PyRo in my python programm. And I have a problem. class B: In callFromProxy print 0, but in callfun print right value = 10. Why? How to fix?
class A(Pyro.core.ObjBase):
# set link to item class B
def set(self, real_B):
self.item_B = real_B
# call function callfun in item_B
def callfun(self):
self.item_B.callfun(10)
class B(Pyro.core.ObjBase):
# init class B
def __init__(self):
self.elements = {"name":0}
# set proxy to item class A
def set(self, proxyA):
self.proxyA = proxyA
# print
def printvalue(self):
print self.elements["name"]
# call from proxy
def callFromProxy(self):
self.proxyA.callfun()
self.printvalue() # this is not print 10, print 0
# call function
def callfun(self, value):
self.elements["name"] = value
self.printvalue() # but this is print 10
itemA = A()
# proxyA connect from PyRo to itemA
itemB = B()
itemB.set(itemA)
itemA.set(itemB)
itemB.callFromProxy() # this is not print 10
A:
I believe (and correct me if I'm wrong) PyRo uses asynchronous calls, at least by default.
So when you call callFromProxy, printvalue might get executed before callfun on itemB, because it takes time to call A.callfun and B.callfun. If/when this happens, elements["name"] will still be 0 when printvalue is called for the first time.
|
PyRo and python
|
I use PyRo in my python programm. And I have a problem. class B: In callFromProxy print 0, but in callfun print right value = 10. Why? How to fix?
class A(Pyro.core.ObjBase):
# set link to item class B
def set(self, real_B):
self.item_B = real_B
# call function callfun in item_B
def callfun(self):
self.item_B.callfun(10)
class B(Pyro.core.ObjBase):
# init class B
def __init__(self):
self.elements = {"name":0}
# set proxy to item class A
def set(self, proxyA):
self.proxyA = proxyA
# print
def printvalue(self):
print self.elements["name"]
# call from proxy
def callFromProxy(self):
self.proxyA.callfun()
self.printvalue() # this is not print 10, print 0
# call function
def callfun(self, value):
self.elements["name"] = value
self.printvalue() # but this is print 10
itemA = A()
# proxyA connect from PyRo to itemA
itemB = B()
itemB.set(itemA)
itemA.set(itemB)
itemB.callFromProxy() # this is not print 10
|
[
"I believe (and correct me if I'm wrong) PyRo uses asynchronous calls, at least by default.\nSo when you call callFromProxy, printvalue might get executed before callfun on itemB, because it takes time to call A.callfun and B.callfun. If/when this happens, elements[\"name\"] will still be 0 when printvalue is called for the first time.\n"
] |
[
1
] |
[] |
[] |
[
"pyro",
"python"
] |
stackoverflow_0002261317_pyro_python.txt
|
Q:
Python repr function problem
I'm dealing with some text parsing in Python and for that purpose, it's good for me to apply repr() function on each string I'm gonna parse, but after the parsing, I need to convert some parsed substring back to the previous representation, because I want to print them and I'm not able to do this. I thought that str() function should get the string back to the human more readable form. But when I apply str function on that substring, nothing's changed.
As I've said I need to print the string in human readable form, without printing escape sequences like \n, \t etc...
But when I apply repr() to a string and then I want to convert it back, I don't know how, because str() function didn't do it.
So my question is, how to convert the string back into human readable form?
Thanks for every reply.
A:
str() has no effect on objects that are already strings. You need to use eval() to undo a repr() where possible. Try using ast.literal_eval() instead though.
|
Python repr function problem
|
I'm dealing with some text parsing in Python and for that purpose, it's good for me to apply repr() function on each string I'm gonna parse, but after the parsing, I need to convert some parsed substring back to the previous representation, because I want to print them and I'm not able to do this. I thought that str() function should get the string back to the human more readable form. But when I apply str function on that substring, nothing's changed.
As I've said I need to print the string in human readable form, without printing escape sequences like \n, \t etc...
But when I apply repr() to a string and then I want to convert it back, I don't know how, because str() function didn't do it.
So my question is, how to convert the string back into human readable form?
Thanks for every reply.
|
[
"str() has no effect on objects that are already strings. You need to use eval() to undo a repr() where possible. Try using ast.literal_eval() instead though.\n"
] |
[
3
] |
[] |
[] |
[
"format",
"python",
"text"
] |
stackoverflow_0002261593_format_python_text.txt
|
Q:
Runing bcdedit from python in Windows 2008 SP2
I do not know windows well, so that may explain my dilemma ...
I am trying to run bcdedit in Windows 2008R2 from Python 2.6.
My Python routine to run a command looks like this:
def run_program(cmd_str):
"""Run the specified command, returning its output as an array of lines"""
dprint("run_program(%s): entering" % cmd_str)
cmd_args = cmd_str.split()
subproc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
(outf, errf) = (subproc.stdout, subproc.stderr)
olines = outf.readlines()
elines = errf.readlines()
if Options.debug:
if elines:
dprint('Error output:')
for line in elines:
dprint(line.rstrip())
if olines:
dprint('Normal output:')
for line in olines:
dprint(line.rstrip())
errf.close()
outf.close()
res = subproc.wait()
dprint('wait result=', res)
return (res, olines)
I call this function thusly:
(res, o) = run_program('bcdedit /set {current} MSI forcedisable')
This command works when I type it from a cmd window, and it works when I put it in a batch file and run it from a command window (as Administrator, of course).
But when I run it from Python (as Administrator), Python claims it can't find the command, returning:
bcdedit is not recognized as an internal or external command,
operable program or batch file
Also, if I trying running my batch file from Python (which works from the command line), it also fails. I've also tried it with the full path to bcdedit, with the same results.
What is it about calling bcdedit from Python that makes it not found?
Note that I can call other EXE files from Python, so I have some level of confidence that my Python code is sane ... but who knows.
Any help would be most appreciated.
A:
Windows 2008 R2 is 64-bit-only, yes? Python's a 32-bit process. When a 32-bit app runs something from C:\Windows\System32, Windows actually looks in C:\Windows\SysWOW64. Use C:\Windows\SysNative.
A:
Perhaps the path to bcdedit.exe isn't in your system path when Python is running for some reason (a different user account, for example). You can find this out by printing:
os.environ.get("PATH")
It's semicolon-delimited, so os.environ.get("PATH").split(';') might be more useful.
I can't see any reason why it wouldn't be there, but just in case, you should be looking for C:\Windows\System32, where C is your Windows drive letter.
A:
Check your PATH variable and see if C:\windows\system32 is there. (use set in DOS)
A:
For some reason I experiment the same trouble from c#. If I list the files it was not here, but when I was looking from Explorer it was there. maybe it is some kind of protected file. To call bcdedit.exe, I manually copied it from system32 to my application folder and it worked. There is also another one in windows\winsxs folder. I can start it from my application, but I`m not sure it is the same path on all computers.
Hope it helps!
|
Runing bcdedit from python in Windows 2008 SP2
|
I do not know windows well, so that may explain my dilemma ...
I am trying to run bcdedit in Windows 2008R2 from Python 2.6.
My Python routine to run a command looks like this:
def run_program(cmd_str):
"""Run the specified command, returning its output as an array of lines"""
dprint("run_program(%s): entering" % cmd_str)
cmd_args = cmd_str.split()
subproc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
(outf, errf) = (subproc.stdout, subproc.stderr)
olines = outf.readlines()
elines = errf.readlines()
if Options.debug:
if elines:
dprint('Error output:')
for line in elines:
dprint(line.rstrip())
if olines:
dprint('Normal output:')
for line in olines:
dprint(line.rstrip())
errf.close()
outf.close()
res = subproc.wait()
dprint('wait result=', res)
return (res, olines)
I call this function thusly:
(res, o) = run_program('bcdedit /set {current} MSI forcedisable')
This command works when I type it from a cmd window, and it works when I put it in a batch file and run it from a command window (as Administrator, of course).
But when I run it from Python (as Administrator), Python claims it can't find the command, returning:
bcdedit is not recognized as an internal or external command,
operable program or batch file
Also, if I trying running my batch file from Python (which works from the command line), it also fails. I've also tried it with the full path to bcdedit, with the same results.
What is it about calling bcdedit from Python that makes it not found?
Note that I can call other EXE files from Python, so I have some level of confidence that my Python code is sane ... but who knows.
Any help would be most appreciated.
|
[
"Windows 2008 R2 is 64-bit-only, yes? Python's a 32-bit process. When a 32-bit app runs something from C:\\Windows\\System32, Windows actually looks in C:\\Windows\\SysWOW64. Use C:\\Windows\\SysNative.\n",
"Perhaps the path to bcdedit.exe isn't in your system path when Python is running for some reason (a different user account, for example). You can find this out by printing:\nos.environ.get(\"PATH\")\n\nIt's semicolon-delimited, so os.environ.get(\"PATH\").split(';') might be more useful.\nI can't see any reason why it wouldn't be there, but just in case, you should be looking for C:\\Windows\\System32, where C is your Windows drive letter.\n",
"Check your PATH variable and see if C:\\windows\\system32 is there. (use set in DOS)\n",
"For some reason I experiment the same trouble from c#. If I list the files it was not here, but when I was looking from Explorer it was there. maybe it is some kind of protected file. To call bcdedit.exe, I manually copied it from system32 to my application folder and it worked. There is also another one in windows\\winsxs folder. I can start it from my application, but I`m not sure it is the same path on all computers. \nHope it helps!\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"python",
"windows_vista"
] |
stackoverflow_0002017557_python_windows_vista.txt
|
Q:
Python: Simulate search algorithms in network models
I am using networkx package to draw power law graphs. I want to simulate a search algorithm on this graph and want to visually see the algorithm move from one node to another on the graph. How do I do that?
A:
On a mac you could use NodeBox: http://nodebox.net/.
A:
NetworkX supports drawing using Graphviz and matplotlib. Did you read the drawing-chapter in its documentation?
|
Python: Simulate search algorithms in network models
|
I am using networkx package to draw power law graphs. I want to simulate a search algorithm on this graph and want to visually see the algorithm move from one node to another on the graph. How do I do that?
|
[
"On a mac you could use NodeBox: http://nodebox.net/. \n",
"NetworkX supports drawing using Graphviz and matplotlib. Did you read the drawing-chapter in its documentation?\n"
] |
[
1,
1
] |
[] |
[] |
[
"graph_drawing",
"networkx",
"python"
] |
stackoverflow_0002146395_graph_drawing_networkx_python.txt
|
Q:
Possible to use Mathematica from other programming languages (python/C#)?
Is it possible to use Mathematica's computing capabilities from other languages? I need to do some complex operations (not necessarily symbolic, btw), and it'd be pretty sweet to be able to just call Mathematica's functions or running Mathematica's code right from my python/c#'s program.
Is it possible?
A:
Looks like there is a MathLink API you can use from C#, c or Java, have you checked this out?
http://reference.wolfram.com/mathematica/guide/MathLinkAPI.html
A:
To links about usage of python and .Net (for C#)
A:
Perhaps the easiest way is to make the Mathematica program its own self-contained script and just call it as a system call or pipe stuff to/from it via stdin/stdout. Here's how to do that:
Call a Mathematica program from the command line, with command-line args, stdin, stdout, and stderr
A:
I haven't used it, but this looks interesting. Looks like you can call Mathematica code directly from your C# app using .NET/Link (a product by Wolfram).
A:
Yes but there are some subtleties. I covered Mathematica .NET interoperability in my book F# for Scientists but dropped the subject for its successor F# for Technical Computing.
|
Possible to use Mathematica from other programming languages (python/C#)?
|
Is it possible to use Mathematica's computing capabilities from other languages? I need to do some complex operations (not necessarily symbolic, btw), and it'd be pretty sweet to be able to just call Mathematica's functions or running Mathematica's code right from my python/c#'s program.
Is it possible?
|
[
"Looks like there is a MathLink API you can use from C#, c or Java, have you checked this out?\nhttp://reference.wolfram.com/mathematica/guide/MathLinkAPI.html\n",
"To links about usage of python and .Net (for C#)\n",
"Perhaps the easiest way is to make the Mathematica program its own self-contained script and just call it as a system call or pipe stuff to/from it via stdin/stdout. Here's how to do that:\nCall a Mathematica program from the command line, with command-line args, stdin, stdout, and stderr\n",
"I haven't used it, but this looks interesting. Looks like you can call Mathematica code directly from your C# app using .NET/Link (a product by Wolfram).\n",
"Yes but there are some subtleties. I covered Mathematica .NET interoperability in my book F# for Scientists but dropped the subject for its successor F# for Technical Computing.\n"
] |
[
5,
4,
4,
1,
1
] |
[] |
[] |
[
"c#",
"mathlink",
"python",
"wolfram_mathematica"
] |
stackoverflow_0001783564_c#_mathlink_python_wolfram_mathematica.txt
|
Q:
List comprehension and functions
I'm a little confusing when try something like this
b = [lambda x:x**i for i in range(11)]
When I then try b[1](2) I have 1024 as a result that is wrong. But when I write so
b = [(lambda i: lambda x:x**i)(i) for i in range(11)]
all is OK
>>> b[1](2)
2
>>> b[5](2)
32
It works fine but what's wrong in first code?
A:
This is due to how closures in Python work.
The loop changes the value in the scope that all the functions share. Move generation of the function into a separate scope, i.e. function.
A:
It's a game of scopes.
In the first code, the "i" name in the lambda is only a reference. The value behind that reference gets altered as the for loop executes.
In the second code, there are two different scopes.
|
List comprehension and functions
|
I'm a little confusing when try something like this
b = [lambda x:x**i for i in range(11)]
When I then try b[1](2) I have 1024 as a result that is wrong. But when I write so
b = [(lambda i: lambda x:x**i)(i) for i in range(11)]
all is OK
>>> b[1](2)
2
>>> b[5](2)
32
It works fine but what's wrong in first code?
|
[
"This is due to how closures in Python work.\nThe loop changes the value in the scope that all the functions share. Move generation of the function into a separate scope, i.e. function.\n",
"It's a game of scopes.\nIn the first code, the \"i\" name in the lambda is only a reference. The value behind that reference gets altered as the for loop executes.\nIn the second code, there are two different scopes.\n"
] |
[
3,
1
] |
[] |
[] |
[
"function",
"list",
"list_comprehension",
"python"
] |
stackoverflow_0002261826_function_list_list_comprehension_python.txt
|
Q:
BMP2avi in python
I am looking for a python code that takes series of BMP file and merges them into Avi file (and get the parameter frames per second from the user)
does anyone has an idea where to begin?
Ariel
A:
I'd begin by using the GStreamer Python bindings; at a minimum, that'll take the AVI encoding (or a great many other codecs, if you prefer) off your plate.
It won't help with BMP input, though; either you can convert them to PNG or another natively-supported input format or use a different library such as PIL to decode them into a buffer for GStreamer's use (feeding the decoded buffers in with the appsrc plugin).
|
BMP2avi in python
|
I am looking for a python code that takes series of BMP file and merges them into Avi file (and get the parameter frames per second from the user)
does anyone has an idea where to begin?
Ariel
|
[
"I'd begin by using the GStreamer Python bindings; at a minimum, that'll take the AVI encoding (or a great many other codecs, if you prefer) off your plate.\nIt won't help with BMP input, though; either you can convert them to PNG or another natively-supported input format or use a different library such as PIL to decode them into a buffer for GStreamer's use (feeding the decoded buffers in with the appsrc plugin).\n"
] |
[
0
] |
[] |
[] |
[
"avi",
"bmp",
"python"
] |
stackoverflow_0002261928_avi_bmp_python.txt
|
Q:
URL redirection problem
i have the below url
http://bit.ly/cDdh1c
When you place the above url in a browser and hit enter it will redirect to the below url
http://www.kennystopproducts.info/Top/?hop=arnishad
But where as when i try to find the base url (after eliminating all the redirect urls) for the same above url http://bit.ly/cDdh1c via a python program (below you can see the code) iam getting the following url http://www.cbtrends.com/ as base url.Please see the log file below
Why the same url is behaving different with browser and with a python program.What should i change in the python program so that it can redirect to the proper url?Iam wondering how this strange behaviour can happen.?
Other url for which iam observing similar behaviour is
http://bit.ly/bEKyOx ====>
http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=150413977509
( via browser)
http://www.ebay.com (via python
program)
maxattempts = 5
turl = url
while (maxattempts > 0) :
host,path = urlparse.urlsplit(turl)[1:3]
if len(host.strip()) == 0 :
return None
try:
connection = httplib.HTTPConnection(host,timeout=10)
connection.request("HEAD", path)
resp = connection.getresponse()
except:
return None
maxattempts = maxattempts - 1
if (resp.status >= 300) and (resp.status <= 399):
self.logger.debug("The present %s is a redirection one" %turl)
turl = resp.getheader('location')
elif (resp.status >= 200) and (resp.status <= 299) :
self.logger.debug("The present url %s is a proper one" %turl)
return turl
else :
#some problem with this url
return None
return None
Log file for your reference
2010-02-14 10:29:43,260 - paypallistener.views.MrCrawler - INFO - Bringing down the base URL
2010-02-14 10:29:43,261 - paypallistener.views.MrCrawler - DEBUG - what is the url=http://bit.ly/cDdh1c
2010-02-14 10:29:43,994 - paypallistener.views.MrCrawler - DEBUG - The present http://bit.ly/cDdh1c is a redirection one
2010-02-14 10:29:43,995 - paypallistener.views.MrCrawler - DEBUG - what is the url=http://www.cbtrends.com/get-product.html?productid=reFfJcmpgGt95hoiavbXUAYIMP7OfiQn0qBA8BC7%252BV8%253D&affid=arnishad&tid=arnishad&utm_source=twitterfeed&utm_medium=twitter
2010-02-14 10:29:44,606 - paypallistener.views.MrCrawler - DEBUG - The present http://www.cbtrends.com/get-product.html?productid=reFfJcmpgGt95hoiavbXUAYIMP7OfiQn0qBA8BC7%252BV8%253D&affid=arnishad&tid=arnishad&utm_source=twitterfeed&utm_medium=twitter is a redirection one
2010-02-14 10:29:44,607 - paypallistener.views.MrCrawler - DEBUG - what is the url=http://www.cbtrends.com/
2010-02-14 10:29:45,547 - paypallistener.views.MrCrawler - DEBUG - The present url http://www.cbtrends.com/ is a proper one
http://www.cbtrends.com/
A:
Your problem is that when you call urlsplit, your path variable only contains the path and is missing the query.
So, instead try:
import httplib
import urlparse
def getUrl(url):
maxattempts = 10
turl = url
while (maxattempts > 0) :
host,path,query = urlparse.urlsplit(turl)[1:4]
if len(host.strip()) == 0 :
return None
try:
connection = httplib.HTTPConnection(host,timeout=10)
connection.request("GET", path+'?'+query)
resp = connection.getresponse()
except:
return None
maxattempts = maxattempts - 1
if (resp.status >= 300) and (resp.status <= 399):
turl = resp.getheader('location')
elif (resp.status >= 200) and (resp.status <= 299) :
return turl
else :
#some problem with this url
return None
return None
print getUrl('http://bit.ly/cDdh1c')
A:
Your problem comes from this line :
host,path = urlparse.urlsplit(turl)[1:3]
You're leaving out the query string. So on the example log you're providing, the second HEAD request you will do will be on http://www.cbtrends.com/get-product.html without the GET parameters. Open that URL in your browser and you'll see it redirects to http://www.cbtrends.com/.
You have to calculate the path using all elements of the tuple returned by urlsplit.
parts = urlparse.urlsplit(turl)
host = parts[1]
path = "%s?%s#%s" % parts[2:5]
|
URL redirection problem
|
i have the below url
http://bit.ly/cDdh1c
When you place the above url in a browser and hit enter it will redirect to the below url
http://www.kennystopproducts.info/Top/?hop=arnishad
But where as when i try to find the base url (after eliminating all the redirect urls) for the same above url http://bit.ly/cDdh1c via a python program (below you can see the code) iam getting the following url http://www.cbtrends.com/ as base url.Please see the log file below
Why the same url is behaving different with browser and with a python program.What should i change in the python program so that it can redirect to the proper url?Iam wondering how this strange behaviour can happen.?
Other url for which iam observing similar behaviour is
http://bit.ly/bEKyOx ====>
http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=150413977509
( via browser)
http://www.ebay.com (via python
program)
maxattempts = 5
turl = url
while (maxattempts > 0) :
host,path = urlparse.urlsplit(turl)[1:3]
if len(host.strip()) == 0 :
return None
try:
connection = httplib.HTTPConnection(host,timeout=10)
connection.request("HEAD", path)
resp = connection.getresponse()
except:
return None
maxattempts = maxattempts - 1
if (resp.status >= 300) and (resp.status <= 399):
self.logger.debug("The present %s is a redirection one" %turl)
turl = resp.getheader('location')
elif (resp.status >= 200) and (resp.status <= 299) :
self.logger.debug("The present url %s is a proper one" %turl)
return turl
else :
#some problem with this url
return None
return None
Log file for your reference
2010-02-14 10:29:43,260 - paypallistener.views.MrCrawler - INFO - Bringing down the base URL
2010-02-14 10:29:43,261 - paypallistener.views.MrCrawler - DEBUG - what is the url=http://bit.ly/cDdh1c
2010-02-14 10:29:43,994 - paypallistener.views.MrCrawler - DEBUG - The present http://bit.ly/cDdh1c is a redirection one
2010-02-14 10:29:43,995 - paypallistener.views.MrCrawler - DEBUG - what is the url=http://www.cbtrends.com/get-product.html?productid=reFfJcmpgGt95hoiavbXUAYIMP7OfiQn0qBA8BC7%252BV8%253D&affid=arnishad&tid=arnishad&utm_source=twitterfeed&utm_medium=twitter
2010-02-14 10:29:44,606 - paypallistener.views.MrCrawler - DEBUG - The present http://www.cbtrends.com/get-product.html?productid=reFfJcmpgGt95hoiavbXUAYIMP7OfiQn0qBA8BC7%252BV8%253D&affid=arnishad&tid=arnishad&utm_source=twitterfeed&utm_medium=twitter is a redirection one
2010-02-14 10:29:44,607 - paypallistener.views.MrCrawler - DEBUG - what is the url=http://www.cbtrends.com/
2010-02-14 10:29:45,547 - paypallistener.views.MrCrawler - DEBUG - The present url http://www.cbtrends.com/ is a proper one
http://www.cbtrends.com/
|
[
"Your problem is that when you call urlsplit, your path variable only contains the path and is missing the query.\nSo, instead try:\nimport httplib\nimport urlparse\n\ndef getUrl(url):\n maxattempts = 10\n turl = url\n while (maxattempts > 0) : \n host,path,query = urlparse.urlsplit(turl)[1:4]\n if len(host.strip()) == 0 :\n return None\n try: \n connection = httplib.HTTPConnection(host,timeout=10)\n connection.request(\"GET\", path+'?'+query)\n resp = connection.getresponse()\n except: \n return None \n maxattempts = maxattempts - 1\n if (resp.status >= 300) and (resp.status <= 399):\n turl = resp.getheader('location')\n elif (resp.status >= 200) and (resp.status <= 299) :\n return turl\n else :\n #some problem with this url\n return None \n return None\nprint getUrl('http://bit.ly/cDdh1c')\n\n",
"Your problem comes from this line :\nhost,path = urlparse.urlsplit(turl)[1:3]\n\nYou're leaving out the query string. So on the example log you're providing, the second HEAD request you will do will be on http://www.cbtrends.com/get-product.html without the GET parameters. Open that URL in your browser and you'll see it redirects to http://www.cbtrends.com/.\nYou have to calculate the path using all elements of the tuple returned by urlsplit.\nparts = urlparse.urlsplit(turl)\nhost = parts[1]\npath = \"%s?%s#%s\" % parts[2:5]\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"bit.ly",
"python",
"redirect",
"url"
] |
stackoverflow_0002261823_bit.ly_python_redirect_url.txt
|
Q:
Displaying a cvMatrix containing complex numbers (CV_64FC2)
I'm new to OpenCV, and I would like to compare the results of a python program with my calculations in OpenCV. My matrix contains complex numbers since its the result of a cvDFT. Python handles complex numbers well and displays it with scientific notation. My C++ program is not effective when trying to use std::cout.
I tried to store my numbers array in a std::complex[] instead of a double[] but it is not compiling.
Here is my code, and its result :
CvMat *dft_A;
dft_A = cvCreateMat(5, 5, CV_64FC2); // complex matrix
double a[] = {
0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
2, 2, 2, 2, 2,
3, 3, 3, 3, 3,
4, 4, 4, 4, 4
};
dft_A->data.db = a;
std::cout << "before : " << a[0] << std::endl;
cvDFT( dft_A, dft_A, CV_DXT_FORWARD); // DFT !
std::cout << "after : " << a[0] << std::endl;
>> before : 0
Here is the same in python, with the output :
>>> a = np.mgrid[:5, :5][0]
>>> a
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])
>>> np.fft.fft2(a)
array([[ 50.0 +0.j , 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ],
[-12.5+17.20477401j, 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ],
[-12.5 +4.0614962j , 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ],
[-12.5 -4.0614962j , 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ],
[-12.5-17.20477401j, 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ]])
>>>
The problem is obviously coming from the second cout which is inefficient with the type of date (CV_64FC2 for complex number).
My question is : how can I dump the result so I can check that my python code is doing the same as my cpp/opencv code ?
Thanks !
A:
There is a dft example in OpenCV 2.0 code, which I am also studying right now. Here is a copy paste for you that might give you an idea. As you can see, it uses cvSplit to spilit to real and imaginary components. Hope that helps:
im = cvLoadImage( filename, CV_LOAD_IMAGE_GRAYSCALE );
if( !im )
return -1;
realInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1);
imaginaryInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1);
complexInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 2);
cvScale(im, realInput, 1.0, 0.0);
cvZero(imaginaryInput);
cvMerge(realInput, imaginaryInput, NULL, NULL, complexInput);
dft_M = cvGetOptimalDFTSize( im->height - 1 );
dft_N = cvGetOptimalDFTSize( im->width - 1 );
dft_A = cvCreateMat( dft_M, dft_N, CV_64FC2 );
image_Re = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1);
image_Im = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1);
// copy A to dft_A and pad dft_A with zeros
cvGetSubRect( dft_A, &tmp, cvRect(0,0, im->width, im->height));
cvCopy( complexInput, &tmp, NULL );
if( dft_A->cols > im->width )
{
cvGetSubRect( dft_A, &tmp, cvRect(im->width,0, dft_A->cols - im->width, im->height));
cvZero( &tmp );
}
// no need to pad bottom part of dft_A with zeros because of
// use nonzero_rows parameter in cvDFT() call below
cvDFT( dft_A, dft_A, CV_DXT_FORWARD, complexInput->height );
cvNamedWindow("win", 0);
cvNamedWindow("magnitude", 0);
cvShowImage("win", im);
// Split Fourier in real and imaginary parts
cvSplit( dft_A, image_Re, image_Im, 0, 0 );
// Compute the magnitude of the spectrum Mag = sqrt(Re^2 + Im^2)
cvPow( image_Re, image_Re, 2.0);
cvPow( image_Im, image_Im, 2.0);
cvAdd( image_Re, image_Im, image_Re, NULL);
cvPow( image_Re, image_Re, 0.5 );
// Compute log(1 + Mag)
cvAddS( image_Re, cvScalarAll(1.0), image_Re, NULL ); // 1 + Mag
cvLog( image_Re, image_Re ); // log(1 + Mag)
A:
Have you tried the python bindings for OpenCV?
http://www.exothermia.net/monkeys_and_robots/2009/12/11/working-opencv-python-bindings/
With the bindings you can call OpenCV functions from python and have the results as numpy arrays and then compare them with those from your pure python code. With some tinkering you can wrap your own C code and have it available in python as well.
But if you only want to dump the data, you can probably save the real and imaginary parts as images and read them in python (i'm not very familiar with OpenCV, you have to check its support - and python's - for float images).
|
Displaying a cvMatrix containing complex numbers (CV_64FC2)
|
I'm new to OpenCV, and I would like to compare the results of a python program with my calculations in OpenCV. My matrix contains complex numbers since its the result of a cvDFT. Python handles complex numbers well and displays it with scientific notation. My C++ program is not effective when trying to use std::cout.
I tried to store my numbers array in a std::complex[] instead of a double[] but it is not compiling.
Here is my code, and its result :
CvMat *dft_A;
dft_A = cvCreateMat(5, 5, CV_64FC2); // complex matrix
double a[] = {
0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
2, 2, 2, 2, 2,
3, 3, 3, 3, 3,
4, 4, 4, 4, 4
};
dft_A->data.db = a;
std::cout << "before : " << a[0] << std::endl;
cvDFT( dft_A, dft_A, CV_DXT_FORWARD); // DFT !
std::cout << "after : " << a[0] << std::endl;
>> before : 0
Here is the same in python, with the output :
>>> a = np.mgrid[:5, :5][0]
>>> a
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])
>>> np.fft.fft2(a)
array([[ 50.0 +0.j , 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ],
[-12.5+17.20477401j, 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ],
[-12.5 +4.0614962j , 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ],
[-12.5 -4.0614962j , 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ],
[-12.5-17.20477401j, 0.0 +0.j , 0.0 +0.j ,
0.0 +0.j , 0.0 +0.j ]])
>>>
The problem is obviously coming from the second cout which is inefficient with the type of date (CV_64FC2 for complex number).
My question is : how can I dump the result so I can check that my python code is doing the same as my cpp/opencv code ?
Thanks !
|
[
"There is a dft example in OpenCV 2.0 code, which I am also studying right now. Here is a copy paste for you that might give you an idea. As you can see, it uses cvSplit to spilit to real and imaginary components. Hope that helps:\nim = cvLoadImage( filename, CV_LOAD_IMAGE_GRAYSCALE );\nif( !im )\n return -1;\n\nrealInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1);\nimaginaryInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1);\ncomplexInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 2);\n\ncvScale(im, realInput, 1.0, 0.0);\ncvZero(imaginaryInput);\ncvMerge(realInput, imaginaryInput, NULL, NULL, complexInput);\n\ndft_M = cvGetOptimalDFTSize( im->height - 1 );\ndft_N = cvGetOptimalDFTSize( im->width - 1 );\n\ndft_A = cvCreateMat( dft_M, dft_N, CV_64FC2 );\nimage_Re = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1);\nimage_Im = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1);\n\n// copy A to dft_A and pad dft_A with zeros\ncvGetSubRect( dft_A, &tmp, cvRect(0,0, im->width, im->height));\ncvCopy( complexInput, &tmp, NULL );\nif( dft_A->cols > im->width )\n{\n cvGetSubRect( dft_A, &tmp, cvRect(im->width,0, dft_A->cols - im->width, im->height));\n cvZero( &tmp );\n}\n\n// no need to pad bottom part of dft_A with zeros because of\n// use nonzero_rows parameter in cvDFT() call below\n\ncvDFT( dft_A, dft_A, CV_DXT_FORWARD, complexInput->height );\n\ncvNamedWindow(\"win\", 0);\ncvNamedWindow(\"magnitude\", 0);\ncvShowImage(\"win\", im);\n\n// Split Fourier in real and imaginary parts\ncvSplit( dft_A, image_Re, image_Im, 0, 0 );\n\n// Compute the magnitude of the spectrum Mag = sqrt(Re^2 + Im^2)\ncvPow( image_Re, image_Re, 2.0);\ncvPow( image_Im, image_Im, 2.0);\ncvAdd( image_Re, image_Im, image_Re, NULL);\ncvPow( image_Re, image_Re, 0.5 );\n\n// Compute log(1 + Mag)\ncvAddS( image_Re, cvScalarAll(1.0), image_Re, NULL ); // 1 + Mag\ncvLog( image_Re, image_Re ); // log(1 + Mag)\n\n",
"Have you tried the python bindings for OpenCV?\nhttp://www.exothermia.net/monkeys_and_robots/2009/12/11/working-opencv-python-bindings/\nWith the bindings you can call OpenCV functions from python and have the results as numpy arrays and then compare them with those from your pure python code. With some tinkering you can wrap your own C code and have it available in python as well.\nBut if you only want to dump the data, you can probably save the real and imaginary parts as images and read them in python (i'm not very familiar with OpenCV, you have to check its support - and python's - for float images).\n"
] |
[
4,
0
] |
[] |
[] |
[
"c++",
"numpy",
"opencv",
"python"
] |
stackoverflow_0002048577_c++_numpy_opencv_python.txt
|
Q:
Entry with suggestions
I'm building a small PyGTK application and I have an text input field (currently a ComboBoxEntry) which is populated with a few values that the user should be able to choose from.
I think what I want to do is to filter out the matching fields and only show those ones so the user using the keyboard arrows can choose one of the matching ones.
To give some background the predefined values are a bunch of urls and the user should be able to choose from theese or fill in a new one.
Example:
the predefined urls:
http://www.google.com
http://www.google.com/android
http://www.greatstuff.com
http://www.facebook.com
When a user types 'http://www.g'
The three URLs starting with that string is to be shown (in some way) and when typeing 'http://www.goog' the two starting with that is to be shown
Any Ideas?
A:
An Entry with an EntryCompletion seems more appropriate than a ComboBoxEntry. As always, the tutorial is a good start.
It's very easy to set up when the predefined URLs list is small and fixed.
You just need to populate a ListStore:
# simplified example from the tutorial
import gtk
urls = [
'http://www.google.com',
'http://www.google.com/android',
'http://www.greatstuff.com',
'http://www.facebook.com',
]
liststore = gtk.ListStore(str)
for s in urls:
liststore.append([s])
completion = gtk.EntryCompletion()
completion.set_model(liststore)
completion.set_text_column(0)
entry = gtk.Entry()
entry.set_completion(completion)
# boilerplate
window = gtk.Window()
window.add(entry)
window.connect('destroy', lambda w: gtk.main_quit())
window.show_all()
gtk.main()
Users are not likely to bother typing "http://" or even "www.", so you probably want to match any part of the URL (e.g. just "og" works!):
def match_anywhere(completion, entrystr, iter, data):
modelstr = completion.get_model()[iter][0]
return entrystr in modelstr
completion.set_match_func(match_anywhere, None)
This will test every value in the ListStore for a match, so it's not scalable to huge lists (I mean huge; a 1000 works fine).
Be sure to play with the various options of EntryCompletion, to configure the most pleasant behavior.
A:
You may want to look at how Deskbar Applet's Cuemiac does it.
A:
Well, you obviously want to deal with prefixes so you'll probably want to use some sort of trie. Of course, there are issues to deal with. For instance, after a person has typed in a few letters ( or maybe even just one) you will want to either traverse the rest of the branches of the trie to find suggestions, or have suggestions stored in each node. A lot of these sorts of decisions depend on how many possible suggestions you plan on having.
|
Entry with suggestions
|
I'm building a small PyGTK application and I have an text input field (currently a ComboBoxEntry) which is populated with a few values that the user should be able to choose from.
I think what I want to do is to filter out the matching fields and only show those ones so the user using the keyboard arrows can choose one of the matching ones.
To give some background the predefined values are a bunch of urls and the user should be able to choose from theese or fill in a new one.
Example:
the predefined urls:
http://www.google.com
http://www.google.com/android
http://www.greatstuff.com
http://www.facebook.com
When a user types 'http://www.g'
The three URLs starting with that string is to be shown (in some way) and when typeing 'http://www.goog' the two starting with that is to be shown
Any Ideas?
|
[
"An Entry with an EntryCompletion seems more appropriate than a ComboBoxEntry. As always, the tutorial is a good start.\nIt's very easy to set up when the predefined URLs list is small and fixed.\nYou just need to populate a ListStore:\n# simplified example from the tutorial\nimport gtk\n\nurls = [\n 'http://www.google.com',\n 'http://www.google.com/android',\n 'http://www.greatstuff.com',\n 'http://www.facebook.com',\n ]\nliststore = gtk.ListStore(str)\nfor s in urls:\n liststore.append([s])\n\ncompletion = gtk.EntryCompletion()\ncompletion.set_model(liststore)\ncompletion.set_text_column(0)\n\nentry = gtk.Entry()\nentry.set_completion(completion)\n\n# boilerplate\nwindow = gtk.Window()\nwindow.add(entry)\n\nwindow.connect('destroy', lambda w: gtk.main_quit())\nwindow.show_all()\ngtk.main()\n\nUsers are not likely to bother typing \"http://\" or even \"www.\", so you probably want to match any part of the URL (e.g. just \"og\" works!):\ndef match_anywhere(completion, entrystr, iter, data):\n modelstr = completion.get_model()[iter][0]\n return entrystr in modelstr\ncompletion.set_match_func(match_anywhere, None)\n\nThis will test every value in the ListStore for a match, so it's not scalable to huge lists (I mean huge; a 1000 works fine).\nBe sure to play with the various options of EntryCompletion, to configure the most pleasant behavior.\n",
"You may want to look at how Deskbar Applet's Cuemiac does it.\n",
"Well, you obviously want to deal with prefixes so you'll probably want to use some sort of trie. Of course, there are issues to deal with. For instance, after a person has typed in a few letters ( or maybe even just one) you will want to either traverse the rest of the branches of the trie to find suggestions, or have suggestions stored in each node. A lot of these sorts of decisions depend on how many possible suggestions you plan on having.\n"
] |
[
8,
0,
0
] |
[] |
[] |
[
"pygtk",
"python"
] |
stackoverflow_0002250477_pygtk_python.txt
|
Q:
What's the difference between "while 1" and "while True"?
I've seen two ways to create an infinite loop in Python:
while 1:
do_something()
while True:
do_something()
Is there any difference between these? Is one more pythonic than the other?
A:
Fundamentally it doesn't matter, such minutiae doesn't really affect whether something is 'pythonic' or not.
If you're interested in trivia however, there are some differences.
The builtin boolean type didn't exist till Python 2.3 so code that was intended to run on ancient versions tends to use the while 1: form. You'll see it in the standard library, for instance.
The True and False builtins are not reserved words prior to Python 3 so could be assigned to, changing their value. This helps with the case above because code could do True = 1 for backwards compatibility, but means that the name True needs to be looked up in the globals dictionary every time it is used.
Because of the above restriction, the bytecode the two versions compile to is different in Python 2 as there's an optimisation for constant integers that it can't use for True. Because Python can tell when compiling the 1 that it's always non-zero, it removes the conditional jump and doesn't load the constant at all:
>>> import dis
>>> def while_1():
... while 1:
... pass
...
>>> def while_true():
... while True:
... pass
...
>>> dis.dis(while_1)
2 0 SETUP_LOOP 5 (to 8)
3 >> 3 JUMP_ABSOLUTE 3
6 POP_TOP
7 POP_BLOCK
>> 8 LOAD_CONST 0 (None)
11 RETURN_VALUE
>>> dis.dis(while_true)
2 0 SETUP_LOOP 12 (to 15)
>> 3 LOAD_GLOBAL 0 (True)
6 JUMP_IF_FALSE 4 (to 13)
9 POP_TOP
3 10 JUMP_ABSOLUTE 3
>> 13 POP_TOP
14 POP_BLOCK
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
So, while True: is a little easier to read, and while 1: is a bit kinder to old versions of Python. As you're unlikely to need to run on Python 2.2 these days or need to worry about the bytecode count of your loops, the former is marginally preferable.
A:
The most pythonic way will always be the most readable. Use while True:
A:
It doesn't really matter. Neither is hard to read or understand, though personally I'd always use while True, which is a bit more explicit.
More generally, a whole lot of while–break loops people write in Python could be something else. Sometimes I see people write i = 0; while True: i += 1 ..., which can be replaced with for i in itertools.count() and people writing while True: foo = fun() if foo is None: break when this can be written for foo in iter(fun, None), which requires learning but has less boilerplate and opportunity for silly mistakes.
A:
Neither.
Both of them mean I have to scan the code looking for the break, instead of being able to see the stop condition right where it belongs.
I try to avoid this kind of thing wherever possible, and if it's not possible, let the code speak for itself like this:
while not found_answer:
check_number += 1
if check_number == 42:
found_answer = True
Edit: It seems that the word "avoid" above wasn't clear enough. Using a basically infinite loop and leaving it from somewhere within the loop (using break) should usually be avoided altogether. Sometimes that isn't possible. In that case, I like to use something like the code above, which, however, still represents the same concept – the above code is nothing more than a compromise – but at least, I can show the purpose of the loop at the beginning – just like I wouldn't call a function do_something_with_args(*args).
A:
IMO the second option is more obvious.
If you could get rid of the while and write more compact code, that might be more pythonic.
For example:
# Get the even numbers in the range 1..10
# Version 1
l = []
n = 1
while 1:
if n % 2 == 0: l.append(n)
n += 1
if n > 10: break
print l
# Version 2
print [i for i in range(1, 11) if i % 2 == 0]
# Version 3
print range(2, 11, 2)
A:
I think this is mostly a matter of style. Both should be easily understandable as an infinite loop.
However, personally I prefer the second option. That's because it just takes a mental micro-step less to understand, especially for programmers without C background.
A:
The first one will work also in those early versions where True is not yet defined.
A:
If you have an algorithm that is suppose to terminate in a finite time, I would recommend this, which is always safer than while True:
maxiter = 1000
for i in xrange(maxiter):
# your code
# on success:
break
else:
# that algorithm has not finished in maxiter steps! do something accordingly
A:
I believe the second expression is more explicit, and thus more pythonic.
A:
This is only a matter of style, any programming beginner will understand either option.
But the second option will only work if True wasn't assigned to False, which was possible until Python 3:
>>> True = False
>>> True
False
A:
The better way is "while True" with a conditional break out of the loop.
|
What's the difference between "while 1" and "while True"?
|
I've seen two ways to create an infinite loop in Python:
while 1:
do_something()
while True:
do_something()
Is there any difference between these? Is one more pythonic than the other?
|
[
"Fundamentally it doesn't matter, such minutiae doesn't really affect whether something is 'pythonic' or not.\nIf you're interested in trivia however, there are some differences.\n\nThe builtin boolean type didn't exist till Python 2.3 so code that was intended to run on ancient versions tends to use the while 1: form. You'll see it in the standard library, for instance.\nThe True and False builtins are not reserved words prior to Python 3 so could be assigned to, changing their value. This helps with the case above because code could do True = 1 for backwards compatibility, but means that the name True needs to be looked up in the globals dictionary every time it is used.\nBecause of the above restriction, the bytecode the two versions compile to is different in Python 2 as there's an optimisation for constant integers that it can't use for True. Because Python can tell when compiling the 1 that it's always non-zero, it removes the conditional jump and doesn't load the constant at all:\n>>> import dis\n>>> def while_1():\n... while 1:\n... pass\n...\n>>> def while_true():\n... while True:\n... pass\n...\n>>> dis.dis(while_1)\n 2 0 SETUP_LOOP 5 (to 8)\n\n 3 >> 3 JUMP_ABSOLUTE 3\n 6 POP_TOP\n 7 POP_BLOCK\n >> 8 LOAD_CONST 0 (None)\n 11 RETURN_VALUE\n>>> dis.dis(while_true)\n 2 0 SETUP_LOOP 12 (to 15)\n >> 3 LOAD_GLOBAL 0 (True)\n 6 JUMP_IF_FALSE 4 (to 13)\n 9 POP_TOP\n\n 3 10 JUMP_ABSOLUTE 3\n >> 13 POP_TOP\n 14 POP_BLOCK\n >> 15 LOAD_CONST 0 (None)\n 18 RETURN_VALUE\n\n\nSo, while True: is a little easier to read, and while 1: is a bit kinder to old versions of Python. As you're unlikely to need to run on Python 2.2 these days or need to worry about the bytecode count of your loops, the former is marginally preferable.\n",
"The most pythonic way will always be the most readable. Use while True:\n",
"It doesn't really matter. Neither is hard to read or understand, though personally I'd always use while True, which is a bit more explicit.\nMore generally, a whole lot of while–break loops people write in Python could be something else. Sometimes I see people write i = 0; while True: i += 1 ..., which can be replaced with for i in itertools.count() and people writing while True: foo = fun() if foo is None: break when this can be written for foo in iter(fun, None), which requires learning but has less boilerplate and opportunity for silly mistakes.\n",
"Neither.\nBoth of them mean I have to scan the code looking for the break, instead of being able to see the stop condition right where it belongs.\nI try to avoid this kind of thing wherever possible, and if it's not possible, let the code speak for itself like this:\nwhile not found_answer:\n check_number += 1\n if check_number == 42:\n found_answer = True\n\nEdit: It seems that the word \"avoid\" above wasn't clear enough. Using a basically infinite loop and leaving it from somewhere within the loop (using break) should usually be avoided altogether. Sometimes that isn't possible. In that case, I like to use something like the code above, which, however, still represents the same concept – the above code is nothing more than a compromise – but at least, I can show the purpose of the loop at the beginning – just like I wouldn't call a function do_something_with_args(*args).\n",
"IMO the second option is more obvious.\nIf you could get rid of the while and write more compact code, that might be more pythonic.\nFor example:\n# Get the even numbers in the range 1..10\n# Version 1\nl = []\nn = 1\nwhile 1:\n if n % 2 == 0: l.append(n)\n n += 1\n if n > 10: break\nprint l\n\n# Version 2\nprint [i for i in range(1, 11) if i % 2 == 0]\n\n# Version 3\nprint range(2, 11, 2)\n\n",
"I think this is mostly a matter of style. Both should be easily understandable as an infinite loop. \nHowever, personally I prefer the second option. That's because it just takes a mental micro-step less to understand, especially for programmers without C background.\n",
"The first one will work also in those early versions where True is not yet defined. \n",
"If you have an algorithm that is suppose to terminate in a finite time, I would recommend this, which is always safer than while True:\nmaxiter = 1000\nfor i in xrange(maxiter):\n # your code\n # on success:\n break\nelse:\n # that algorithm has not finished in maxiter steps! do something accordingly\n\n",
"I believe the second expression is more explicit, and thus more pythonic. \n",
"This is only a matter of style, any programming beginner will understand either option.\nBut the second option will only work if True wasn't assigned to False, which was possible until Python 3:\n>>> True = False\n>>> True\nFalse\n\n",
"The better way is \"while True\" with a conditional break out of the loop.\n"
] |
[
47,
11,
5,
4,
3,
2,
2,
2,
1,
0,
0
] |
[] |
[] |
[
"infinite_loop",
"python",
"while_loop"
] |
stackoverflow_0002261987_infinite_loop_python_while_loop.txt
|
Q:
How to parse just the text from a Word Doc using Python?
When you try opening a MS Word document or for that matter most Windows file formats, you will see gibberish as given below broken intermittently by the actual text. I need to extract the text that goes in and want to ignore the gibberish -- which is something like given below. How do I extract only the text that matters, and ignore rest of the stuff. Please advise.
Here's a sample of open("sample.doc",r").read() of a word doc. Thanks
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00In an Interesting news,his is the first time we polled Indian channel community for their preferred memory supplier. Transcend came a close second, was seen to be more popular among class A city based resellers, was also the most recalled memory brand among customers according to resellers. However Transcend channels complained of parallel imports and constant unavailability of the products in grey x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
A:
The tool that seems the most viable, particularly if you need an all python solution is OleFileIO.
A:
doc is a binary format, it's not a markup language or something.
Specs: http://www.microsoft.com/interop/docs/OfficeBinaryFormats.mspx
A:
There is no generic why to extract
information from every file format.
You need to know the format to know
how to extract the information.
Just wanted to state that first. So what you should look for is libraries and software that can convert/extract the information you want. And as mentioned by Ofir MicroSoft have tools for that for their formats.
But if you can not do this and want to take the chance that there is text visible in the file that you think is interesting to read you could do a normal read and look for sequences of bytes that will build text. Then comes the question, what languages/charset should I support support in my hunt for text. Is it multi-byte text?
The easy start is to loop through the data and look for sequences of [a-zA-z0-9_- ] to find the text. But word is probably multi-byte. So you should scan double byte as one char.
Note: some of the new formats like open office and docx is multiple files in a compressed container. So you need to de-compress the file first, and scan XML documents after the text you looking for.
A:
Word doc is a compressed format. You need to uncompress it first to get the real data (try open a doc file in a program like winrar, and you'll see it contains multiple files.
It even seems to be XML, so reading the format should not be that hard, although I'm not sure if you get all the data this way.
A:
I had a similar problem, needing to query hundreds of Word documents. I converted the Word files to text files and used normal text parsing tools. Worked well.
|
How to parse just the text from a Word Doc using Python?
|
When you try opening a MS Word document or for that matter most Windows file formats, you will see gibberish as given below broken intermittently by the actual text. I need to extract the text that goes in and want to ignore the gibberish -- which is something like given below. How do I extract only the text that matters, and ignore rest of the stuff. Please advise.
Here's a sample of open("sample.doc",r").read() of a word doc. Thanks
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00In an Interesting news,his is the first time we polled Indian channel community for their preferred memory supplier. Transcend came a close second, was seen to be more popular among class A city based resellers, was also the most recalled memory brand among customers according to resellers. However Transcend channels complained of parallel imports and constant unavailability of the products in grey x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
|
[
"The tool that seems the most viable, particularly if you need an all python solution is OleFileIO.\n",
"doc is a binary format, it's not a markup language or something.\nSpecs: http://www.microsoft.com/interop/docs/OfficeBinaryFormats.mspx\n",
"\nThere is no generic why to extract\n information from every file format.\n You need to know the format to know\n how to extract the information.\n\nJust wanted to state that first. So what you should look for is libraries and software that can convert/extract the information you want. And as mentioned by Ofir MicroSoft have tools for that for their formats.\nBut if you can not do this and want to take the chance that there is text visible in the file that you think is interesting to read you could do a normal read and look for sequences of bytes that will build text. Then comes the question, what languages/charset should I support support in my hunt for text. Is it multi-byte text?\nThe easy start is to loop through the data and look for sequences of [a-zA-z0-9_- ] to find the text. But word is probably multi-byte. So you should scan double byte as one char.\nNote: some of the new formats like open office and docx is multiple files in a compressed container. So you need to de-compress the file first, and scan XML documents after the text you looking for.\n",
"Word doc is a compressed format. You need to uncompress it first to get the real data (try open a doc file in a program like winrar, and you'll see it contains multiple files.\nIt even seems to be XML, so reading the format should not be that hard, although I'm not sure if you get all the data this way.\n",
"I had a similar problem, needing to query hundreds of Word documents. I converted the Word files to text files and used normal text parsing tools. Worked well.\n"
] |
[
3,
1,
0,
0,
0
] |
[] |
[] |
[
"ms_word",
"python",
"regex",
"screen_scraping"
] |
stackoverflow_0002261650_ms_word_python_regex_screen_scraping.txt
|
Q:
How can I detect what other copy of Python script is already running
I have a script. It uses GTK. And I need to know if another copy of scrip starts. If it starts window will extend.
Please, tell me the way I can detect it.
A:
You could use a D-Bus service. Your script would start a new service if none is found running in the current session, and otherwise send a D-Bus message to the running instace (that can send "anything", including strings, lists, dicts).
The GTK-based library libunique (missing Python bindings?) uses this approach in its implementation of "unique" applications.
A:
You can use a PID file to determine if the application is already running (just search for "python daemon" on Google to find some working implementations).
If you detected that the program is already running, you can communicate with the running instance using named pipes.
A:
The new copy could search for running copies, fire a SIGUSER signal and trigger a callback in your running process that then handles all the magic.
See the signal library for details and the list of things that can go wrong.
A:
I've done that using several ways depending upon the scenario
In one case my script had to listen on a TCP port. So I'd just see if the port was available it'd mean it is a new copy. This was sufficient for me but in certain cases, if the port is already in use, it might be because some other kind of application is listening on that port. You can use OS calls to find out who is listening on the port or try sending data and checking the response.
In another case I used PID file. Just decide a location and a filename, and everytime your script starts, read that file to get a PID. If that PID is running, it means another copy is already there. Otherwise create that file and write your process ID in it. This is pretty simple. If you are using django then you can simply use django's daemonizer: "from django.utils import daemonize". Otherwise you can use this script: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
|
How can I detect what other copy of Python script is already running
|
I have a script. It uses GTK. And I need to know if another copy of scrip starts. If it starts window will extend.
Please, tell me the way I can detect it.
|
[
"You could use a D-Bus service. Your script would start a new service if none is found running in the current session, and otherwise send a D-Bus message to the running instace (that can send \"anything\", including strings, lists, dicts).\nThe GTK-based library libunique (missing Python bindings?) uses this approach in its implementation of \"unique\" applications.\n",
"You can use a PID file to determine if the application is already running (just search for \"python daemon\" on Google to find some working implementations).\nIf you detected that the program is already running, you can communicate with the running instance using named pipes.\n",
"The new copy could search for running copies, fire a SIGUSER signal and trigger a callback in your running process that then handles all the magic.\nSee the signal library for details and the list of things that can go wrong.\n",
"I've done that using several ways depending upon the scenario\n\nIn one case my script had to listen on a TCP port. So I'd just see if the port was available it'd mean it is a new copy. This was sufficient for me but in certain cases, if the port is already in use, it might be because some other kind of application is listening on that port. You can use OS calls to find out who is listening on the port or try sending data and checking the response. \nIn another case I used PID file. Just decide a location and a filename, and everytime your script starts, read that file to get a PID. If that PID is running, it means another copy is already there. Otherwise create that file and write your process ID in it. This is pretty simple. If you are using django then you can simply use django's daemonizer: \"from django.utils import daemonize\". Otherwise you can use this script: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/\n\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002261997_python.txt
|
Q:
How can I get the text between tags using python SAX parser?
What I need is just get the text of the corresponding tag and persist it into database. Since the xml file is big (4.5GB) I'm using sax. I used the characters method to get the text and put it in a dictionary. However when I'm printing the text at the endElement method I'm getting a new line instead of the text.
Here is my code:
def characters(self,content):
text = unescape(content))
self.map[self.tag]=text
def startElement(self, name, attrs):
self.tag = name
def endElement (self, name)
if (name=="sometag")
print self.map[name]
Thanks in advance.
A:
The text in the tag is chunked by the SAX processor. characters might be called multiple times.
You need to do something like:
def startElement(self, name, attrs):
self.map[name] = ''
self.tag = name
def characters(self, content):
self.map[self.tag] += content
def endElement(self, name):
print self.map[name]
|
How can I get the text between tags using python SAX parser?
|
What I need is just get the text of the corresponding tag and persist it into database. Since the xml file is big (4.5GB) I'm using sax. I used the characters method to get the text and put it in a dictionary. However when I'm printing the text at the endElement method I'm getting a new line instead of the text.
Here is my code:
def characters(self,content):
text = unescape(content))
self.map[self.tag]=text
def startElement(self, name, attrs):
self.tag = name
def endElement (self, name)
if (name=="sometag")
print self.map[name]
Thanks in advance.
|
[
"The text in the tag is chunked by the SAX processor. characters might be called multiple times.\nYou need to do something like:\ndef startElement(self, name, attrs):\n self.map[name] = ''\n self.tag = name\n\ndef characters(self, content):\n self.map[self.tag] += content\n\ndef endElement(self, name):\n print self.map[name]\n\n"
] |
[
8
] |
[] |
[] |
[
"python",
"sax",
"xml"
] |
stackoverflow_0002262577_python_sax_xml.txt
|
Q:
unexpected list appearing in python loop
I am new to python and have the following piece of test code featuring a nested loop and I'm getting some unexpected lists generated:
import pybel
import math
import openbabel
search = ["CCC","CCCC"]
matches = []
#n = 0
#b = 0
print search
for n in search:
print "n=",n
smarts = pybel.Smarts(n)
allmol = [mol for mol in pybel.readfile("sdf", "zincsdf2mols.sdf.txt")]
for b in allmol:
matches = smarts.findall(b)
print matches, "\n"
Essentially, the list "search" is a couple of strings I am looking to match in some molecules and I want to iterate over both strings in every molecule contained in allmol using the pybel software. However, the result I get is:
['CCC', 'CCCC']
n= CCC
[(1, 2, 28), (1, 2, 4), (2, 4, 5), (4, 2, 28)]
[]
n= CCCC
[(1, 2, 4, 5), (5, 4, 2, 28)]
[]
as expected except for a couple of extra empty lists slotted in which are messing me up and I cannot see where they are coming from. They appear after the "\n" so are not an artefact of the smarts.findall(). What am I doing wrong?
thanks for any help.
A:
allmol has 2 items and so you're looping twice with matches being an empty list the second time.
Notice how the newline is printed after each; changing that "\n" to "<-- matches" may clear things up for you:
print matches, "<-- matches"
# or, more commonly:
print "matches:", matches
|
unexpected list appearing in python loop
|
I am new to python and have the following piece of test code featuring a nested loop and I'm getting some unexpected lists generated:
import pybel
import math
import openbabel
search = ["CCC","CCCC"]
matches = []
#n = 0
#b = 0
print search
for n in search:
print "n=",n
smarts = pybel.Smarts(n)
allmol = [mol for mol in pybel.readfile("sdf", "zincsdf2mols.sdf.txt")]
for b in allmol:
matches = smarts.findall(b)
print matches, "\n"
Essentially, the list "search" is a couple of strings I am looking to match in some molecules and I want to iterate over both strings in every molecule contained in allmol using the pybel software. However, the result I get is:
['CCC', 'CCCC']
n= CCC
[(1, 2, 28), (1, 2, 4), (2, 4, 5), (4, 2, 28)]
[]
n= CCCC
[(1, 2, 4, 5), (5, 4, 2, 28)]
[]
as expected except for a couple of extra empty lists slotted in which are messing me up and I cannot see where they are coming from. They appear after the "\n" so are not an artefact of the smarts.findall(). What am I doing wrong?
thanks for any help.
|
[
"allmol has 2 items and so you're looping twice with matches being an empty list the second time.\nNotice how the newline is printed after each; changing that \"\\n\" to \"<-- matches\" may clear things up for you:\nprint matches, \"<-- matches\"\n# or, more commonly:\nprint \"matches:\", matches\n\n"
] |
[
2
] |
[
"Perhaps it is supposed to end like this\nfor b in allmol: \n matches.append(smarts.findall(b)) \nprint matches, \"\\n\"\n\notherwise I'm not sure why you'd initialise matches to an empty list\nIf that is the case, you can instead write\nmatches = [smarts.findall(b) for b in allmol]\nprint matches\n\nanother possibility is that the file is ending in an empty line\nfor b in allmol: \n if not b.strip(): continue\n matches.append(smarts.findall(b)) \n print matches, \"\\n\"\n\n"
] |
[
-1
] |
[
"for_loop",
"list",
"openbabel",
"python"
] |
stackoverflow_0002262509_for_loop_list_openbabel_python.txt
|
Q:
How to make my Python unit tests to import the tested modules if they are in sister folders?
I am still getting my head around the import statement. If I have 2 folders in the same level:
src
test
How to make the py files in test import the modules in src?
Is there a better solution (like put a folder inside another?)
A:
The code you want is for using src/module_name.py
from src import module_name
and the root directory is on your PYTHONPATH e.g. you run from the root directory
Your directory structure is what I use but with the model name instead from src. I got this structure from J Calderone's blog and
A:
Try this out:
import sys
import os
sys.path.append(os.path.join('..', 'src'))
import module_in_src_folder
edited to support any platform
A:
I have exactly the same situation as the OP with all the python projects I write:
Project Folder
src
test
All modules, whether in src, or test, or subfolders of these always use the form of import that Mark shows in his answer:
from src import module_name
What I have done is write a module that sits in Project Folder and recursively discovers all the test modules within the test folder and gets unittest to run all those tests. As python is running in Project Folder, then modules are relative to the working directory.
This means that the tests are just like any other client that wants to modules from src.
|
How to make my Python unit tests to import the tested modules if they are in sister folders?
|
I am still getting my head around the import statement. If I have 2 folders in the same level:
src
test
How to make the py files in test import the modules in src?
Is there a better solution (like put a folder inside another?)
|
[
"The code you want is for using src/module_name.py\nfrom src import module_name \n\nand the root directory is on your PYTHONPATH e.g. you run from the root directory\nYour directory structure is what I use but with the model name instead from src. I got this structure from J Calderone's blog and\n",
"Try this out:\nimport sys\nimport os\nsys.path.append(os.path.join('..', 'src'))\nimport module_in_src_folder\n\nedited to support any platform\n",
"I have exactly the same situation as the OP with all the python projects I write:\n\nProject Folder\n\n\nsrc\ntest\n\n\nAll modules, whether in src, or test, or subfolders of these always use the form of import that Mark shows in his answer:\nfrom src import module_name\n\nWhat I have done is write a module that sits in Project Folder and recursively discovers all the test modules within the test folder and gets unittest to run all those tests. As python is running in Project Folder, then modules are relative to the working directory.\nThis means that the tests are just like any other client that wants to modules from src.\n"
] |
[
10,
6,
0
] |
[] |
[] |
[
"code_organization",
"directory",
"import",
"python",
"python_unittest"
] |
stackoverflow_0002262546_code_organization_directory_import_python_python_unittest.txt
|
Q:
Python equivalent of C code from Bit Twiddling Hacks?
I have a bit counting method that I am trying to make as fast as possible. I want to try the algorithm below from Bit Twiddling Hacks, but I don't know C. What is 'type T' and what is the python equivalent of (T)~(T)0/3?
A generalization of the best bit
counting method to integers of
bit-widths upto 128 (parameterized by
type T) is this:
v = v - ((v >> 1) & (T)~(T)0/3); // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(v) - 1) * CHAR_BIT; // count
A:
T is a integer type, which I'm assuming is unsigned. Since this is C, it'll be fixed width, probably (but not necessarily) one of 8, 16, 32, 64 or 128. The fragment (T)~(T)0 that appears repeatedly in that code sample just gives the value 2**N-1, where N is the width of the type T. I suspect that the code may require that N be a multiple of 8
for correct operation.
Here's a direct translation of the given code into Python, parameterized in terms of N, the width of T in bits.
def count_set_bits(v, N=128):
mask = (1 << N) - 1
v = v - ((v >> 1) & mask//3)
v = (v & mask//15*3) + ((v >> 2) & mask//15*3)
v = (v + (v >> 4)) & mask//255*15
return (mask & v * (mask//255)) >> (N//8 - 1) * 8
Caveats:
(1) the above will only work for numbers up to 2**128. You might be able to generalize it for larger numbers, though.
(2) There are obvious inefficiencies: for example, 'mask//15' is computed twice. This doesn't matter for C, of course, because the compiler will almost certainly do the division at compile time rather than run time, but Python's peephole optimizer may not be so clever.
(3) The fastest C method may well not translate to the fastest Python method. For Python speed, you should probably be looking for an algorithm that minimizes the number of Python bitwise operations. As Alexander Gessler said: profile!
A:
What you copied is a template for generating code. It's not a good idea to transliterate that template into another language and expect it to run fast. Let's expand the template.
(T)~(T)0 means "as many 1-bits as fit in type T". The algorithm needs 4 masks which we will compute for the various T-sizes we might be interested in.
>>> for N in (8, 16, 32, 64, 128):
... all_ones = (1 << N) - 1
... constants = ' '.join([hex(x) for x in [
... all_ones // 3,
... all_ones // 15 * 3,
... all_ones // 255 * 15,
... all_ones // 255,
... ]])
... print N, constants
...
8 0x55 0x33 0xf 0x1
16 0x5555 0x3333 0xf0f 0x101
32 0x55555555L 0x33333333L 0xf0f0f0fL 0x1010101L
64 0x5555555555555555L 0x3333333333333333L 0xf0f0f0f0f0f0f0fL 0x101010101010101L
128 0x55555555555555555555555555555555L 0x33333333333333333333333333333333L 0xf0f0f0f0f0f0f0f0f0f0f0f0f0f0f0fL 0x1010101010101010101010101010101L
>>>
You'll notice that the masks generated for the 32-bit case match those in the hardcoded 32-bit C code. Implementation detail: lose the L suffix from the 32-bit masks (Python 2.x) and lose all L suffixes for Python 3.x.
As you can see the whole template and (T)~(T)0 caper is merely obfuscatory sophistry. Put quite simply, for a k-byte type, you need 4 masks:
k bytes each 0x55
k bytes each 0x33
k bytes each 0x0f
k bytes each 0x01
and the final shift is merely N-8 (i.e. 8*(k-1)) bits. Aside: I doubt if the template code would actually work on a machine whose CHAR_BIT was not 8, but there aren't very many of those around these days.
Update: There is another point that affects the correctness and the speed when transliterating such algorithms from C to Python. The C algorithms often assume unsigned integers. In C, operations on unsigned integers work silently modulo 2**N. In other words, only the least significant N bits are retained. No overflow exceptions. Many bit twiddling algorithms rely on this. However (a) Python's int and long are signed (b) old Python 2.X will raise an exception, recent Python 2.Xs will silently promote int to long and Python 3.x int == Python 2.x long.
The correctness problem usually requires register &= all_ones at least once in the Python code. Careful analysis is often required to determine the minimal correct masking.
Working in long instead of int doesn't do much for efficiency. You'll notice that the algorithm for 32 bits will return a long answer even from input of 0, because the 32-bits all_ones is long.
|
Python equivalent of C code from Bit Twiddling Hacks?
|
I have a bit counting method that I am trying to make as fast as possible. I want to try the algorithm below from Bit Twiddling Hacks, but I don't know C. What is 'type T' and what is the python equivalent of (T)~(T)0/3?
A generalization of the best bit
counting method to integers of
bit-widths upto 128 (parameterized by
type T) is this:
v = v - ((v >> 1) & (T)~(T)0/3); // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(v) - 1) * CHAR_BIT; // count
|
[
"T is a integer type, which I'm assuming is unsigned. Since this is C, it'll be fixed width, probably (but not necessarily) one of 8, 16, 32, 64 or 128. The fragment (T)~(T)0 that appears repeatedly in that code sample just gives the value 2**N-1, where N is the width of the type T. I suspect that the code may require that N be a multiple of 8\nfor correct operation.\nHere's a direct translation of the given code into Python, parameterized in terms of N, the width of T in bits.\ndef count_set_bits(v, N=128):\n mask = (1 << N) - 1\n\n v = v - ((v >> 1) & mask//3)\n v = (v & mask//15*3) + ((v >> 2) & mask//15*3)\n v = (v + (v >> 4)) & mask//255*15\n return (mask & v * (mask//255)) >> (N//8 - 1) * 8\n\nCaveats:\n(1) the above will only work for numbers up to 2**128. You might be able to generalize it for larger numbers, though.\n(2) There are obvious inefficiencies: for example, 'mask//15' is computed twice. This doesn't matter for C, of course, because the compiler will almost certainly do the division at compile time rather than run time, but Python's peephole optimizer may not be so clever.\n(3) The fastest C method may well not translate to the fastest Python method. For Python speed, you should probably be looking for an algorithm that minimizes the number of Python bitwise operations. As Alexander Gessler said: profile!\n",
"What you copied is a template for generating code. It's not a good idea to transliterate that template into another language and expect it to run fast. Let's expand the template.\n(T)~(T)0 means \"as many 1-bits as fit in type T\". The algorithm needs 4 masks which we will compute for the various T-sizes we might be interested in.\n>>> for N in (8, 16, 32, 64, 128):\n... all_ones = (1 << N) - 1\n... constants = ' '.join([hex(x) for x in [\n... all_ones // 3,\n... all_ones // 15 * 3,\n... all_ones // 255 * 15,\n... all_ones // 255,\n... ]])\n... print N, constants\n...\n8 0x55 0x33 0xf 0x1\n16 0x5555 0x3333 0xf0f 0x101\n32 0x55555555L 0x33333333L 0xf0f0f0fL 0x1010101L\n64 0x5555555555555555L 0x3333333333333333L 0xf0f0f0f0f0f0f0fL 0x101010101010101L\n128 0x55555555555555555555555555555555L 0x33333333333333333333333333333333L 0xf0f0f0f0f0f0f0f0f0f0f0f0f0f0f0fL 0x1010101010101010101010101010101L\n>>>\n\nYou'll notice that the masks generated for the 32-bit case match those in the hardcoded 32-bit C code. Implementation detail: lose the L suffix from the 32-bit masks (Python 2.x) and lose all L suffixes for Python 3.x.\nAs you can see the whole template and (T)~(T)0 caper is merely obfuscatory sophistry. Put quite simply, for a k-byte type, you need 4 masks:\nk bytes each 0x55\nk bytes each 0x33\nk bytes each 0x0f\nk bytes each 0x01\n\nand the final shift is merely N-8 (i.e. 8*(k-1)) bits. Aside: I doubt if the template code would actually work on a machine whose CHAR_BIT was not 8, but there aren't very many of those around these days.\nUpdate: There is another point that affects the correctness and the speed when transliterating such algorithms from C to Python. The C algorithms often assume unsigned integers. In C, operations on unsigned integers work silently modulo 2**N. In other words, only the least significant N bits are retained. No overflow exceptions. Many bit twiddling algorithms rely on this. However (a) Python's int and long are signed (b) old Python 2.X will raise an exception, recent Python 2.Xs will silently promote int to long and Python 3.x int == Python 2.x long.\nThe correctness problem usually requires register &= all_ones at least once in the Python code. Careful analysis is often required to determine the minimal correct masking.\nWorking in long instead of int doesn't do much for efficiency. You'll notice that the algorithm for 32 bits will return a long answer even from input of 0, because the 32-bits all_ones is long.\n"
] |
[
7,
2
] |
[] |
[] |
[
"bit_manipulation",
"c",
"python"
] |
stackoverflow_0002261671_bit_manipulation_c_python.txt
|
Q:
mod_python not detecting files when using open()
I am trying to open a file I have in my /var/www/ directory named cardlist.xml.
this is the code I am using.
import cgi
import os
open("./cardlist.xml", "r")
def crawlXml():
return 0
My error is
MOD_PYTHON ERROR
ProcessId: 11361 Interpreter:
'127.0.1.1'
ServerName: '127.0.1.1'
DocumentRoot: '/var/www'
URI: '/test.py/crawlXml'
Location: None Directory:
'/var/www/' Filename:
'/var/www/test.py' PathInfo:
'/crawlXml'
Phase: 'PythonHandler'
Handler: 'mod_python.publisher'
Traceback (most recent call last):
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 1229, in _process_target
result = _execute_target(config, req, object, arg)
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 1128, in _execute_target
result = object(arg)
File
"/usr/lib/python2.6/dist-packages/mod_python/publisher.py",
line 204, in handler
module = page_cache[req]
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 1059, in getitem
return import_module(req.filename)
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 296, in import_module
log, import_path)
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 680, in import_module
execfile(file, module.dict)
File "/var/www/test.py", line 4, in
open("./cardlist.xml", "r")
IOError: [Errno 2] No such file or
directory: './cardlist.xml'
MODULE CACHE DETAILS
Accessed: Sun Feb 14 16:59:58
2010 Generation: 19
_mp_27cc55c5447f9e0aa13691719290c225 { FileName: '/var/www/test.py'
Instance: 85 [RELOAD]
Generation: 19 [ERROR] Modified:
Sun Feb 14 16:40:17 2010 Imported:
Sun Feb 14 16:22:38 2010 }
This is the result of ls -la in the
/var/www/ directory drwxr-xr-x 3 root
root 4096 2010-02-14 16:40 .
drwxr-xr-x 16 root root 4096
2010-02-14 15:05 ..
-rwxr-xr-x 1 root root 4612891 2010-01-30 16:39 cardlist.xml
drwxrwx--- 3 root root 4096
2010-02-14 14:31 mtg
-rw-r--r-- 1 root root 110 2010-02-14 16:40 test.py
-rw-r--r-- 1 root root 111 2010-02-14 16:32 test.py~
Does anyone know what is going wrong?
A:
The working directory might not be the directory of the file. Try using an absolute path, or an explicitly relative path:
import os.path
open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cardlist.xml'))
|
mod_python not detecting files when using open()
|
I am trying to open a file I have in my /var/www/ directory named cardlist.xml.
this is the code I am using.
import cgi
import os
open("./cardlist.xml", "r")
def crawlXml():
return 0
My error is
MOD_PYTHON ERROR
ProcessId: 11361 Interpreter:
'127.0.1.1'
ServerName: '127.0.1.1'
DocumentRoot: '/var/www'
URI: '/test.py/crawlXml'
Location: None Directory:
'/var/www/' Filename:
'/var/www/test.py' PathInfo:
'/crawlXml'
Phase: 'PythonHandler'
Handler: 'mod_python.publisher'
Traceback (most recent call last):
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 1229, in _process_target
result = _execute_target(config, req, object, arg)
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 1128, in _execute_target
result = object(arg)
File
"/usr/lib/python2.6/dist-packages/mod_python/publisher.py",
line 204, in handler
module = page_cache[req]
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 1059, in getitem
return import_module(req.filename)
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 296, in import_module
log, import_path)
File
"/usr/lib/python2.6/dist-packages/mod_python/importer.py",
line 680, in import_module
execfile(file, module.dict)
File "/var/www/test.py", line 4, in
open("./cardlist.xml", "r")
IOError: [Errno 2] No such file or
directory: './cardlist.xml'
MODULE CACHE DETAILS
Accessed: Sun Feb 14 16:59:58
2010 Generation: 19
_mp_27cc55c5447f9e0aa13691719290c225 { FileName: '/var/www/test.py'
Instance: 85 [RELOAD]
Generation: 19 [ERROR] Modified:
Sun Feb 14 16:40:17 2010 Imported:
Sun Feb 14 16:22:38 2010 }
This is the result of ls -la in the
/var/www/ directory drwxr-xr-x 3 root
root 4096 2010-02-14 16:40 .
drwxr-xr-x 16 root root 4096
2010-02-14 15:05 ..
-rwxr-xr-x 1 root root 4612891 2010-01-30 16:39 cardlist.xml
drwxrwx--- 3 root root 4096
2010-02-14 14:31 mtg
-rw-r--r-- 1 root root 110 2010-02-14 16:40 test.py
-rw-r--r-- 1 root root 111 2010-02-14 16:32 test.py~
Does anyone know what is going wrong?
|
[
"The working directory might not be the directory of the file. Try using an absolute path, or an explicitly relative path:\nimport os.path\nopen(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cardlist.xml'))\n\n"
] |
[
3
] |
[] |
[] |
[
"apache2",
"mod_python",
"python"
] |
stackoverflow_0002263005_apache2_mod_python_python.txt
|
Q:
How can I send data to a base template in Django?
Let's say I have a django site, and a base template for all pages with a footer that I want to display a list of the top 5 products on my site. How would I go about sending that list to the base template to render? Does every view need to send that data to the render_to_response? Should I use a template_tag? How would you do it?
A:
You should use a custom context processor. With this you can set a variable e.g. top_products that will be available in all your templates.
E.g.
# in project/app/context_processors.py
from app.models import Product
def top_products(request):
return {'top_products': Products.objects.all()} # of course some filter here
In your settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
# maybe other here
'app.context_processors.top_products',
)
And in your template:
{% for product in top_products %}
...
|
How can I send data to a base template in Django?
|
Let's say I have a django site, and a base template for all pages with a footer that I want to display a list of the top 5 products on my site. How would I go about sending that list to the base template to render? Does every view need to send that data to the render_to_response? Should I use a template_tag? How would you do it?
|
[
"You should use a custom context processor. With this you can set a variable e.g. top_products that will be available in all your templates.\nE.g.\n# in project/app/context_processors.py\nfrom app.models import Product\n\ndef top_products(request):\n return {'top_products': Products.objects.all()} # of course some filter here\n\nIn your settings.py:\nTEMPLATE_CONTEXT_PROCESSORS = (\n # maybe other here\n 'app.context_processors.top_products',\n)\n\nAnd in your template:\n{% for product in top_products %}\n ...\n\n"
] |
[
11
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0002263258_django_django_templates_python.txt
|
Q:
Generating & Merging PDF Files in Python
I want to automatically generate booking confirmation PDF files in Python. Most of the content will be static (i.e. logos, booking terms, phone numbers), with a few dynamic bits (dates, costs, etc).
From the user side, the simplest way to do this would be to start with a PDF file with the static content, and then using python to just add the dynamic parts. Is this a simple process?
From doing a bit of search, it seems that I can use reportlab for creating content and pyPdf for merging PDF's together. Is this the best approach? Or is there a really funky way that I haven't come across yet?
Thanks!
A:
From the user side, the simplest way to do this would be to start with a PDF file with the static content, and then using python to just add the dynamic parts. Is this a simple process?
Unfortunately no. There are several tools that are good at producing PDFs from scratch (most commonly for Python, ReportLab), but they don't generally load existing PDFs. You would have to include generating code for any boilerplate text, lines, blocks, shapes and images, rather than this being freely editable by the user.
On the other side there's pyPdf which can load PDFs, collate the pages, and extract some of the information, but can't really add new content. You can ‘merge’ pages into one, but you'd still have to create the extra information overlay as a page in ReportLab first.
A:
Look into docutils and reSTructuredText. You could quickly write out your PDF document in reST and then compile the PDF using rst2pdf.py
I've used this, it creates very beautiful documents and the markup is extensible! Later you could take the same code and run it into rst2html to create a website out if it!
Take a look here:
http://docutils.sourceforge.net/docs/user/rst/quickref.html
http://code.google.com/p/rst2pdf/
Good luck
A:
You could generate a document through, for example, TeX, or OpenOffice, or whatever gives you the most comfortable bindings and then print the document with a pdf printer.
This allows you not to have to figure out where to put fields precisely or figure out what to do if your content overflows the space allocated for it.
|
Generating & Merging PDF Files in Python
|
I want to automatically generate booking confirmation PDF files in Python. Most of the content will be static (i.e. logos, booking terms, phone numbers), with a few dynamic bits (dates, costs, etc).
From the user side, the simplest way to do this would be to start with a PDF file with the static content, and then using python to just add the dynamic parts. Is this a simple process?
From doing a bit of search, it seems that I can use reportlab for creating content and pyPdf for merging PDF's together. Is this the best approach? Or is there a really funky way that I haven't come across yet?
Thanks!
|
[
"\nFrom the user side, the simplest way to do this would be to start with a PDF file with the static content, and then using python to just add the dynamic parts. Is this a simple process?\n\nUnfortunately no. There are several tools that are good at producing PDFs from scratch (most commonly for Python, ReportLab), but they don't generally load existing PDFs. You would have to include generating code for any boilerplate text, lines, blocks, shapes and images, rather than this being freely editable by the user.\nOn the other side there's pyPdf which can load PDFs, collate the pages, and extract some of the information, but can't really add new content. You can ‘merge’ pages into one, but you'd still have to create the extra information overlay as a page in ReportLab first.\n",
"Look into docutils and reSTructuredText. You could quickly write out your PDF document in reST and then compile the PDF using rst2pdf.py\nI've used this, it creates very beautiful documents and the markup is extensible! Later you could take the same code and run it into rst2html to create a website out if it!\nTake a look here:\n\nhttp://docutils.sourceforge.net/docs/user/rst/quickref.html\nhttp://code.google.com/p/rst2pdf/\n\nGood luck\n",
"You could generate a document through, for example, TeX, or OpenOffice, or whatever gives you the most comfortable bindings and then print the document with a pdf printer.\nThis allows you not to have to figure out where to put fields precisely or figure out what to do if your content overflows the space allocated for it.\n"
] |
[
8,
2,
1
] |
[] |
[] |
[
"merge",
"pdf",
"pypdf",
"python",
"reportlab"
] |
stackoverflow_0002263263_merge_pdf_pypdf_python_reportlab.txt
|
Q:
Converting from ascii to utf-8 with Python
I have xmpp bot written in python. One of it's plugins is able to execute OS commands and send output to the user. As far as I know output should be unicode-like to send it over xmpp protocol. So I tried to handle it this way:
output = os.popen(cmd).read()
if not isinstance(output, unicode):
output = unicode(output,'utf-8','ignore')
bot.send(xmpp.Message(mess.getFrom(),output))
But when Russian symbols appear in output they aren't converted well.
sys.getdefaultencoding()
says that default command prompt encoding is 'ascii', but when I try to do
output.decode('ascii')
in python console I get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 1:
ordinal not in range(128)
OS: Win XP, Python 2.5.4
PS: Sorry for my English :(
A:
sys.getdefaultencoding() returns python's default encoding - which is ASCII unless you have changed it. ASCII doesn't support Russian characters.
You need to work out what encoding the actual text is, either manually, or using the locale module.
Typically something like:
import locale
encoding = locale.getpreferredencoding(do_setlocale=True)¶
A:
Ascii has no defined character values above 127 0x7F. Perhaps you mean the Cyrillic code page? It's 866
See http://en.wikipedia.org/wiki/Code_page
edit: since this answer was marked correct presumably 886 worked, but as other answers have pointed it, 886 is not the only Russian language code page. If you use a code page different from the one that was used when the Russian symbols were encoded, you will get the wrong result.
A:
You say """sys.getdefaultencoding() says that default command prompt encoding is 'ascii'"""
sys.getdefaultencoding says NOTHING about the "command prompt" encoding.
On Windows, sys.stdout.encoding should do the job. On my machine, it contains cp850 when Python is run in a Command Prompt window, and cp1252 in IDLE. Yours should contain cp866 and cp1251 respectively.
Update You say that you still need cp866 in IDLE. Note this:
IDLE 2.6.4
>>> import os
>>> os.popen('chcp').read()
'Active code page: 850\n'
>>>
So when your app starts up, check if you are on Windows and if so, parse the result of os.popen('chcp').read(). The text before the : is probably locale-dependent. codepage = result.split()[-1] may be good enough "parsing". On Unix, which doesn't have a Windows/MS-DOS split personality, sys.stdout.encoding should be OK.
A:
In Python 'cp855', 'cp866', 'cp1251', 'iso8859_5', 'koi8_r' are differing Russian code pages. You'll need to use the right one to decode the output of popen. In the Windows console, the 'chcp' command lists the code page used by console commands. That won't necessarily be the same code page as Windows applications. On US Windows, 'cp437' is used for the console and 'cp1252' is used for applications like Notepad.
|
Converting from ascii to utf-8 with Python
|
I have xmpp bot written in python. One of it's plugins is able to execute OS commands and send output to the user. As far as I know output should be unicode-like to send it over xmpp protocol. So I tried to handle it this way:
output = os.popen(cmd).read()
if not isinstance(output, unicode):
output = unicode(output,'utf-8','ignore')
bot.send(xmpp.Message(mess.getFrom(),output))
But when Russian symbols appear in output they aren't converted well.
sys.getdefaultencoding()
says that default command prompt encoding is 'ascii', but when I try to do
output.decode('ascii')
in python console I get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 1:
ordinal not in range(128)
OS: Win XP, Python 2.5.4
PS: Sorry for my English :(
|
[
"sys.getdefaultencoding() returns python's default encoding - which is ASCII unless you have changed it. ASCII doesn't support Russian characters.\nYou need to work out what encoding the actual text is, either manually, or using the locale module.\nTypically something like:\nimport locale\nencoding = locale.getpreferredencoding(do_setlocale=True)¶\n\n",
"Ascii has no defined character values above 127 0x7F. Perhaps you mean the Cyrillic code page? It's 866 \nSee http://en.wikipedia.org/wiki/Code_page\nedit: since this answer was marked correct presumably 886 worked, but as other answers have pointed it, 886 is not the only Russian language code page. If you use a code page different from the one that was used when the Russian symbols were encoded, you will get the wrong result.\n",
"You say \"\"\"sys.getdefaultencoding() says that default command prompt encoding is 'ascii'\"\"\"\nsys.getdefaultencoding says NOTHING about the \"command prompt\" encoding.\nOn Windows, sys.stdout.encoding should do the job. On my machine, it contains cp850 when Python is run in a Command Prompt window, and cp1252 in IDLE. Yours should contain cp866 and cp1251 respectively. \nUpdate You say that you still need cp866 in IDLE. Note this:\nIDLE 2.6.4 \n>>> import os\n>>> os.popen('chcp').read()\n'Active code page: 850\\n'\n>>>\n\nSo when your app starts up, check if you are on Windows and if so, parse the result of os.popen('chcp').read(). The text before the : is probably locale-dependent. codepage = result.split()[-1] may be good enough \"parsing\". On Unix, which doesn't have a Windows/MS-DOS split personality, sys.stdout.encoding should be OK.\n",
"In Python 'cp855', 'cp866', 'cp1251', 'iso8859_5', 'koi8_r' are differing Russian code pages. You'll need to use the right one to decode the output of popen. In the Windows console, the 'chcp' command lists the code page used by console commands. That won't necessarily be the same code page as Windows applications. On US Windows, 'cp437' is used for the console and 'cp1252' is used for applications like Notepad.\n"
] |
[
3,
2,
1,
0
] |
[] |
[] |
[
"ascii",
"command_prompt",
"python",
"utf_8"
] |
stackoverflow_0002262879_ascii_command_prompt_python_utf_8.txt
|
Q:
Control 2 separate Excel instances by COM independently... can it be done?
I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook.
It's been given a python interface using the Win32Com library. Other processes can call functions in my python package which in turn invokes the functions I need via Win32Com.
Unfortunately COM does not allow me to specify a particular COM process, so at the moment no matter how powerful my server I can only control one instance of Excel at a time on the computer. If I were to try to run more than one instance of excel there would be no way of ensuring that the python layer is bound to a specific Excel instance.
I'd like to be able to run more than 1 of my excel applications on my Windows server concurrently. Is there a way to do this? For example, could I compartmentalize my environment so that I could run as many Excel _ Python combinations as my application will support?
A:
See "Starting a new instance of a COM application" by Tim Golden, also referenced here, which give the hint to use
xl_app = DispatchEx("Excel.Application")
rather than
xl_app = Dispatch("Excel.Application")
to start a separate process. So you should be able to do:
xl_app_1 = DispatchEx("Excel.Application")
xl_app_2 = DispatchEx("Excel.Application")
xl_app_3 = DispatchEx("Excel.Application")
Note that when you're done, to close the app, I've found it's necessary to do:
xl_app.Quit()
xl_app = None
I found the process won't shut down until xl_app = None, that is, the Python COM object's reference count goes to zero.
Note I'm having one remaining problem: while my Python program is running, if I double-click an Excel file in Explorer (at least, on Win2k), it ends up opening the file in the existing Excel process that Python started (which is running hidden), which disrupts the Python program. I haven't yet found a resolution for this.
A:
I don't know a thing about Python, unfortunately, but if it works through COM, Excel is not a Single-Instance application, so you should be able to create as many instances of Excel as memory permits.
Using C# you can create multiple Excel Application instances via:
Excel.Application xlApp1 = new Excel.Application();
Excel.Application xlApp2 = new Excel.Application();
Excel.Application xlApp3 = new Excel.Application();
Using late binding in C# you can use:
object objXL1 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
object objXL2 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
object objXL3 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
If using VB.NET, VB6 or VBA you can use CreateObject as follows:
Dim objXL1 As Object = CreateObject("Excel.Application")
Dim objXL2 As Object = CreateObject("Excel.Application")
Dim objXL3 As Object = CreateObject("Excel.Application")
Unfortunately, in Python, I don't have a clue. But unless there is some limitation to Python (which I can't imagine?) then I would think that it's very do-able.
That said, the idea of having multiple instances of Excel acting as some kind of server for other operations sounds pretty dicy... I'd be careful to test what you are doing, especially with respect to how many instances you can have open at once without running out of memory and what happens to the calling program if Excel crashed for some reason.
A:
If you application uses a single excel file which contains macros which you call, I fear the answer is probably no since aside from COM Excel does not allow the same file to be opened with the same name (even if in different directories). You may be able to get around this by dynamically copying the file to another name before opening.
My python knowledge isn't huge, but in most languages there is a way of specifying when you create a COM object whether you wish it to be a new object or connect to a preexisting instance by default. Check the python docs for something along these lines.
Can you list the kind of specific problems you are having and exactly what you are hoping to do?
|
Control 2 separate Excel instances by COM independently... can it be done?
|
I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook.
It's been given a python interface using the Win32Com library. Other processes can call functions in my python package which in turn invokes the functions I need via Win32Com.
Unfortunately COM does not allow me to specify a particular COM process, so at the moment no matter how powerful my server I can only control one instance of Excel at a time on the computer. If I were to try to run more than one instance of excel there would be no way of ensuring that the python layer is bound to a specific Excel instance.
I'd like to be able to run more than 1 of my excel applications on my Windows server concurrently. Is there a way to do this? For example, could I compartmentalize my environment so that I could run as many Excel _ Python combinations as my application will support?
|
[
"See \"Starting a new instance of a COM application\" by Tim Golden, also referenced here, which give the hint to use\nxl_app = DispatchEx(\"Excel.Application\")\n\nrather than\nxl_app = Dispatch(\"Excel.Application\")\n\nto start a separate process. So you should be able to do:\nxl_app_1 = DispatchEx(\"Excel.Application\")\nxl_app_2 = DispatchEx(\"Excel.Application\")\nxl_app_3 = DispatchEx(\"Excel.Application\")\n\nNote that when you're done, to close the app, I've found it's necessary to do:\nxl_app.Quit()\nxl_app = None\n\nI found the process won't shut down until xl_app = None, that is, the Python COM object's reference count goes to zero.\nNote I'm having one remaining problem: while my Python program is running, if I double-click an Excel file in Explorer (at least, on Win2k), it ends up opening the file in the existing Excel process that Python started (which is running hidden), which disrupts the Python program. I haven't yet found a resolution for this.\n",
"I don't know a thing about Python, unfortunately, but if it works through COM, Excel is not a Single-Instance application, so you should be able to create as many instances of Excel as memory permits.\nUsing C# you can create multiple Excel Application instances via:\nExcel.Application xlApp1 = new Excel.Application();\nExcel.Application xlApp2 = new Excel.Application();\nExcel.Application xlApp3 = new Excel.Application();\n\nUsing late binding in C# you can use:\nobject objXL1 = Activator.CreateInstance(Type.GetTypeFromProgID(\"Excel.Application\"));\nobject objXL2 = Activator.CreateInstance(Type.GetTypeFromProgID(\"Excel.Application\"));\nobject objXL3 = Activator.CreateInstance(Type.GetTypeFromProgID(\"Excel.Application\"));\n\nIf using VB.NET, VB6 or VBA you can use CreateObject as follows:\nDim objXL1 As Object = CreateObject(\"Excel.Application\")\nDim objXL2 As Object = CreateObject(\"Excel.Application\")\nDim objXL3 As Object = CreateObject(\"Excel.Application\")\n\nUnfortunately, in Python, I don't have a clue. But unless there is some limitation to Python (which I can't imagine?) then I would think that it's very do-able.\nThat said, the idea of having multiple instances of Excel acting as some kind of server for other operations sounds pretty dicy... I'd be careful to test what you are doing, especially with respect to how many instances you can have open at once without running out of memory and what happens to the calling program if Excel crashed for some reason.\n",
"If you application uses a single excel file which contains macros which you call, I fear the answer is probably no since aside from COM Excel does not allow the same file to be opened with the same name (even if in different directories). You may be able to get around this by dynamically copying the file to another name before opening. \nMy python knowledge isn't huge, but in most languages there is a way of specifying when you create a COM object whether you wish it to be a new object or connect to a preexisting instance by default. Check the python docs for something along these lines.\nCan you list the kind of specific problems you are having and exactly what you are hoping to do?\n"
] |
[
9,
2,
0
] |
[] |
[] |
[
"com",
"excel",
"python",
"windows"
] |
stackoverflow_0000516946_com_excel_python_windows.txt
|
Q:
How to calculate positions of holes in a game board?
I'm making a game with Python->PyGame->Albow and ran into a problem with board generation. However I'll try to explain the problem in a language agnostic way. I believe it's not related to python.
I've split the game board generation into several parts.
Part one generates the board holes.
Holes are contained in a list/array. Each hole object has a mapping of angles relating to other holes which are surrounding it, each of those holes also links back to it. (Sort of like HTML DOM siblings, the difference being any angle is possible)
A hole is something like:
hole = {
empty: True,
links: {
90: <other hole>,
270: <another hole>,
etc...
}
}
Part two, calculate hole positions.
The code is something like this.
def calculate_position(hole):
for linked_hole in hole.links:
if linked_hole.position == None:
#calculate linked hole's position relative to this hole
linked_hole.position = [position relative to first hole]
calculate_position(linked_hole)
first_hole.position = (0, 0) #x, y
calculate_position( first_hole )
Part three, draw board.
Find the window height, expand the positions of holes (calculated in step two) to fit the window. Draw everything.
I believe that the problem is in step two I am calculating every hole relative to a previous hole. Rounding errors add up and the board goes squint shaped the further away from the starting hole the holes are and the bigger the board is. This only happens when making boards that aren't rectangular because otherwise there aren't rounding errors.
I am using simple trigonometry to calculate the relative positions of holes by converting the angle into radians and using built in sin/cos functions.
Any idea as to a solution or if I'm mistaken as to the problem is useful :)
PS: I will post the source code if it would help however feel it will clutter things up
Thanks for all the answers.
The people who said rounding probably wasn't going to be an issue were spot on. I had another look through the code with that in mind. I'm embarrassed to say I was generating the wrong angles in the first part of the board generation, the rendering part was correct.
I've marked Norman's answer as correct because it explains how to use a linear combination of vectors to solve the problem.
A:
If hole positions are stored as integers, I don't doubt rounding error accumulates quickly enough to kill you. If hole positions are stored as floating point, and if you have an error of one unit in the last place (ULP) at each computation, I'm not quite sure how quickly error accumulates—but if error doubles at each step, then you have at most 53 links before even double-precision floating point would go wrong.
If you want to be rock-solid accurate, I would represent each position as a linear combination of vectors. You can represent each vector by its angle, and you have just a few angles, so you can represent the position of a hole as something like
Take six 30-degree steps and two 90-degree steps and four 180-degree steps
The numbers six, two, and four will be exact, and once you've computed all positions as vectors, you can then do the trig to convert to (x, y) coordinates all at one go. If you're worried about speed you can cache the arctangent of each angle and it will even be fast.
If this description is too terse, let me know.
A:
The bit about accuracy becomes relatively important as soon as we realize these points are going to be converted to pixel coordinates, a.k.a. integers. Accumulate an error of 0.5 and bam! You're one pixel off.
So, either there is a huge problem with accuracy and rounding errors are climbing very very fast, or the source of the issue is elsewhere. I'm looking at this in step in particular:
expand the positions of holes (calculated in step two) to fit the window
Until I see a screenie, I'll assume "squint" means 'oval-kinda-sorta-thing'; sounds exactly what a bug in this step could produce.
A:
I hate to be the one to suggest this, but, start in the the center. Also, you should look at your code and double check for an unfortunate conversion. The is, if a hole ends up at "138.2, 150.8", you need to keep the fractional parts until you have computed the next hole.
|
How to calculate positions of holes in a game board?
|
I'm making a game with Python->PyGame->Albow and ran into a problem with board generation. However I'll try to explain the problem in a language agnostic way. I believe it's not related to python.
I've split the game board generation into several parts.
Part one generates the board holes.
Holes are contained in a list/array. Each hole object has a mapping of angles relating to other holes which are surrounding it, each of those holes also links back to it. (Sort of like HTML DOM siblings, the difference being any angle is possible)
A hole is something like:
hole = {
empty: True,
links: {
90: <other hole>,
270: <another hole>,
etc...
}
}
Part two, calculate hole positions.
The code is something like this.
def calculate_position(hole):
for linked_hole in hole.links:
if linked_hole.position == None:
#calculate linked hole's position relative to this hole
linked_hole.position = [position relative to first hole]
calculate_position(linked_hole)
first_hole.position = (0, 0) #x, y
calculate_position( first_hole )
Part three, draw board.
Find the window height, expand the positions of holes (calculated in step two) to fit the window. Draw everything.
I believe that the problem is in step two I am calculating every hole relative to a previous hole. Rounding errors add up and the board goes squint shaped the further away from the starting hole the holes are and the bigger the board is. This only happens when making boards that aren't rectangular because otherwise there aren't rounding errors.
I am using simple trigonometry to calculate the relative positions of holes by converting the angle into radians and using built in sin/cos functions.
Any idea as to a solution or if I'm mistaken as to the problem is useful :)
PS: I will post the source code if it would help however feel it will clutter things up
Thanks for all the answers.
The people who said rounding probably wasn't going to be an issue were spot on. I had another look through the code with that in mind. I'm embarrassed to say I was generating the wrong angles in the first part of the board generation, the rendering part was correct.
I've marked Norman's answer as correct because it explains how to use a linear combination of vectors to solve the problem.
|
[
"If hole positions are stored as integers, I don't doubt rounding error accumulates quickly enough to kill you. If hole positions are stored as floating point, and if you have an error of one unit in the last place (ULP) at each computation, I'm not quite sure how quickly error accumulates—but if error doubles at each step, then you have at most 53 links before even double-precision floating point would go wrong.\nIf you want to be rock-solid accurate, I would represent each position as a linear combination of vectors. You can represent each vector by its angle, and you have just a few angles, so you can represent the position of a hole as something like\n\nTake six 30-degree steps and two 90-degree steps and four 180-degree steps\n\nThe numbers six, two, and four will be exact, and once you've computed all positions as vectors, you can then do the trig to convert to (x, y) coordinates all at one go. If you're worried about speed you can cache the arctangent of each angle and it will even be fast.\nIf this description is too terse, let me know.\n",
"The bit about accuracy becomes relatively important as soon as we realize these points are going to be converted to pixel coordinates, a.k.a. integers. Accumulate an error of 0.5 and bam! You're one pixel off.\nSo, either there is a huge problem with accuracy and rounding errors are climbing very very fast, or the source of the issue is elsewhere. I'm looking at this in step in particular:\n\nexpand the positions of holes (calculated in step two) to fit the window\n\nUntil I see a screenie, I'll assume \"squint\" means 'oval-kinda-sorta-thing'; sounds exactly what a bug in this step could produce.\n",
"I hate to be the one to suggest this, but, start in the the center. Also, you should look at your code and double check for an unfortunate conversion. The is, if a hole ends up at \"138.2, 150.8\", you need to keep the fractional parts until you have computed the next hole.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"language_agnostic",
"precision",
"python",
"rounding"
] |
stackoverflow_0002263121_language_agnostic_precision_python_rounding.txt
|
Q:
OAuth with Twitter script in Python is not working
I'm writing a script of OAuth in Python.
For testing this, I use Twitter API. But it is not working well.
def test():
params = {
"oauth_consumer_key": TWITTER_OAUTH_CONSUMER_KEY,
"oauth_nonce": "".join(random.choice(string.digits + string.letters) for i in xrange(7)),
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": str(int(time.time())),
"oauth_token": res_dict["oauth_token"],
"oauth_version": "1.0",
}
status = {"status": u"Always_look_on_the_bright_side_of_life".encode("UTF-8")}
print status
params.update(status)
url = "http://twitter.com/statuses/update.xml"
key = "&".join([TWITTER_OAUTH_CONSUMER_SECRET, res_dict["oauth_token_secret"]])
msg = "&".join(["POST", urllib.quote(url,""),
urllib.quote("&".join([k+"="+params[k] for k in sorted(params)]), "-._~")])
print msg
signature = hmac.new(key, msg, hashlib.sha1).digest().encode("base64").strip()
params["oauth_signature"] = signature
req = urllib2.Request(url,
headers={"Authorization":"OAuth", "Content-type":"application/x-www-form-urlencoded"})
req.add_data("&".join([k+"="+urllib.quote(params[k], "-._~") for k in params]))
print req.get_data()
res = urllib2.urlopen(req).read()
print res
This script (status="Always_look_on_the_bright_side_of_life") is working.
But, in case status is "Always look on the bright side of life"(replaced underscore with space), it isn't working(is returning HTTP Error 401: Unauthorized).
I referenced this question, but failed.
Please give me some advice. Thank you.
A:
I got the same problem in OAuth with FaceBook a while ago. The problem is that the signature validation on server side fails. See your signature generation code here:
msg = "&".join(["POST", urllib.quote(url,""),
urllib.quote("&".join([k+"="+params[k] for k in sorted(params)]), "-._~")])
print msg
signature = hmac.new(key, msg, hashlib.sha1).digest().encode("base64").strip()
It uses the raw (non-encoded) form of the string to generate the signature. However, the server side generates validates the signature against the URL quoted string:
req.add_data("&".join([k+"="+urllib.quote(params[k], "-._~") for k in params]))
To fix the code, you need to do fix this line by creating the signature from the url encoded parameter:
msg = "&".join(["POST", urllib.quote(url,""),
urllib.quote("&".join([k+"="+urllib.quote(params[k], "-._~") for k in sorted(params)]), "-._~")])
A:
The easiest way to fix this is to add status = urllib.quote(status) after status = {"status": u"Always_look_on_the_bright_side_of_life".encode("UTF-8")}. This will escape the spaces and other special characters as required.
|
OAuth with Twitter script in Python is not working
|
I'm writing a script of OAuth in Python.
For testing this, I use Twitter API. But it is not working well.
def test():
params = {
"oauth_consumer_key": TWITTER_OAUTH_CONSUMER_KEY,
"oauth_nonce": "".join(random.choice(string.digits + string.letters) for i in xrange(7)),
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": str(int(time.time())),
"oauth_token": res_dict["oauth_token"],
"oauth_version": "1.0",
}
status = {"status": u"Always_look_on_the_bright_side_of_life".encode("UTF-8")}
print status
params.update(status)
url = "http://twitter.com/statuses/update.xml"
key = "&".join([TWITTER_OAUTH_CONSUMER_SECRET, res_dict["oauth_token_secret"]])
msg = "&".join(["POST", urllib.quote(url,""),
urllib.quote("&".join([k+"="+params[k] for k in sorted(params)]), "-._~")])
print msg
signature = hmac.new(key, msg, hashlib.sha1).digest().encode("base64").strip()
params["oauth_signature"] = signature
req = urllib2.Request(url,
headers={"Authorization":"OAuth", "Content-type":"application/x-www-form-urlencoded"})
req.add_data("&".join([k+"="+urllib.quote(params[k], "-._~") for k in params]))
print req.get_data()
res = urllib2.urlopen(req).read()
print res
This script (status="Always_look_on_the_bright_side_of_life") is working.
But, in case status is "Always look on the bright side of life"(replaced underscore with space), it isn't working(is returning HTTP Error 401: Unauthorized).
I referenced this question, but failed.
Please give me some advice. Thank you.
|
[
"I got the same problem in OAuth with FaceBook a while ago. The problem is that the signature validation on server side fails. See your signature generation code here:\nmsg = \"&\".join([\"POST\", urllib.quote(url,\"\"),\n urllib.quote(\"&\".join([k+\"=\"+params[k] for k in sorted(params)]), \"-._~\")])\nprint msg\nsignature = hmac.new(key, msg, hashlib.sha1).digest().encode(\"base64\").strip()\n\nIt uses the raw (non-encoded) form of the string to generate the signature. However, the server side generates validates the signature against the URL quoted string:\nreq.add_data(\"&\".join([k+\"=\"+urllib.quote(params[k], \"-._~\") for k in params]))\n\nTo fix the code, you need to do fix this line by creating the signature from the url encoded parameter:\nmsg = \"&\".join([\"POST\", urllib.quote(url,\"\"),\n urllib.quote(\"&\".join([k+\"=\"+urllib.quote(params[k], \"-._~\") for k in sorted(params)]), \"-._~\")])\n\n",
"The easiest way to fix this is to add status = urllib.quote(status) after status = {\"status\": u\"Always_look_on_the_bright_side_of_life\".encode(\"UTF-8\")}. This will escape the spaces and other special characters as required.\n"
] |
[
1,
0
] |
[] |
[] |
[
"oauth",
"python",
"twitter"
] |
stackoverflow_0002244608_oauth_python_twitter.txt
|
Q:
Detect the location of an image within a larger image
How do you detect the location of an image within a larger image? I have an unmodified copy of the image. This image is then changed to an arbitrary resolution and placed randomly within a much larger image which is of an arbitrary size. No other transformations are conducted on the resulting image. Python code would be ideal, and it would probably require libgd. If you know of a good approach to this problem you'll get a +1.
A:
There is a quick and dirty solution, and that's simply sliding a window over the target image and computing some measure of similarity at each location, then picking the location with the highest similarity. Then you compare the similarity to a threshold, if the score is above the threshold, you conclude the image is there and that's the location; if the score is below the threshold, then the image isn't there.
As a similarity measure, you can use normalized correlation or sum of squared differences (aka L2 norm). As people mentioned, this will not deal with scale changes. So you also rescale your original image multiple times and repeat the process above with each scaled version. Depending on the size of your input image and the range of possible scales, this may be good enough, and it's easy to implement.
A proper solution is to use affine invariants. Try looking up "wide-baseline stereo matching", people looked at that problem in that context. The methods that are used are generally something like this:
Preprocessing of the original image
Run an "interest point detector". This will find a few points in the image which are easily localizable, e.g. corners. There are many detectors, a detector called "harris-affine" works well and is pretty popular (so implementations probably exist). Another option is to use the Difference-of-Gaussians (DoG) detector, it was developed for SIFT and works well too.
At each interest point, extract a small sub-image (e.g. 30x30 pixels)
For each sub-image, compute a "descriptor", some representation of the image content in that window. Again, many descriptors exist. Things to look at are how well the descriptor describes the image content (you want two descriptors to match only if they are similar) and how invariant it is (you want it to be the same even after scaling). In your case, I'd recommend using SIFT. It is not as invariant as some other descriptors, but can cope with scale well, and in your case scale is the only thing that changes.
At the end of this stage, you will have a set of descriptors.
Testing (with the new test image).
First, you run the same interest point detector as in step 1 and get a set of interest points. You compute the same descriptor for each point, as above. Now you have a set of descriptors for the target image as well.
Next, you look for matches. Ideally, to each descriptor from your original image, there will be some pretty similar descriptor in the target image. (Since the target image is larger, there will also be "leftover" descriptors, i.e. points that don't correspond to anything in the original image.) So if enough of the original descriptors match with enough similarity, then you know the target is there. Moreover, since the descriptors are location-specific, you will also know where in the target image the original image is.
A:
You probably want cross-correlation. (Autocorrelation is correlating a signal with itself; cross correlating is correlating two different signals.)
What correlation does for you, over simply checking for exact matches, is that it will tell you where the best matches are, and how good they are. Flip side is that, for a 2-D picture, it's something like O(N^3), and it's not that simple an algorithm. But it's magic once you get it to work.
EDIT: Aargh, you specified an arbitrary resize. That's going to break any correlation-based algorithm. Sorry, you're outside my experience now and SO won't let me delete this answer.
A:
http://en.wikipedia.org/wiki/Autocorrelation is my first instinct.
A:
Take a look at Scale-Invariant Feature Transforms; there are many different flavors that may be more or less tailored to the type of images you happen to be working with.
|
Detect the location of an image within a larger image
|
How do you detect the location of an image within a larger image? I have an unmodified copy of the image. This image is then changed to an arbitrary resolution and placed randomly within a much larger image which is of an arbitrary size. No other transformations are conducted on the resulting image. Python code would be ideal, and it would probably require libgd. If you know of a good approach to this problem you'll get a +1.
|
[
"There is a quick and dirty solution, and that's simply sliding a window over the target image and computing some measure of similarity at each location, then picking the location with the highest similarity. Then you compare the similarity to a threshold, if the score is above the threshold, you conclude the image is there and that's the location; if the score is below the threshold, then the image isn't there.\nAs a similarity measure, you can use normalized correlation or sum of squared differences (aka L2 norm). As people mentioned, this will not deal with scale changes. So you also rescale your original image multiple times and repeat the process above with each scaled version. Depending on the size of your input image and the range of possible scales, this may be good enough, and it's easy to implement.\nA proper solution is to use affine invariants. Try looking up \"wide-baseline stereo matching\", people looked at that problem in that context. The methods that are used are generally something like this:\nPreprocessing of the original image\n\nRun an \"interest point detector\". This will find a few points in the image which are easily localizable, e.g. corners. There are many detectors, a detector called \"harris-affine\" works well and is pretty popular (so implementations probably exist). Another option is to use the Difference-of-Gaussians (DoG) detector, it was developed for SIFT and works well too.\nAt each interest point, extract a small sub-image (e.g. 30x30 pixels)\nFor each sub-image, compute a \"descriptor\", some representation of the image content in that window. Again, many descriptors exist. Things to look at are how well the descriptor describes the image content (you want two descriptors to match only if they are similar) and how invariant it is (you want it to be the same even after scaling). In your case, I'd recommend using SIFT. It is not as invariant as some other descriptors, but can cope with scale well, and in your case scale is the only thing that changes.\n\nAt the end of this stage, you will have a set of descriptors.\nTesting (with the new test image).\n\nFirst, you run the same interest point detector as in step 1 and get a set of interest points. You compute the same descriptor for each point, as above. Now you have a set of descriptors for the target image as well.\nNext, you look for matches. Ideally, to each descriptor from your original image, there will be some pretty similar descriptor in the target image. (Since the target image is larger, there will also be \"leftover\" descriptors, i.e. points that don't correspond to anything in the original image.) So if enough of the original descriptors match with enough similarity, then you know the target is there. Moreover, since the descriptors are location-specific, you will also know where in the target image the original image is.\n\n",
"You probably want cross-correlation. (Autocorrelation is correlating a signal with itself; cross correlating is correlating two different signals.)\nWhat correlation does for you, over simply checking for exact matches, is that it will tell you where the best matches are, and how good they are. Flip side is that, for a 2-D picture, it's something like O(N^3), and it's not that simple an algorithm. But it's magic once you get it to work.\nEDIT: Aargh, you specified an arbitrary resize. That's going to break any correlation-based algorithm. Sorry, you're outside my experience now and SO won't let me delete this answer.\n",
"http://en.wikipedia.org/wiki/Autocorrelation is my first instinct.\n",
"Take a look at Scale-Invariant Feature Transforms; there are many different flavors that may be more or less tailored to the type of images you happen to be working with.\n"
] |
[
7,
3,
2,
2
] |
[] |
[] |
[
"gdlib",
"image",
"image_processing",
"python"
] |
stackoverflow_0002262832_gdlib_image_image_processing_python.txt
|
Q:
How do I get the google username and email when someone logins to my site?
the next is mysite1\django_openid\registration.py:
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.conf import settings
from django_openid.auth import AuthConsumer
from django_openid.utils import OpenID, int_to_hex, hex_to_int
from django_openid import signed
from django_openid import forms
from openid.consumer import consumer
import urlparse
class RegistrationConsumer(AuthConsumer):
already_signed_in_message = 'You are already signed in to this site'
unknown_openid_message = \
'That OpenID is not recognised. Would you like to create an account?'
c_already_confirmed_message = 'Your account is already confirmed'
register_template = 'django_openid/register.html'
set_password_template = 'django_openid/set_password.html'
confirm_email_template = 'django_openid/register_confirm_email.txt'
register_email_sent_template = 'django_openid/register_email_sent.html'
register_complete_template = 'django_openid/register_complete.html'
after_registration_url = None # None means "show a message instead"
unconfirmed_group = 'Unconfirmed users'
# Registration options
reserved_usernames = ['security', 'info', 'admin']
no_duplicate_emails = True
confirm_email_addresses = True
confirm_email_from = None # If None, uses settings.DEFAULT_FROM_EMAIL
confirm_email_subject = 'Confirm your e-mail address'
confirm_link_secret = None
confirm_link_salt = 'confirm-link-salt'
# sreg
sreg = ['nickname', 'email', 'fullname']
RegistrationForm = forms.RegistrationFormPasswordConfirm
ChangePasswordForm = forms.ChangePasswordForm
def user_is_confirmed(self, user):
return not self.user_is_unconfirmed(user)
def user_is_unconfirmed(self, user):
return user.groups.filter(name = self.unconfirmed_group).count()
def mark_user_unconfirmed(self, user):
from django.contrib.auth.models import Group
user.is_active = False
user.save()
group, _ = Group.objects.get_or_create(name = self.unconfirmed_group)
user.groups.add(group)
def mark_user_confirmed(self, user):
user.groups.filter(name = self.unconfirmed_group).delete()
def get_registration_form_class(self, request):
return self.RegistrationForm
def get_change_password_form_class(self, request):
return self.ChangePasswordForm
def show_i_have_logged_you_in(self, request):
return self.show_message(
request, 'You are logged in',
'You already have an account for that OpenID. ' +
'You are now logged in.'
)
def do_register_complete(self, request):
def on_success(request, identity_url, openid_response):
# We need to behave differently from the default AuthConsumer
# success behaviour. For simplicity, we do the following:
# 1. "Log them in" as that OpenID i.e. stash it in the session
# 2. If it's already associated with an account, log them in as
# that account and show a message.
# 2. If NOT already associated, redirect back to /register/ again
openid_object = OpenID.from_openid_response(openid_response)
matches = self.lookup_openid(request, identity_url)
if matches:
# Log them in and show the message
self.log_in_user(request, matches[0])
response = self.show_i_have_logged_you_in(request)
else:
response = HttpResponseRedirect(urlparse.urljoin(
request.path, '../register/'
))
self.persist_openid(request, response, openid_object)
return response
return self.dispatch_openid_complete(request, {
consumer.SUCCESS: on_success,
consumer.CANCEL:
lambda request, openid_response: self.do_register(request,
message = self.request_cancelled_message
),
consumer.FAILURE:
lambda request, openid_response: self.do_register(request,
message = self.failure_message % openid_response.message
),
consumer.SETUP_NEEDED:
lambda request, openid_response: self.do_register(request,
message = self.setup_needed_message
),
})
def on_registration_complete(self, request):
if self.after_registration_url:
return HttpResponseRedirect(self.after_registration_url)
else:
return self.render(request, self.register_complete_template)
def do_register(self, request, message=None):
# Show a registration / signup form, provided the user is not
# already logged in
if not request.user.is_anonymous():
return self.show_already_signed_in(request)
# Spot incoming openid_url authentication requests
if request.POST.get('openid_url', None):
return self.start_openid_process(request,
user_url = request.POST.get('openid_url'),
on_complete_url = urlparse.urljoin(
request.path, '../register_complete/'
),
trust_root = urlparse.urljoin(request.path, '..')
)
RegistrationForm = self.get_registration_form_class(request)
try:
openid = request.openid and request.openid.openid or None
except AttributeError:
return self.show_error(
request, 'Add CookieConsumer or similar to your middleware'
)
if request.method == 'POST':
# TODO: The user might have entered an OpenID as a starting point,
# or they might have decided to sign up normally
form = RegistrationForm(
request.POST,
openid = openid,
reserved_usernames = self.reserved_usernames,
no_duplicate_emails = self.no_duplicate_emails
)
if form.is_valid():
user = self.create_user(request, form.cleaned_data, openid)
if self.confirm_email_addresses:
return self.confirm_email_step(request, user)
else:
self.log_in_user(request, user)
return self.on_registration_complete(request)
else:
form = RegistrationForm(
initial = request.openid and self.initial_from_sreg(
request.openid.sreg
) or {},
openid = openid,
reserved_usernames = self.reserved_usernames,
no_duplicate_emails = self.no_duplicate_emails
)
return self.render(request, self.register_template, {
'form': form,
'message': message,
'openid': request.openid,
'logo': self.logo_path or (urlparse.urljoin(
request.path, '../logo/'
)),
'no_thanks': self.sign_next(request.path),
'action': request.path,
})
def confirm_email_step(self, request, user):
self.mark_user_unconfirmed(user)
self.send_confirm_email(request, user)
return self.render(request, self.register_email_sent_template, {
'email': user.email,
})
def generate_confirm_code(self, user):
return signed.sign(int_to_hex(user.id), key = (
self.confirm_link_secret or settings.SECRET_KEY
) + self.confirm_link_salt)
def send_confirm_email(self, request, user):
from_email = self.confirm_email_from or settings.DEFAULT_FROM_EMAIL
code = self.generate_confirm_code(user)
path = urlparse.urljoin(request.path, '../c/%s/' % code)
url = request.build_absolute_uri(path)
send_mail(
subject = self.confirm_email_subject,
message = self.render(request, self.confirm_email_template, {
'url': url,
'code': code,
'user': user,
}).content,
from_email = from_email,
recipient_list = [user.email]
)
def do_c(self, request, token = ''):
if not token:
# TODO: show a form where they can paste in their token?
raise Http404
token = token.rstrip('/').encode('utf8')
try:
value = signed.unsign(token, key = (
self.confirm_link_secret or settings.SECRET_KEY
) + self.confirm_link_salt)
except signed.BadSignature:
return self.show_message(
request, self.invalid_token_message,
self.invalid_token_message + ': ' + token
)
user_id = hex_to_int(value)
user = self.lookup_user_by_id(user_id)
if not user: # Maybe the user was deleted?
return self.show_error(request, r_user_not_found_message)
# Check user is NOT active but IS in the correct group
if self.user_is_unconfirmed(user):
# Confirm them
user.is_active = True
user.save()
self.mark_user_confirmed(user)
self.log_in_user(request, user)
return self.on_registration_complete(request)
else:
return self.show_error(request, self.c_already_confirmed_message)
do_c.urlregex = '^c/([^/]+)/$'
def create_user(self, request, data, openid=None):
from django.contrib.auth.models import User
user = User.objects.create(
username = data['username'],
first_name = data.get('first_name', ''),
last_name = data.get('last_name', ''),
email = data.get('email', ''),
)
# Set OpenID, if one has been associated
if openid:
user.openids.create(openid = openid)
# Set password, if one has been specified
password = data.get('password')
if password:
user.set_password(password)
else:
user.set_unusable_password()
user.save()
return user
def do_password(self, request):
"Allow users to set a password on their account"
if request.user.is_anonymous():
return self.show_error(request, 'You need to log in first')
ChangePasswordForm = self.get_change_password_form_class(request)
if request.method == 'POST':
form = ChangePasswordForm(request.user, data=request.POST)
if form.is_valid():
u = request.user
u.set_password(form.cleaned_data['password'])
u.save()
return self.show_password_has_been_set(request)
else:
form = ChangePasswordForm(request.user)
return self.render(request, self.set_password_template, {
'form': form,
'action': request.path,
})
def show_password_has_been_set(self, request):
return self.show_message(
request, 'Password set', 'Your password has been set.'
)
def initial_from_sreg(self, sreg):
"Maps sreg to data for populating registration form"
fullname = sreg.get('fullname', '')
first_name, last_name = '', ''
if fullname:
bits = fullname.split()
first_name = bits[0]
if len(bits) > 1:
last_name = ' '.join(bits[1:])
return {
'username': self.suggest_nickname(sreg.get('nickname', '')),
'first_name': first_name,
'last_name': last_name,
'email': sreg.get('email', ''),
}
def suggest_nickname(self, nickname):
"Return a suggested nickname that has not yet been taken"
from django.contrib.auth.models import User
if not nickname:
return ''
original_nickname = nickname
suffix = None
while User.objects.filter(username = nickname).count():
if suffix is None:
suffix = 1
else:
suffix += 1
nickname = original_nickname + str(suffix)
return nickname
def show_unknown_openid(self, request, openid):
# If the user gets here, they have attempted to log in using an
# OpenID BUT it's an OpenID we have never seen before - so show
# them the index page but with an additional message
return self.do_index(request, self.unknown_openid_message)
def show_already_signed_in(self, request):
return self.show_message(
request, 'Already signed in', self.already_signed_in_message
)
and the login view:
def login(request, form_class=LoginForm, template_name="account/login.html",
success_url=None, associate_openid=False, openid_success_url=None,
url_required=False, extra_context=None):
if extra_context is None:
extra_context = {}
if success_url is None:
success_url = get_default_redirect(request)
if request.method == "POST" and not url_required:
form = form_class(request.POST)
if form.login(request):
if associate_openid and association_model is not None:
for openid in request.session.get('openids', []):
assoc, created = UserOpenidAssociation.objects.get_or_create(
user=form.user, openid=openid.openid
)
success_url = openid_success_url or success_url
return HttpResponseRedirect(success_url)
else:
form = form_class()
ctx = {
"form": form,
"url_required": url_required,
}
ctx.update(extra_context)
return render_to_response(template_name, ctx,
context_instance = RequestContext(request)
)
A:
You ask the user. OpenID is inherently designed to not require providing anything except a user-unique identifier for authenticated users; any information beyond that is in the realm of application-specific.
|
How do I get the google username and email when someone logins to my site?
|
the next is mysite1\django_openid\registration.py:
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.conf import settings
from django_openid.auth import AuthConsumer
from django_openid.utils import OpenID, int_to_hex, hex_to_int
from django_openid import signed
from django_openid import forms
from openid.consumer import consumer
import urlparse
class RegistrationConsumer(AuthConsumer):
already_signed_in_message = 'You are already signed in to this site'
unknown_openid_message = \
'That OpenID is not recognised. Would you like to create an account?'
c_already_confirmed_message = 'Your account is already confirmed'
register_template = 'django_openid/register.html'
set_password_template = 'django_openid/set_password.html'
confirm_email_template = 'django_openid/register_confirm_email.txt'
register_email_sent_template = 'django_openid/register_email_sent.html'
register_complete_template = 'django_openid/register_complete.html'
after_registration_url = None # None means "show a message instead"
unconfirmed_group = 'Unconfirmed users'
# Registration options
reserved_usernames = ['security', 'info', 'admin']
no_duplicate_emails = True
confirm_email_addresses = True
confirm_email_from = None # If None, uses settings.DEFAULT_FROM_EMAIL
confirm_email_subject = 'Confirm your e-mail address'
confirm_link_secret = None
confirm_link_salt = 'confirm-link-salt'
# sreg
sreg = ['nickname', 'email', 'fullname']
RegistrationForm = forms.RegistrationFormPasswordConfirm
ChangePasswordForm = forms.ChangePasswordForm
def user_is_confirmed(self, user):
return not self.user_is_unconfirmed(user)
def user_is_unconfirmed(self, user):
return user.groups.filter(name = self.unconfirmed_group).count()
def mark_user_unconfirmed(self, user):
from django.contrib.auth.models import Group
user.is_active = False
user.save()
group, _ = Group.objects.get_or_create(name = self.unconfirmed_group)
user.groups.add(group)
def mark_user_confirmed(self, user):
user.groups.filter(name = self.unconfirmed_group).delete()
def get_registration_form_class(self, request):
return self.RegistrationForm
def get_change_password_form_class(self, request):
return self.ChangePasswordForm
def show_i_have_logged_you_in(self, request):
return self.show_message(
request, 'You are logged in',
'You already have an account for that OpenID. ' +
'You are now logged in.'
)
def do_register_complete(self, request):
def on_success(request, identity_url, openid_response):
# We need to behave differently from the default AuthConsumer
# success behaviour. For simplicity, we do the following:
# 1. "Log them in" as that OpenID i.e. stash it in the session
# 2. If it's already associated with an account, log them in as
# that account and show a message.
# 2. If NOT already associated, redirect back to /register/ again
openid_object = OpenID.from_openid_response(openid_response)
matches = self.lookup_openid(request, identity_url)
if matches:
# Log them in and show the message
self.log_in_user(request, matches[0])
response = self.show_i_have_logged_you_in(request)
else:
response = HttpResponseRedirect(urlparse.urljoin(
request.path, '../register/'
))
self.persist_openid(request, response, openid_object)
return response
return self.dispatch_openid_complete(request, {
consumer.SUCCESS: on_success,
consumer.CANCEL:
lambda request, openid_response: self.do_register(request,
message = self.request_cancelled_message
),
consumer.FAILURE:
lambda request, openid_response: self.do_register(request,
message = self.failure_message % openid_response.message
),
consumer.SETUP_NEEDED:
lambda request, openid_response: self.do_register(request,
message = self.setup_needed_message
),
})
def on_registration_complete(self, request):
if self.after_registration_url:
return HttpResponseRedirect(self.after_registration_url)
else:
return self.render(request, self.register_complete_template)
def do_register(self, request, message=None):
# Show a registration / signup form, provided the user is not
# already logged in
if not request.user.is_anonymous():
return self.show_already_signed_in(request)
# Spot incoming openid_url authentication requests
if request.POST.get('openid_url', None):
return self.start_openid_process(request,
user_url = request.POST.get('openid_url'),
on_complete_url = urlparse.urljoin(
request.path, '../register_complete/'
),
trust_root = urlparse.urljoin(request.path, '..')
)
RegistrationForm = self.get_registration_form_class(request)
try:
openid = request.openid and request.openid.openid or None
except AttributeError:
return self.show_error(
request, 'Add CookieConsumer or similar to your middleware'
)
if request.method == 'POST':
# TODO: The user might have entered an OpenID as a starting point,
# or they might have decided to sign up normally
form = RegistrationForm(
request.POST,
openid = openid,
reserved_usernames = self.reserved_usernames,
no_duplicate_emails = self.no_duplicate_emails
)
if form.is_valid():
user = self.create_user(request, form.cleaned_data, openid)
if self.confirm_email_addresses:
return self.confirm_email_step(request, user)
else:
self.log_in_user(request, user)
return self.on_registration_complete(request)
else:
form = RegistrationForm(
initial = request.openid and self.initial_from_sreg(
request.openid.sreg
) or {},
openid = openid,
reserved_usernames = self.reserved_usernames,
no_duplicate_emails = self.no_duplicate_emails
)
return self.render(request, self.register_template, {
'form': form,
'message': message,
'openid': request.openid,
'logo': self.logo_path or (urlparse.urljoin(
request.path, '../logo/'
)),
'no_thanks': self.sign_next(request.path),
'action': request.path,
})
def confirm_email_step(self, request, user):
self.mark_user_unconfirmed(user)
self.send_confirm_email(request, user)
return self.render(request, self.register_email_sent_template, {
'email': user.email,
})
def generate_confirm_code(self, user):
return signed.sign(int_to_hex(user.id), key = (
self.confirm_link_secret or settings.SECRET_KEY
) + self.confirm_link_salt)
def send_confirm_email(self, request, user):
from_email = self.confirm_email_from or settings.DEFAULT_FROM_EMAIL
code = self.generate_confirm_code(user)
path = urlparse.urljoin(request.path, '../c/%s/' % code)
url = request.build_absolute_uri(path)
send_mail(
subject = self.confirm_email_subject,
message = self.render(request, self.confirm_email_template, {
'url': url,
'code': code,
'user': user,
}).content,
from_email = from_email,
recipient_list = [user.email]
)
def do_c(self, request, token = ''):
if not token:
# TODO: show a form where they can paste in their token?
raise Http404
token = token.rstrip('/').encode('utf8')
try:
value = signed.unsign(token, key = (
self.confirm_link_secret or settings.SECRET_KEY
) + self.confirm_link_salt)
except signed.BadSignature:
return self.show_message(
request, self.invalid_token_message,
self.invalid_token_message + ': ' + token
)
user_id = hex_to_int(value)
user = self.lookup_user_by_id(user_id)
if not user: # Maybe the user was deleted?
return self.show_error(request, r_user_not_found_message)
# Check user is NOT active but IS in the correct group
if self.user_is_unconfirmed(user):
# Confirm them
user.is_active = True
user.save()
self.mark_user_confirmed(user)
self.log_in_user(request, user)
return self.on_registration_complete(request)
else:
return self.show_error(request, self.c_already_confirmed_message)
do_c.urlregex = '^c/([^/]+)/$'
def create_user(self, request, data, openid=None):
from django.contrib.auth.models import User
user = User.objects.create(
username = data['username'],
first_name = data.get('first_name', ''),
last_name = data.get('last_name', ''),
email = data.get('email', ''),
)
# Set OpenID, if one has been associated
if openid:
user.openids.create(openid = openid)
# Set password, if one has been specified
password = data.get('password')
if password:
user.set_password(password)
else:
user.set_unusable_password()
user.save()
return user
def do_password(self, request):
"Allow users to set a password on their account"
if request.user.is_anonymous():
return self.show_error(request, 'You need to log in first')
ChangePasswordForm = self.get_change_password_form_class(request)
if request.method == 'POST':
form = ChangePasswordForm(request.user, data=request.POST)
if form.is_valid():
u = request.user
u.set_password(form.cleaned_data['password'])
u.save()
return self.show_password_has_been_set(request)
else:
form = ChangePasswordForm(request.user)
return self.render(request, self.set_password_template, {
'form': form,
'action': request.path,
})
def show_password_has_been_set(self, request):
return self.show_message(
request, 'Password set', 'Your password has been set.'
)
def initial_from_sreg(self, sreg):
"Maps sreg to data for populating registration form"
fullname = sreg.get('fullname', '')
first_name, last_name = '', ''
if fullname:
bits = fullname.split()
first_name = bits[0]
if len(bits) > 1:
last_name = ' '.join(bits[1:])
return {
'username': self.suggest_nickname(sreg.get('nickname', '')),
'first_name': first_name,
'last_name': last_name,
'email': sreg.get('email', ''),
}
def suggest_nickname(self, nickname):
"Return a suggested nickname that has not yet been taken"
from django.contrib.auth.models import User
if not nickname:
return ''
original_nickname = nickname
suffix = None
while User.objects.filter(username = nickname).count():
if suffix is None:
suffix = 1
else:
suffix += 1
nickname = original_nickname + str(suffix)
return nickname
def show_unknown_openid(self, request, openid):
# If the user gets here, they have attempted to log in using an
# OpenID BUT it's an OpenID we have never seen before - so show
# them the index page but with an additional message
return self.do_index(request, self.unknown_openid_message)
def show_already_signed_in(self, request):
return self.show_message(
request, 'Already signed in', self.already_signed_in_message
)
and the login view:
def login(request, form_class=LoginForm, template_name="account/login.html",
success_url=None, associate_openid=False, openid_success_url=None,
url_required=False, extra_context=None):
if extra_context is None:
extra_context = {}
if success_url is None:
success_url = get_default_redirect(request)
if request.method == "POST" and not url_required:
form = form_class(request.POST)
if form.login(request):
if associate_openid and association_model is not None:
for openid in request.session.get('openids', []):
assoc, created = UserOpenidAssociation.objects.get_or_create(
user=form.user, openid=openid.openid
)
success_url = openid_success_url or success_url
return HttpResponseRedirect(success_url)
else:
form = form_class()
ctx = {
"form": form,
"url_required": url_required,
}
ctx.update(extra_context)
return render_to_response(template_name, ctx,
context_instance = RequestContext(request)
)
|
[
"You ask the user. OpenID is inherently designed to not require providing anything except a user-unique identifier for authenticated users; any information beyond that is in the realm of application-specific.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"openid",
"pinax",
"python"
] |
stackoverflow_0002264193_django_openid_pinax_python.txt
|
Q:
twisted.web2 and spawining threads for synchronous code?
So, I'm writing a python web application using the twisted web2 framework. There's a library that I need to use (SQLAlchemy, to be specific) that doesn't have asynchronous code. Would it be bad to spawn a thread to handle the request, fetch any data from the DB, and then return a response? I'm afraid that if there was a flood of requests, too many threads would be started and the server would be overwhelmed. Is there something built into twisted that prevents this from happening (eg request throttling)?
A:
See the docs, and specifically the thread pool which lets you control how many threads are active at most. Spawning one new thread per request would definitely be an inferior idea!
|
twisted.web2 and spawining threads for synchronous code?
|
So, I'm writing a python web application using the twisted web2 framework. There's a library that I need to use (SQLAlchemy, to be specific) that doesn't have asynchronous code. Would it be bad to spawn a thread to handle the request, fetch any data from the DB, and then return a response? I'm afraid that if there was a flood of requests, too many threads would be started and the server would be overwhelmed. Is there something built into twisted that prevents this from happening (eg request throttling)?
|
[
"See the docs, and specifically the thread pool which lets you control how many threads are active at most. Spawning one new thread per request would definitely be an inferior idea!\n"
] |
[
0
] |
[] |
[] |
[
"multithreading",
"python",
"twisted"
] |
stackoverflow_0002264135_multithreading_python_twisted.txt
|
Q:
Unwind a function call
This is a difficult problem to describe so please let me know if anything is unclear.
I am trying to solve a possible deadlock situation in my C++ app and I am having trouble visualizing an appropriate solution. The restrictions placed on me by the two libraries I am trying to connect make my problem very complex and troublesome but it can all boil down to a simple diagram. Quite simply I have a situation like so
Python | Thread 1 Thread 2
|
Action 1 -|-> GIL LOCK --> Random Calls
Action 2 | GIL LOCK <----------------------------- [Action 2]
| Action 1 -- signals ---> Do_Action_1
| Wait Forever Wait on Action 2
Action 2 happens to be a timer firing, the library I am using has this timer code that will call functions after a set amount of time.
Trouble occurs when a timer fires while I am destroying the timer handler (Action 1). The timer handler will wait for the timers to finish their functions and the timer functions cannot finish because they are waiting to call a python function. In order to get into python they need to take the GIL which is being held by the timer handler destruction action.
I am wondering if its possible for me from Thread 1 to interrupt its wait on the GIL and unwind its stack to put it out of harms way of this deadlock. Although I fear going down to far into specific OS implementations I just can not think of any better solution.
In other words, I want to cancel the Action 2 call from thread 1. Is this in ANY way possible?
I should mention that I cannot edit the operation in Thread 2 ie, I cannot edit that library that is managing that thread.
I can modify python's GIL lock to maybe be a try lock or a timed lock or maybe even a wait on a condition but that would be really hard to pull off.
I suppose the best solution would be to modify python to wait on the gil and a named condition that my Thread 1 can signal when I want to cancel its wait on the GIL. But before going down that route I want to know if I am missing anything.
A:
If you're destroying the timer handler, I figure you're exiting the program. Before you try to exit and begin killing the timers, can you set a flag to prevent Action 1 and have Thread 1 terminate itself? I hope I'm reading your diagram right, because it doesn't exactly match with the text...
|
Unwind a function call
|
This is a difficult problem to describe so please let me know if anything is unclear.
I am trying to solve a possible deadlock situation in my C++ app and I am having trouble visualizing an appropriate solution. The restrictions placed on me by the two libraries I am trying to connect make my problem very complex and troublesome but it can all boil down to a simple diagram. Quite simply I have a situation like so
Python | Thread 1 Thread 2
|
Action 1 -|-> GIL LOCK --> Random Calls
Action 2 | GIL LOCK <----------------------------- [Action 2]
| Action 1 -- signals ---> Do_Action_1
| Wait Forever Wait on Action 2
Action 2 happens to be a timer firing, the library I am using has this timer code that will call functions after a set amount of time.
Trouble occurs when a timer fires while I am destroying the timer handler (Action 1). The timer handler will wait for the timers to finish their functions and the timer functions cannot finish because they are waiting to call a python function. In order to get into python they need to take the GIL which is being held by the timer handler destruction action.
I am wondering if its possible for me from Thread 1 to interrupt its wait on the GIL and unwind its stack to put it out of harms way of this deadlock. Although I fear going down to far into specific OS implementations I just can not think of any better solution.
In other words, I want to cancel the Action 2 call from thread 1. Is this in ANY way possible?
I should mention that I cannot edit the operation in Thread 2 ie, I cannot edit that library that is managing that thread.
I can modify python's GIL lock to maybe be a try lock or a timed lock or maybe even a wait on a condition but that would be really hard to pull off.
I suppose the best solution would be to modify python to wait on the gil and a named condition that my Thread 1 can signal when I want to cancel its wait on the GIL. But before going down that route I want to know if I am missing anything.
|
[
"If you're destroying the timer handler, I figure you're exiting the program. Before you try to exit and begin killing the timers, can you set a flag to prevent Action 1 and have Thread 1 terminate itself? I hope I'm reading your diagram right, because it doesn't exactly match with the text...\n"
] |
[
0
] |
[] |
[] |
[
"boost_python",
"c++",
"multithreading",
"python"
] |
stackoverflow_0002264137_boost_python_c++_multithreading_python.txt
|
Q:
How to check if a page is displaying a specific tag
What is the best way to determine if a page on a website is REALLY displaying a specific img tag like this <img src=http://domain.com/img.jpg>? A simple string comparison is easy to fool using http comments <!-- -->. Even if the html tag exists it could be deleted with JavaScript. It could also be obscured by placing an image over it using CSS. Do you know of a solid method of detecting the img tag dispute these obscuring attacks listed? Do you know of another method of obscuring the image? Python code to detect the image would be ideal, but if you know of a good tactic or method that will earn you a +1 from me.
A:
The only surefire way I can think of is to render the page and check. It is simple to strip comments etc. But if scripts are involved, it is not possible to have a general solution that will not amount to executing them (I believe this is the first time I ever invoked Church's theorem...).
A:
I don't think you can ever be sure. First, you're not even sure the program will stop.
Aside from that, consider the following scenarios. Your <img> can be added, removed or get obscured using JavaScript, CSS and/or server-side:
randomly.
at specific times.
to a certain part of the world.
according to differences and bugs between browsers.
Google is facing a similar problem - people are hiding search keywords in hidden text and links to get a better rank. Their solution is to penalize sites with hidden text. They get away with it because they're Google; people depend on them for traffic.
As for you, you can't do much better than to ask nicely...
A:
You could place a script anywhere that processes the request, counts the view and delivers the image like this:
http://yourhost.com/imageprocess?image=media/foo/bar.jpg
Then you can be sure that the image was loaded. If if was viewed, you of course can't be sure, however.
|
How to check if a page is displaying a specific tag
|
What is the best way to determine if a page on a website is REALLY displaying a specific img tag like this <img src=http://domain.com/img.jpg>? A simple string comparison is easy to fool using http comments <!-- -->. Even if the html tag exists it could be deleted with JavaScript. It could also be obscured by placing an image over it using CSS. Do you know of a solid method of detecting the img tag dispute these obscuring attacks listed? Do you know of another method of obscuring the image? Python code to detect the image would be ideal, but if you know of a good tactic or method that will earn you a +1 from me.
|
[
"The only surefire way I can think of is to render the page and check. It is simple to strip comments etc. But if scripts are involved, it is not possible to have a general solution that will not amount to executing them (I believe this is the first time I ever invoked Church's theorem...).\n",
"I don't think you can ever be sure. First, you're not even sure the program will stop.\nAside from that, consider the following scenarios. Your <img> can be added, removed or get obscured using JavaScript, CSS and/or server-side:\n\nrandomly.\nat specific times.\nto a certain part of the world.\naccording to differences and bugs between browsers.\n\nGoogle is facing a similar problem - people are hiding search keywords in hidden text and links to get a better rank. Their solution is to penalize sites with hidden text. They get away with it because they're Google; people depend on them for traffic.\nAs for you, you can't do much better than to ask nicely...\n",
"You could place a script anywhere that processes the request, counts the view and delivers the image like this:\nhttp://yourhost.com/imageprocess?image=media/foo/bar.jpg\nThen you can be sure that the image was loaded. If if was viewed, you of course can't be sure, however.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"browser",
"python",
"security",
"web_crawler"
] |
stackoverflow_0002262724_browser_python_security_web_crawler.txt
|
Q:
how to work with strings and integers as bit strings in python?
I'm developing a Genetic Algorithm in python were chromosomes are composed of strings and integers. To apply the genetic operations, I want to convert these groups of integers and strings into bit strings.
For example, if one chromosome is:
["Hello", 4, "anotherString"]
I'd like it to become something like:
0100100100101001010011110011
(this is not actual translation). So... How can I do this? Chromosomes will contain the same amount of strings and integers, but this numbers can vary from one algorithm run to another.
To be clear, what I want to obtain is the bit representation of each element in the chromosome concatenated.
If you think this would not be the best way to apply genetic operators (such as mutation and simple crossover) just tell me! I'm open to new ideas.
Thanks a lot!
Manuel
A:
You can turn strings and integers into bytestrings (and back) with the struct module, and that's exactly 8 bits to a byte. If for some reason you want these binary bytestrings as text strings made up of 0 and 1 characters, you can print them in binary form, of course.
Edit: forgot to remind you how to format a byte into a text string made up of 0 and 1 characters -- in Python 2.6 or better:
>>> format(23, '08b')
'00010111'
and to get back from such a string to a byte, of course:
>>> int('00010111', 2)
23
A:
Converting everything into one concatenated string, and than applying genetic operations doesn't seem to be the best idea. Genetic operations can break here many things (especially if you have some constrains on individuals), additionally effectiveness of such solution is probably low. I would suggest different approach.
Try implementing individual using SuperGene concept (wiki). Example of applying it to GA is described here. Additionally as per this they say it improves overall GA performance.
In my opinion it will make design clearer. I would try this approach.
A:
Once you describe exactly how the translation from strings to bitstrings should go, the "how" should be fairly easy. If the genetic algorithms should work on a bit-level then obviously a bit level string makes sense, but it is probably way slower than using numbers or character strings.
|
how to work with strings and integers as bit strings in python?
|
I'm developing a Genetic Algorithm in python were chromosomes are composed of strings and integers. To apply the genetic operations, I want to convert these groups of integers and strings into bit strings.
For example, if one chromosome is:
["Hello", 4, "anotherString"]
I'd like it to become something like:
0100100100101001010011110011
(this is not actual translation). So... How can I do this? Chromosomes will contain the same amount of strings and integers, but this numbers can vary from one algorithm run to another.
To be clear, what I want to obtain is the bit representation of each element in the chromosome concatenated.
If you think this would not be the best way to apply genetic operators (such as mutation and simple crossover) just tell me! I'm open to new ideas.
Thanks a lot!
Manuel
|
[
"You can turn strings and integers into bytestrings (and back) with the struct module, and that's exactly 8 bits to a byte. If for some reason you want these binary bytestrings as text strings made up of 0 and 1 characters, you can print them in binary form, of course.\nEdit: forgot to remind you how to format a byte into a text string made up of 0 and 1 characters -- in Python 2.6 or better:\n>>> format(23, '08b')\n'00010111'\n\nand to get back from such a string to a byte, of course:\n>>> int('00010111', 2)\n23\n\n",
"Converting everything into one concatenated string, and than applying genetic operations doesn't seem to be the best idea. Genetic operations can break here many things (especially if you have some constrains on individuals), additionally effectiveness of such solution is probably low. I would suggest different approach. \nTry implementing individual using SuperGene concept (wiki). Example of applying it to GA is described here. Additionally as per this they say it improves overall GA performance.\nIn my opinion it will make design clearer. I would try this approach. \n",
"Once you describe exactly how the translation from strings to bitstrings should go, the \"how\" should be fairly easy. If the genetic algorithms should work on a bit-level then obviously a bit level string makes sense, but it is probably way slower than using numbers or character strings.\n"
] |
[
3,
3,
0
] |
[] |
[] |
[
"artificial_intelligence",
"bit_manipulation",
"data_conversion",
"genetic_algorithm",
"python"
] |
stackoverflow_0002264130_artificial_intelligence_bit_manipulation_data_conversion_genetic_algorithm_python.txt
|
Q:
Creating a GUI Calculator in python similar to MS Calculator
I need to write a code that runs similar to normal calculators in such a way that it displays the first number I type in, when i press the operand, the entry widget still displays the first number, but when i press the numbers for my second number, the first one gets replaced. I'm not to the point in writing the whole code yet, but I'm stuck at the point where when I press the 2nd number(s), the first set gets replaced. I was thinking about if key == one of the operands, than I set the num on the entry as variable first, then I do ent.delete(0,end) to clear the screen and ent.insert(0,first) to display the first num in the entry widget. Now I don't know what to do to clear the entry widget when the 2nd number(s) is pressed.
A:
What you need here is a concept of state. Each time a key is pressed, you check the state and determine what action to take.
In the initial state, you take input of numbers.
When an operand button is pressed, you store the operand, and change the state.
When another number is pressed, you store the number, clear the numeric input, and start the number input again.
Then when the equals button is pressed, you perform the operation, using your stored number and operand with the current number in the numeric input.
Note that with a dynamic language like Python, instead of using a variable and if statements to check the state, you can just change the function that handles key/button pressed depending on what the state is.
|
Creating a GUI Calculator in python similar to MS Calculator
|
I need to write a code that runs similar to normal calculators in such a way that it displays the first number I type in, when i press the operand, the entry widget still displays the first number, but when i press the numbers for my second number, the first one gets replaced. I'm not to the point in writing the whole code yet, but I'm stuck at the point where when I press the 2nd number(s), the first set gets replaced. I was thinking about if key == one of the operands, than I set the num on the entry as variable first, then I do ent.delete(0,end) to clear the screen and ent.insert(0,first) to display the first num in the entry widget. Now I don't know what to do to clear the entry widget when the 2nd number(s) is pressed.
|
[
"What you need here is a concept of state. Each time a key is pressed, you check the state and determine what action to take.\nIn the initial state, you take input of numbers.\nWhen an operand button is pressed, you store the operand, and change the state.\nWhen another number is pressed, you store the number, clear the numeric input, and start the number input again.\nThen when the equals button is pressed, you perform the operation, using your stored number and operand with the current number in the numeric input.\nNote that with a dynamic language like Python, instead of using a variable and if statements to check the state, you can just change the function that handles key/button pressed depending on what the state is.\n"
] |
[
2
] |
[] |
[] |
[
"calculator",
"python",
"user_interface"
] |
stackoverflow_0002264371_calculator_python_user_interface.txt
|
Q:
Python csv tags
I have a csv file with different headers.
name,city
john doe,chicago
Have headers as
reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
headers = reader.fieldnames
How will you run a regex that whenever a tag [name] was to be proceesed it will show "john doe"
A:
You could use re.sub() with a function passed as repl, or you could just use string interpolation with a mapping:
print 'My name is %(name)s' % rowdict
|
Python csv tags
|
I have a csv file with different headers.
name,city
john doe,chicago
Have headers as
reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
headers = reader.fieldnames
How will you run a regex that whenever a tag [name] was to be proceesed it will show "john doe"
|
[
"You could use re.sub() with a function passed as repl, or you could just use string interpolation with a mapping:\nprint 'My name is %(name)s' % rowdict\n\n"
] |
[
0
] |
[] |
[] |
[
"csv",
"python"
] |
stackoverflow_0002264567_csv_python.txt
|
Q:
if i have the key of google openid when someone who login my site,how do i get the username
if the key is https://www.google.com/accounts/o8/id?id=AItOawmqS0V2RR5FihojGdC90vXJpjcukoZ
how do i get the username who login my site ?
thanks
A:
I am afraid, that with OpenID, the URL really is the closest thing to a user name. According to Wikipedia:
Unlike a typical login form with fields for the user name and password, the OpenID login form has only one field—for the OpenID identifier, typically along with a small OpenID logo.
If you go to your own profile page here on StackOverflow, you should see a field named openid, containing the URL you are authenticated with. SO does not know which user name (if any) you use to authenticate with your OpenID provider.
However, it is possible (but not guaranteed) for login providers to provide a "nick name" for the user signed in. If it exists, it should be part of the response you get from the OpenID provider. Typically, you will want to add "user name" a field in your data model, and allow the user to supply a value for this field upon first login - initialized to nick name if available.
A:
Yup, the point with OpenID if you still need them to have an identifier to your page / site is to have a backend DB that attributes that key (openid url) with their identifier (key / username) on your site.
So googles A410d314 OpenID URL key is your 'superuser23' username. It can be a many to one correlation in a way and they can all point to 'superuser23'.
|
if i have the key of google openid when someone who login my site,how do i get the username
|
if the key is https://www.google.com/accounts/o8/id?id=AItOawmqS0V2RR5FihojGdC90vXJpjcukoZ
how do i get the username who login my site ?
thanks
|
[
"I am afraid, that with OpenID, the URL really is the closest thing to a user name. According to Wikipedia:\n\nUnlike a typical login form with fields for the user name and password, the OpenID login form has only one field—for the OpenID identifier, typically along with a small OpenID logo.\n\nIf you go to your own profile page here on StackOverflow, you should see a field named openid, containing the URL you are authenticated with. SO does not know which user name (if any) you use to authenticate with your OpenID provider.\nHowever, it is possible (but not guaranteed) for login providers to provide a \"nick name\" for the user signed in. If it exists, it should be part of the response you get from the OpenID provider. Typically, you will want to add \"user name\" a field in your data model, and allow the user to supply a value for this field upon first login - initialized to nick name if available.\n",
"Yup, the point with OpenID if you still need them to have an identifier to your page / site is to have a backend DB that attributes that key (openid url) with their identifier (key / username) on your site.\nSo googles A410d314 OpenID URL key is your 'superuser23' username. It can be a many to one correlation in a way and they can all point to 'superuser23'.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"openid",
"python"
] |
stackoverflow_0002264833_django_openid_python.txt
|
Q:
Where can I find some "hello world"-simple Beautiful Soup examples?
I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?
A:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('''
<html>
<head><title>Testing</title></head>
<body>
<a href="http://foo.com/">foo</a>
<a href="http://bar.com/bar">Bar</a>
</body>
</html>''')
for link in soup.findAll('a'): # find all links
link['href'] = link['href'] + '?foo'
print soup
That prints:
<html>
<head><title>Testing</title></head>
<body>
<a href="http://foo.com/?foo">foo</a>
<a href="http://bar.com/bar?foo">Bar</a>
</body>
</html>
The documentation also has some examples for changing attributes. It is an extensive tutorial that covers all common aspects of BeautifulSoup. I don't know what is missing from the documentation, maybe you should clarify.
A:
my example:
HEADERS = {"User-Agent" : "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5",
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language" : "ru,en-us;q=0.7,en;q=0.3",
"Accept-Charset" : "windows-1251,utf-8;q=0.7,*;q=0.7",
"Accept-Encoding" : "identity, *;q=0",
"Connection" : "Keep-Alive"}
PROXY=None
timeout=60
def parse_manuf_page_about(page_str_about):
slovar={}
global timeout
socket.setdefaulttimeout(timeout)
if PROXY is not None:
proxy_handler = urllib2.ProxyHandler( { "http": "http://"+PROXY+"/" } )
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
page_request = urllib2.Request(url=page_str_about, headers=HEADERS)
try:
#print "Page reading ... %s" %page_str
page_zapr = urllib2.urlopen(url=page_request)
page=page_zapr.read()
except Exception ,error:
print str(error)
res=False
return res,slovar
soup = BeautifulSoup(page)
select_pod=soup.findAll('div', {"class":"win aboutUs"})
promeg= select_pod[0].findAll("p")[0]
zerro_br= promeg.findAll(text=True)
Company_Info=" ".join(zerro_br).strip(" \t\n")
select =soup.findAll('div', {"class":"win"})
cells_tabl= select[0].findAll("tr")
for yach in cells_tabl:
text_zag=yach.findAll("th")
for zn_yach in text_zag:
if len(zn_yach)>0:
txt_zn_yach="".join(zn_yach.findAll(text=True)).strip(" \t\n")
else:
txt_zn_yach= zn_yach.contents[0].strip(" \t\n")
#print txt_zn_yach
text_znach_td=yach.findAll("td")
for zn_yach_td in text_znach_td:
if len(zn_yach_td)>0:
txt_zn_yach_td="".join(zn_yach_td.findAll(text=True)).strip(" \t\n")
else:
txt_zn_yach_td= zn_yach.contents[0].strip(" \t\n")
#print txt_zn_yach_td
# Делаем замены неугодных символов / Replase browsers char
if " " in txt_zn_yach_td:
while txt_zn_yach_td.find("nbsp;")>0:
pos_gavna=txt_zn_yach_td.find(" ")
txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+txt_zn_yach_td[pos_gavna+6:]
if """ in txt_zn_yach_td:
while txt_zn_yach_td.find("quot;")>0:
pos_gavna=txt_zn_yach_td.find(""")
txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+'"'+txt_zn_yach_td[pos_gavna+6:]
if "&" in txt_zn_yach_td:
while txt_zn_yach_td.find("&")>0:
pos_gavna=txt_zn_yach_td.find("&")
txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+'&'+txt_zn_yach_td[pos_gavna+6:]
slovar[str(txt_zn_yach)]=txt_zn_yach_td
slovar["Company_Info"]=Company_Info
# разбираем нижнюю таблицу с контактом и вытаскиваем оттуда имя контакта | get name contacts
select_contact=soup.findAll('a', {"class":"member-name"})
for contact_person in select_contact:
slovar["Contact_Person"]= contact_person.contents[0]
# получаем статус голд партнера по наличию таблички в левом верхнем углу | get Gold status
select_gold_part=soup.findAll('a', {"class":"memberLogo"})
if len(select_gold_part)==0:
slovar["Gold member"]="N"
else:
slovar["Gold member"]="Y"
res=True
return res,slovar
This code parsing one page of manufactury on Alibaba.com. You can see it page - http://xmxinhuafeng.en.alibaba.com/aboutus.html
|
Where can I find some "hello world"-simple Beautiful Soup examples?
|
I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?
|
[
"from BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup('''\n<html>\n <head><title>Testing</title></head>\n <body>\n <a href=\"http://foo.com/\">foo</a>\n <a href=\"http://bar.com/bar\">Bar</a>\n </body>\n</html>''')\n\nfor link in soup.findAll('a'): # find all links\n link['href'] = link['href'] + '?foo'\n\nprint soup\n\nThat prints:\n<html>\n<head><title>Testing</title></head>\n<body>\n<a href=\"http://foo.com/?foo\">foo</a>\n<a href=\"http://bar.com/bar?foo\">Bar</a>\n</body>\n</html>\n\nThe documentation also has some examples for changing attributes. It is an extensive tutorial that covers all common aspects of BeautifulSoup. I don't know what is missing from the documentation, maybe you should clarify.\n",
"my example:\nHEADERS = {\"User-Agent\" : \"Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5\",\n \"Accept\" : \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n \"Accept-Language\" : \"ru,en-us;q=0.7,en;q=0.3\",\n \"Accept-Charset\" : \"windows-1251,utf-8;q=0.7,*;q=0.7\",\n \"Accept-Encoding\" : \"identity, *;q=0\",\n \"Connection\" : \"Keep-Alive\"}\nPROXY=None\ntimeout=60\n\n\ndef parse_manuf_page_about(page_str_about):\nslovar={}\nglobal timeout\nsocket.setdefaulttimeout(timeout)\nif PROXY is not None:\n proxy_handler = urllib2.ProxyHandler( { \"http\": \"http://\"+PROXY+\"/\" } )\n opener = urllib2.build_opener(proxy_handler)\n urllib2.install_opener(opener)\npage_request = urllib2.Request(url=page_str_about, headers=HEADERS)\ntry:\n #print \"Page reading ... %s\" %page_str\n page_zapr = urllib2.urlopen(url=page_request)\n page=page_zapr.read()\nexcept Exception ,error:\n print str(error)\n res=False\n return res,slovar\nsoup = BeautifulSoup(page)\nselect_pod=soup.findAll('div', {\"class\":\"win aboutUs\"})\n\npromeg= select_pod[0].findAll(\"p\")[0]\nzerro_br= promeg.findAll(text=True)\nCompany_Info=\" \".join(zerro_br).strip(\" \\t\\n\")\nselect =soup.findAll('div', {\"class\":\"win\"})\ncells_tabl= select[0].findAll(\"tr\")\n\nfor yach in cells_tabl:\n text_zag=yach.findAll(\"th\")\n for zn_yach in text_zag:\n if len(zn_yach)>0:\n txt_zn_yach=\"\".join(zn_yach.findAll(text=True)).strip(\" \\t\\n\")\n else:\n txt_zn_yach= zn_yach.contents[0].strip(\" \\t\\n\")\n #print txt_zn_yach\n text_znach_td=yach.findAll(\"td\")\n for zn_yach_td in text_znach_td:\n if len(zn_yach_td)>0:\n txt_zn_yach_td=\"\".join(zn_yach_td.findAll(text=True)).strip(\" \\t\\n\")\n else:\n txt_zn_yach_td= zn_yach.contents[0].strip(\" \\t\\n\")\n #print txt_zn_yach_td\n # Делаем замены неугодных символов / Replase browsers char\n if \" \" in txt_zn_yach_td:\n while txt_zn_yach_td.find(\"nbsp;\")>0:\n pos_gavna=txt_zn_yach_td.find(\" \")\n txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+txt_zn_yach_td[pos_gavna+6:]\n if \""\" in txt_zn_yach_td:\n while txt_zn_yach_td.find(\"quot;\")>0:\n pos_gavna=txt_zn_yach_td.find(\""\")\n txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+'\"'+txt_zn_yach_td[pos_gavna+6:]\n if \"&\" in txt_zn_yach_td:\n while txt_zn_yach_td.find(\"&\")>0:\n pos_gavna=txt_zn_yach_td.find(\"&\")\n txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+'&'+txt_zn_yach_td[pos_gavna+6:]\n slovar[str(txt_zn_yach)]=txt_zn_yach_td\n slovar[\"Company_Info\"]=Company_Info\n# разбираем нижнюю таблицу с контактом и вытаскиваем оттуда имя контакта | get name contacts\nselect_contact=soup.findAll('a', {\"class\":\"member-name\"})\nfor contact_person in select_contact:\n slovar[\"Contact_Person\"]= contact_person.contents[0]\n# получаем статус голд партнера по наличию таблички в левом верхнем углу | get Gold status\nselect_gold_part=soup.findAll('a', {\"class\":\"memberLogo\"})\nif len(select_gold_part)==0:\n slovar[\"Gold member\"]=\"N\"\nelse:\n slovar[\"Gold member\"]=\"Y\"\nres=True\nreturn res,slovar\n\nThis code parsing one page of manufactury on Alibaba.com. You can see it page - http://xmxinhuafeng.en.alibaba.com/aboutus.html\n"
] |
[
15,
0
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0000821173_beautifulsoup_python.txt
|
Q:
How can I install django-stdimage in my django project, rather than as a module (jailed shell, no path access)
The question about covers it. I'm using dreamhost, and need to utilize the stdimagefield rather than image field so I can do this:
image3 = StdImageField(upload_to='path/to/img', size=(640, 480))
If there is a better way to do this, please let me know.
Edit: Trying it like this, everything is working with the "python manage.py shell" as you can see below:
>>> from stdimage import StdImageField
>>> image = StdImageField(upload_to='path', size=(425,325))
>>> print image
<stdimage.fields.StdImageField object at 0x762db3ac5910>
When I try to use it in my model though, I get this error on every page:
Using the URLconf defined in runningshoesreview.urls, Django tried these URL patterns, in this order:
^admin/(.*)
^reviews/
The current URL, internal_error.html, didn't match any of these.
A:
Just put the django-stdimage folder into your project folder (it should already be a package).
A:
Just copy the module contents into your project, making it a package if necessary. I put "external" modules in an external package.
|
How can I install django-stdimage in my django project, rather than as a module (jailed shell, no path access)
|
The question about covers it. I'm using dreamhost, and need to utilize the stdimagefield rather than image field so I can do this:
image3 = StdImageField(upload_to='path/to/img', size=(640, 480))
If there is a better way to do this, please let me know.
Edit: Trying it like this, everything is working with the "python manage.py shell" as you can see below:
>>> from stdimage import StdImageField
>>> image = StdImageField(upload_to='path', size=(425,325))
>>> print image
<stdimage.fields.StdImageField object at 0x762db3ac5910>
When I try to use it in my model though, I get this error on every page:
Using the URLconf defined in runningshoesreview.urls, Django tried these URL patterns, in this order:
^admin/(.*)
^reviews/
The current URL, internal_error.html, didn't match any of these.
|
[
"Just put the django-stdimage folder into your project folder (it should already be a package).\n",
"Just copy the module contents into your project, making it a package if necessary. I put \"external\" modules in an external package.\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"dreamhost",
"module",
"python"
] |
stackoverflow_0002264959_django_dreamhost_module_python.txt
|
Q:
How can I write a Python list to persistent storage?
I am currently trying to solve this problem in MySQL. I have MySQLdb installed. What is the best way to write a list in Python, e.g.
[1, 2, -1, -2]
to a column of a MySQL database table? I would like each consecutive entry of the list to be put into consecutive rows of a MySQL column. I can obviously run individual queries in a loop, but I was wondering if there is any better/faster way.
I am also willing to experiment with different data storage techniques if this isn't possible using MySQLdb. I am working with lists that contain several million entries each, and need to read/write quickly to some form of persistent storage that can store these many different lists as columns.
UPDATE: Thanks for your responses. After being led to search for execute many, I found this link, which had a useful example of executemany().
A:
You're looking for executemany().
A:
Caution: There is no notion of consecutive rows in SQL.
The order of input is not recorded in the SQL database unless you also have an auto increment column that is automatically updated as you insert data or some other way to order the data on input, and the order of output depends on your ORDER BY clause.
|
How can I write a Python list to persistent storage?
|
I am currently trying to solve this problem in MySQL. I have MySQLdb installed. What is the best way to write a list in Python, e.g.
[1, 2, -1, -2]
to a column of a MySQL database table? I would like each consecutive entry of the list to be put into consecutive rows of a MySQL column. I can obviously run individual queries in a loop, but I was wondering if there is any better/faster way.
I am also willing to experiment with different data storage techniques if this isn't possible using MySQLdb. I am working with lists that contain several million entries each, and need to read/write quickly to some form of persistent storage that can store these many different lists as columns.
UPDATE: Thanks for your responses. After being led to search for execute many, I found this link, which had a useful example of executemany().
|
[
"You're looking for executemany().\n",
"Caution: There is no notion of consecutive rows in SQL.\nThe order of input is not recorded in the SQL database unless you also have an auto increment column that is automatically updated as you insert data or some other way to order the data on input, and the order of output depends on your ORDER BY clause.\n"
] |
[
2,
2
] |
[] |
[] |
[
"mysql",
"python",
"storage"
] |
stackoverflow_0002265016_mysql_python_storage.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.