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:
nosetest deprecation warnings
I am getting deprecation warnings from nosetest for 3rd party modules imported by my code.
Does anybody know how to silence these warnings?
I know of the following flag which works for arbitrary python runs of the same code:
python -W ignore::DeprecationWarning
But, calling nosetest does not appear to offer me a similar flag to prevent the warnings from appearing within the test reports.
A:
Put
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
at the start of your test script, before you import any problematic libraries.
| nosetest deprecation warnings | I am getting deprecation warnings from nosetest for 3rd party modules imported by my code.
Does anybody know how to silence these warnings?
I know of the following flag which works for arbitrary python runs of the same code:
python -W ignore::DeprecationWarning
But, calling nosetest does not appear to offer me a similar flag to prevent the warnings from appearing within the test reports.
| [
"Put \nimport warnings\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\n\nat the start of your test script, before you import any problematic libraries.\n"
] | [
3
] | [] | [] | [
"deprecated",
"python",
"suppress_warnings",
"unit_testing"
] | stackoverflow_0003728325_deprecated_python_suppress_warnings_unit_testing.txt |
Q:
Python USSD via com port
I am new to python. Is there anyway i can use python to send ussd with a phone via at+cusd commands. i can do that using hyperterminal. i want to automate using python. thanks.
A:
Yes. Use pyserial.
>>> import serial
>>> ser = serial.Serial(0) # open first serial port
>>> print ser.portstr # check which port was really used
>>> ser.write("hello") # write a string
>>> ser.close() # close port
| Python USSD via com port | I am new to python. Is there anyway i can use python to send ussd with a phone via at+cusd commands. i can do that using hyperterminal. i want to automate using python. thanks.
| [
"Yes. Use pyserial.\n>>> import serial\n>>> ser = serial.Serial(0) # open first serial port\n>>> print ser.portstr # check which port was really used\n>>> ser.write(\"hello\") # write a string\n>>> ser.close() # close port\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003727938_python.txt |
Q:
Getting current user home directory on OS X?
How to find current user home directory on OS X?
HOME environmental variable is not always set, for example when you do not run in console (GUI apps).
For this reason I'm looking for a generic solution, one that will fall-back if os.environ['HOME'] is not set.
There is a similar question (C) but it already has an accepted solution that is invalid.
A Python solution would be preferred but other languages are welcome as long they provide a valid home or at least one location where you can write.
A:
It looks that os.path.expanduser("~") always returns the home directory, even on Windows.
| Getting current user home directory on OS X? | How to find current user home directory on OS X?
HOME environmental variable is not always set, for example when you do not run in console (GUI apps).
For this reason I'm looking for a generic solution, one that will fall-back if os.environ['HOME'] is not set.
There is a similar question (C) but it already has an accepted solution that is invalid.
A Python solution would be preferred but other languages are welcome as long they provide a valid home or at least one location where you can write.
| [
"It looks that os.path.expanduser(\"~\") always returns the home directory, even on Windows.\n"
] | [
1
] | [] | [] | [
"home_directory",
"macos",
"python"
] | stackoverflow_0003726113_home_directory_macos_python.txt |
Q:
How to quickly fail a python script if it is called from wrong interpreter?
I have inherited a few Python scripts from someone who has left my employer. Some are meant to be run from Jython, others are not.
I'd like to add them to svn, but before I do I want to modify these files so that if a "requires Jython" file is run from python, the user gets a message like "please run with Jython" and the program exits.
(Warning: I am not very familiar with Python/Jython.)
I expect the simplest way to do this is create a file require-jython.py with the contents like:
if runtime.name != 'jython'
print "Please run with Jython"
exit(1)
and then "include/require"? this file (again I'm not an expert. bear with me here)
Can anyone spell out the steps for me?
A:
What I have seen done is to try to import a module exclusive to a given version or implementation, and raise ImportError if the module does not exist.
Imagine that Jython (and not Python) has a module called special, then you add:
# at the top of your module:
try:
import special
except ImportError:
raise ImportError("this script is meant to be used with Jython")
else:
raise
Notice that you make the ImportError exception more explicit, as opposed to simply raising it (and lead the user to believe that there was a problem with the module itself, as opposed to informing that the interpreter was improperly selected). I would give you a more concrete example of what module to import, but I am not at all familiar with Jython.
In other words, use duck typing for the module import: assume the import was made correctly but fail as soon as you cannot find the expected behaviour (this is what the try statement is supposed to be used for).
Another way to check the interpreter is to use the sys module (in Python - I don't know if Jython has it):
>>> import sys
>>> print sys.subversion
('CPython', 'tags/r264', '75821M')
| How to quickly fail a python script if it is called from wrong interpreter? | I have inherited a few Python scripts from someone who has left my employer. Some are meant to be run from Jython, others are not.
I'd like to add them to svn, but before I do I want to modify these files so that if a "requires Jython" file is run from python, the user gets a message like "please run with Jython" and the program exits.
(Warning: I am not very familiar with Python/Jython.)
I expect the simplest way to do this is create a file require-jython.py with the contents like:
if runtime.name != 'jython'
print "Please run with Jython"
exit(1)
and then "include/require"? this file (again I'm not an expert. bear with me here)
Can anyone spell out the steps for me?
| [
"What I have seen done is to try to import a module exclusive to a given version or implementation, and raise ImportError if the module does not exist. \nImagine that Jython (and not Python) has a module called special, then you add:\n# at the top of your module:\ntry:\n import special\nexcept ImportError:\n ra... | [
3
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0003728546_jython_python.txt |
Q:
Python scoping and threading question
I have one thread that inserts into the queueStream (not shown here) and FlowController which is another thread that pops from the queue if the queue is not empty.
I verified that the data is inserted into the queue correctly with the debug code in addToQueue()
Problem is, the 'if queueStream' statement in FlowController always sees the queueStream as empty, and instead goes to the else statement.
I'm new to Python and I feel I'm missing some simple scoping rules of some kind. I am using the 'global queueStream' but that appears to not be doing anything.
Thanks for any help.
from stream import *
from textwrap import TextWrapper
import threading
import time
queueStream = []
class FlowController(threading.Thread):
def run(self):
global queueStream
while True:
if queueStream:
print 'Handling tweet'
self.handleNextTweet()
else:
print 'No tweets, sleep for 1 second'
time.sleep(1)
def handleNextTweet(self):
global queueStream
status = queueStream.pop(0)
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
def addToQueue(status):
print 'adding tweets to the queue'
queueStream.append(status)
#debug
if queueStream:
print 'queueStream is non-empty'
if __name__ == '__main__':
try:
runner = RunStream()
runner.start()
flow = FlowController()
flow.start()
except KeyboardInterrupt:
print '\nGoodbye!'
EDIT::::::::::::
Thanks for the help so far. The Queue documentation is nice and has helped me write cleaner code since the get() function blocks (cool!). Anyway, it still did not solve my problem, but I printed out the queueStream instance before passing it to FlowController and after, and they had two different memory locations. That is why I believe nothing is being popped from the queue in FlowController. Does that mean that Python passes queueStream by value and not by reference? If so, how do I get around that?
from stream import *
from textwrap import TextWrapper
from threading import Thread
from Queue import Queue
import time
class FlowController(Thread):
def __init__(self, queueStream):
Thread.__init__(self)
self.queueStream=queueStream
def run(self):
while True:
status = self.queueStream.get()
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
def addToQueue(status):
print 'adding tweets to the queue'
queueStream.put(status)
queueStream = Queue()
if __name__ == '__main__':
try:
runner = RunStream()
runner.start()
flow = FlowController(queueStream)
flow.start()
except KeyboardInterrupt:
print '\nGoodbye!'
A:
It's hard to debug this problem without seeing RunStream.
So I tried to dream up a simple RunStream that might exhibit the problem.
I wasn't able to reproduce the problem, but this code seems to work.
If it does work and is similar enough to your RunStream, perhaps you can compare this code to your own to find what's wrong.
import threading
import time
import Queue
import sys
import random
class FlowController(threading.Thread):
def __init__(self,queueStream):
threading.Thread.__init__(self)
self.queueStream=queueStream
def run(self):
while True:
if not self.queueStream.empty():
print 'Handling tweet'
self.handleNextTweet()
else:
print 'No tweets, sleep for 1 second'
time.sleep(1)
def handleNextTweet(self):
status = self.queueStream.get()
print(status)
class RunStream(threading.Thread):
def __init__(self,queueStream):
threading.Thread.__init__(self)
self.queueStream=queueStream
def run(self):
i=0
while True:
addToQueue(self.queueStream,i)
i+=1
time.sleep(random.randint(0,2))
def addToQueue(queueStream,status):
print 'adding tweets to the queue'
queueStream.put(status)
if not queueStream.empty():
print 'queueStream is non-empty'
if __name__ == '__main__':
queueStream = Queue.Queue()
try:
runner = RunStream(queueStream)
runner.daemon=True
runner.start()
flow = FlowController(queueStream)
flow.daemon=True
flow.start()
time.sleep(100)
except KeyboardInterrupt:
pass
finally:
print('Bye!')
A:
I'm not a python expert, but I believe you have to declare your global variables even in module level functions
def addToQueue(status):
global queueStream
print 'adding tweets to the queue'
queueStream.append(status)
#debug
if queueStream:
print 'queueStream is non-empty'
| Python scoping and threading question | I have one thread that inserts into the queueStream (not shown here) and FlowController which is another thread that pops from the queue if the queue is not empty.
I verified that the data is inserted into the queue correctly with the debug code in addToQueue()
Problem is, the 'if queueStream' statement in FlowController always sees the queueStream as empty, and instead goes to the else statement.
I'm new to Python and I feel I'm missing some simple scoping rules of some kind. I am using the 'global queueStream' but that appears to not be doing anything.
Thanks for any help.
from stream import *
from textwrap import TextWrapper
import threading
import time
queueStream = []
class FlowController(threading.Thread):
def run(self):
global queueStream
while True:
if queueStream:
print 'Handling tweet'
self.handleNextTweet()
else:
print 'No tweets, sleep for 1 second'
time.sleep(1)
def handleNextTweet(self):
global queueStream
status = queueStream.pop(0)
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
def addToQueue(status):
print 'adding tweets to the queue'
queueStream.append(status)
#debug
if queueStream:
print 'queueStream is non-empty'
if __name__ == '__main__':
try:
runner = RunStream()
runner.start()
flow = FlowController()
flow.start()
except KeyboardInterrupt:
print '\nGoodbye!'
EDIT::::::::::::
Thanks for the help so far. The Queue documentation is nice and has helped me write cleaner code since the get() function blocks (cool!). Anyway, it still did not solve my problem, but I printed out the queueStream instance before passing it to FlowController and after, and they had two different memory locations. That is why I believe nothing is being popped from the queue in FlowController. Does that mean that Python passes queueStream by value and not by reference? If so, how do I get around that?
from stream import *
from textwrap import TextWrapper
from threading import Thread
from Queue import Queue
import time
class FlowController(Thread):
def __init__(self, queueStream):
Thread.__init__(self)
self.queueStream=queueStream
def run(self):
while True:
status = self.queueStream.get()
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
def addToQueue(status):
print 'adding tweets to the queue'
queueStream.put(status)
queueStream = Queue()
if __name__ == '__main__':
try:
runner = RunStream()
runner.start()
flow = FlowController(queueStream)
flow.start()
except KeyboardInterrupt:
print '\nGoodbye!'
| [
"It's hard to debug this problem without seeing RunStream.\nSo I tried to dream up a simple RunStream that might exhibit the problem.\nI wasn't able to reproduce the problem, but this code seems to work. \nIf it does work and is similar enough to your RunStream, perhaps you can compare this code to your own to find... | [
1,
0
] | [] | [] | [
"multithreading",
"python",
"scoping"
] | stackoverflow_0003728577_multithreading_python_scoping.txt |
Q:
How can I programmatically change the argspec of a function in a python decorator?
Given a function:
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
@decorator
def func2(f1, kw='default'):
pass
decorated_argspec = inspect.getargspec(func2)
How can I create a decorator such that bare_argspec == decorated_argspec?
(As to why, the framework that calls the decorated function does argspec inspection to choose what to pass in, so the decorator has to retain the same argspec in order to play nice. When I posed this question on #python, I got a long speech about why the framework sucks, which is not what I'm looking for; I have to solve the problem here. Also, I'm just interested in the answer, too)
A:
Michele Simionato's decorator module has a decorator called decorator which preserves function argspecs.
import inspect
import decorator
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
print(bare_argspec)
# ArgSpec(args=['f1', 'kw'], varargs=None, keywords=None, defaults=('default',))
@decorator.decorator
def mydecorator(func,*args,**kw):
result=func(*args,**kw)
return result
@mydecorator
def func2(f1, kw='default'):
pass
decorated_argspec = inspect.getargspec(func2)
print(decorated_argspec)
# ArgSpec(args=['f1', 'kw'], varargs=None, keywords=None, defaults=('default',))
assert(bare_argspec==decorated_argspec)
A:
There's the decorator module:
from decorator import decorator
@decorator
def trace(func, *args, **kw):
print 'calling', func, 'with', args, kw
return func(*args, **kw)
That makes trace a decorator with the same argspecs as the decorated function. Example:
>>> @trace
... def f(x, y=1, z=2, *args, **kw):
... pass
>>> f(0, 3)
calling f with (0, 3, 2), {}
>>> from inspect import getargspec
>>> print getargspec(f)
ArgSpec(args=['x', 'y', 'z'], varargs='args', keywords='kw', defaults=(1, 2))
A:
Are functools.update_wrapper() and/or functools.wraps() good enough?
| How can I programmatically change the argspec of a function in a python decorator? | Given a function:
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
@decorator
def func2(f1, kw='default'):
pass
decorated_argspec = inspect.getargspec(func2)
How can I create a decorator such that bare_argspec == decorated_argspec?
(As to why, the framework that calls the decorated function does argspec inspection to choose what to pass in, so the decorator has to retain the same argspec in order to play nice. When I posed this question on #python, I got a long speech about why the framework sucks, which is not what I'm looking for; I have to solve the problem here. Also, I'm just interested in the answer, too)
| [
"Michele Simionato's decorator module has a decorator called decorator which preserves function argspecs.\nimport inspect\nimport decorator\n\ndef func(f1, kw='default'):\n pass\nbare_argspec = inspect.getargspec(func)\nprint(bare_argspec)\n# ArgSpec(args=['f1', 'kw'], varargs=None, keywords=None, defaults=('def... | [
13,
2,
0
] | [] | [] | [
"decorator",
"inspect",
"python",
"reflection"
] | stackoverflow_0003729378_decorator_inspect_python_reflection.txt |
Q:
python re: r'\b \$ \d+ \b' won't match 'aug 12, 2010 abc $123'
so i'm just making a script to collect $ values from a transaction log type file
for line in sys.stdin:
match = re.match( r'\b \$ (\d+) \b', line)
if match is not None:
for value in match.groups():
print value
right now I'm just trying to print those values
it would match a line containing $12323 but not when there are other things in the line
From what I read it should work, but looks like I could be missing something
A:
re.match:
If zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.
What your are looking for is either re.search or re.findall:
#!/usr/bin/env python
import re
s = 'aug 12, 2010 abc $123'
print re.findall(r'\$(\d+)', s)
# => ['123']
print re.search(r'\$(\d+)', s).group()
# => $123
print re.search(r'\$(\d+)', s).group(1)
# => 123
A:
By having a space between \$ and (\d+), the regex expects a space in your string between them. Is there such a space?
A:
I am not so clear what is accepted for you but from statement
a line containing $12323 but not when there are other things in the line
I would get that
'aug 12, 2010 abc $123'
Is not supposed to match as it has other text befor the amount.
If you want to match amount at end of the line here is the customary anti-regexp answer (even I am not against of using them in easy cases):
loglines = ['aug 12, 2010 abc $123', " $1 ", "a $1 amount", "exactly $1 - no less"]
# match $amount at end of line without other text after
for line in loglines:
if '$' in line:
_,_, amount = line.rpartition('$')
try:
amount = float(amount)
except:
pass
else:
print "$%.2f" % amount
A:
Others have already pointed out some shortcomings of your regex (especially the mandatory spaces and re.match vs. re.search).
There is another thing, though: \b word anchors match between alphanumeric and non-alphanumeric characters. In other words, \b \$ will fail (even when doing a search instead of a match operation) unless the string has some alphanumeric characters before the space.
Example (admittedly contrived) to work with your regex:
>>> import re
>>> test = [" $1 ", "a $1 amount", "exactly $1 - no less"]
>>> for string in test:
... print(re.search(r"\b \$\d+ \b", string))
...
None
<_sre.SRE_Match object at 0x0000000001DD4370>
None
| python re: r'\b \$ \d+ \b' won't match 'aug 12, 2010 abc $123' | so i'm just making a script to collect $ values from a transaction log type file
for line in sys.stdin:
match = re.match( r'\b \$ (\d+) \b', line)
if match is not None:
for value in match.groups():
print value
right now I'm just trying to print those values
it would match a line containing $12323 but not when there are other things in the line
From what I read it should work, but looks like I could be missing something
| [
"re.match:\n\nIf zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.\n\nWhat your are looking for is either re.search or re.findall:\... | [
6,
3,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003728292_python_regex.txt |
Q:
Python: Execute a command in a subshell without cmd interface or hidden or in background
I would like to know how I could execute a command whitout appears the cmd window.
My code is in Python and the O.S. is Windows7.
The problematic line is:
os.system(pathandarguments)
The program works fine, execute the given path with the arguments but I loose the control of my program because my program window minimizes, I see cmd window a seconds and then my window program dont maximizes.
I want to execute the string pathandarguments without minimize my principal window. I prefer, if its possible, dont show cmd window.
I tried differents ways to make this:
os.system(pathandarguments) = works fine but minimizes my program window.
os.popen(pathandarguments) = ERROR: CThread::staticThread : Access violation at 0x77498c19: Writing location 0x00000014 (Don't work)
subprocess.Popen([pathandarguments], shell=False) = Exception in python script's onAction (Don't work)
Thanks in advance.
EDIT
@martineau, The problem is not that I cannot import process, revising the log of my app I saw the problem is with import process at line 146:
13:42:20 T:4116 M:2156859392 NOTICE: import win32api
13:42:20 T:4116 M:2156859392 NOTICE: ImportError
13:42:20 T:4116 M:2156859392 NOTICE: :
13:42:20 T:4116 M:2156859392 NOTICE: No module named win32api
I dont have module win32api.
A:
For a long time I've been using an open source Python module for process control called process-python. The Project Status there says "In its current state it was used heavily in the commercial Komodo IDE project." It's multiplatform, but one of the main reasons I started using it was because on Windows it will spawn a process without a console window. It's very simple to use. Here's a trivial example:
import process
p = process.ProcessOpen([eventfilepath]) # open text file with associated program
ignored_exitstatus = p.wait()
Hope this helps.
| Python: Execute a command in a subshell without cmd interface or hidden or in background | I would like to know how I could execute a command whitout appears the cmd window.
My code is in Python and the O.S. is Windows7.
The problematic line is:
os.system(pathandarguments)
The program works fine, execute the given path with the arguments but I loose the control of my program because my program window minimizes, I see cmd window a seconds and then my window program dont maximizes.
I want to execute the string pathandarguments without minimize my principal window. I prefer, if its possible, dont show cmd window.
I tried differents ways to make this:
os.system(pathandarguments) = works fine but minimizes my program window.
os.popen(pathandarguments) = ERROR: CThread::staticThread : Access violation at 0x77498c19: Writing location 0x00000014 (Don't work)
subprocess.Popen([pathandarguments], shell=False) = Exception in python script's onAction (Don't work)
Thanks in advance.
EDIT
@martineau, The problem is not that I cannot import process, revising the log of my app I saw the problem is with import process at line 146:
13:42:20 T:4116 M:2156859392 NOTICE: import win32api
13:42:20 T:4116 M:2156859392 NOTICE: ImportError
13:42:20 T:4116 M:2156859392 NOTICE: :
13:42:20 T:4116 M:2156859392 NOTICE: No module named win32api
I dont have module win32api.
| [
"For a long time I've been using an open source Python module for process control called process-python. The Project Status there says \"In its current state it was used heavily in the commercial Komodo IDE project.\" It's multiplatform, but one of the main reasons I started using it was because on Windows it will ... | [
1
] | [] | [] | [
"cmd",
"python"
] | stackoverflow_0003729061_cmd_python.txt |
Q:
Uses of self referencing lists
I know it is possible to create a self referencing list in languages like Python:
>>> my_list = [1,2]
>>> my_list.append(my_list)
>>> print my_list
[1,2,[...]]
>>> print my_list[0]
1
>>> print my_list[2]
[1,2,[...]]
What algorithms benefit from self referencing lists? I cannot think of one.
Thanks.
A:
Self-referencing lists, and, generally speaking, circular data structures, can be caused when representing a graph using data structures.
For example, consider this naive representation of a graph: Each node is either an atomic value, or a list of nodes that it is linked to. A circle may cause a list to contain another list that contains the list. A self-circle, i.e., an edge from a node to itself, will cause a self-referencing list.
A:
Most recursive problem definition uses some kind of self refrential objects or a data with self-referential definition.
I would add the wikipedia link as it provides a good readup:
http://en.wikipedia.org/wiki/Recursion_(computer_science)
Others on SO
What is recursion and when should I use it?
Recursive Sets vs Recursive Functions
Understanding recursion
Recursive Splay Tree
https://stackoverflow.com/questions/2085834/how-did-you-practically-use-recursion
A:
If you are asking just about lists, then I can't think of something right now, except for maybe recursively creating/searching in a data structure modeled as list.
But one application of a self-referencing could be this Self Referencing Class Definition in python
| Uses of self referencing lists | I know it is possible to create a self referencing list in languages like Python:
>>> my_list = [1,2]
>>> my_list.append(my_list)
>>> print my_list
[1,2,[...]]
>>> print my_list[0]
1
>>> print my_list[2]
[1,2,[...]]
What algorithms benefit from self referencing lists? I cannot think of one.
Thanks.
| [
"Self-referencing lists, and, generally speaking, circular data structures, can be caused when representing a graph using data structures.\nFor example, consider this naive representation of a graph: Each node is either an atomic value, or a list of nodes that it is linked to. A circle may cause a list to contain a... | [
4,
0,
0
] | [] | [] | [
"algorithm",
"language_agnostic",
"list",
"python",
"self_reference"
] | stackoverflow_0003728667_algorithm_language_agnostic_list_python_self_reference.txt |
Q:
a list of pygame sprites loses its first element, and gains a duplicate of the last
I have a function that loads a sprite sheet, finds a block of sprites, and then puts each individual sprite into a list. Before it appends a sprite into the list, it will blit it onto the screen. Once it's done loading sprites, it will then iterate through the list, blitting each sprite as it goes. The two sets of blits should be identical, but instead the first sprite is dropped from the list, and the last sprite is duplicated. The two sets of blits look like this:
Each sprite is blitted in the order it was appended to the list, going from left to right, top to bottom, so the first sprite is the top left one, and the last is the bottom right.
Here's the function that loads the sprites:
def assembleSprites(name, screen):
"""Given a character name, this function will return a list of all that
character's sprites. This is used to populate the global variable spriteSets"""
spriteSize = (35, 35)
spritesheet = pygame.image.load("./images/patchconsprites.png")
sprites = []
start = charCoords[name]
char = list(start)
image = pygame.Surface((35,35))
# load each sprite and blit them as they're added to the list
for y in range(5):
char[0] = start[0]
for x in range(9):
rect = (char[0], char[1], char[0]+spriteSize[0], char[1]+spriteSize[1])
image.blit(spritesheet, (0,0), rect)
image = image.convert()
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
screen.blit(image, (x*40, y*40))
pygame.display.update()
sprites.append(image)
char[0] += spriteSize[0]+2
char[1] += spriteSize[1]+2
# check that the list was constructed correctly
count = 0
for y in range(6,11):
for x in range(9):
screen.blit(sprites[count], (x*40,y*40))
count += 1
pygame.display.update()
return sprites
Anyone see how I'm screwing the list up?
A:
image.blit(spritesheet, (0,0), rect)
You haven't re-initialised image each time around the loop, it's still the same surface you used in the previous iteration, a surface that is already in the list. Each time round the loop you overwrite the sprite you appended to the list in the previous step.
I suggest grabbing a new image= pygame.Surface((35,35)) immediately before the line instead of before the start of the loop.
| a list of pygame sprites loses its first element, and gains a duplicate of the last | I have a function that loads a sprite sheet, finds a block of sprites, and then puts each individual sprite into a list. Before it appends a sprite into the list, it will blit it onto the screen. Once it's done loading sprites, it will then iterate through the list, blitting each sprite as it goes. The two sets of blits should be identical, but instead the first sprite is dropped from the list, and the last sprite is duplicated. The two sets of blits look like this:
Each sprite is blitted in the order it was appended to the list, going from left to right, top to bottom, so the first sprite is the top left one, and the last is the bottom right.
Here's the function that loads the sprites:
def assembleSprites(name, screen):
"""Given a character name, this function will return a list of all that
character's sprites. This is used to populate the global variable spriteSets"""
spriteSize = (35, 35)
spritesheet = pygame.image.load("./images/patchconsprites.png")
sprites = []
start = charCoords[name]
char = list(start)
image = pygame.Surface((35,35))
# load each sprite and blit them as they're added to the list
for y in range(5):
char[0] = start[0]
for x in range(9):
rect = (char[0], char[1], char[0]+spriteSize[0], char[1]+spriteSize[1])
image.blit(spritesheet, (0,0), rect)
image = image.convert()
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
screen.blit(image, (x*40, y*40))
pygame.display.update()
sprites.append(image)
char[0] += spriteSize[0]+2
char[1] += spriteSize[1]+2
# check that the list was constructed correctly
count = 0
for y in range(6,11):
for x in range(9):
screen.blit(sprites[count], (x*40,y*40))
count += 1
pygame.display.update()
return sprites
Anyone see how I'm screwing the list up?
| [
"image.blit(spritesheet, (0,0), rect)\n\nYou haven't re-initialised image each time around the loop, it's still the same surface you used in the previous iteration, a surface that is already in the list. Each time round the loop you overwrite the sprite you appended to the list in the previous step.\nI suggest grab... | [
7
] | [] | [] | [
"list",
"pygame",
"python"
] | stackoverflow_0003729648_list_pygame_python.txt |
Q:
Issue with Django admin registering an inline user profile admin
I'm currently working on a django project. I'm attempting to add a UserProfile model inline to my User model. In my models.py I have:
class UserProfile(models.Model):
'''
Extension to the User model in django admin.
'''
user = models.ForeignKey(User)
site_role = models.CharField(max_length=128, choices=SITE_ROLE)
signature = models.CharField(max_length=128)
position_title = models.CharField(max_length=128)
on_duty = models.BooleanField(default=False)
on_duty_order = models.IntegerField()
In my admin.py I have:
class UserProfileInline(admin.StackedInline):
model = UserProfile
class UserAdmin(admin.ModelAdmin):
inlines = [UserProfileInline]
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
When I run the development server (yes, I have restarted it) I get the following exception:
NotRegistered at /admin
The model User is not registered
This exception is coming from the admin.site.unregister(User) line.
However, when I comment out that line, I get the following exception:
AlreadyRegistered at /admin
The model User is already registered
Something about my django setup seems to be a little bi-polar. I've spent an hour or so researching this problem and the code I have seems to work great for others. Does anyone have any insight into why this might be happening?
Thanks,
Travis
A:
my guess is that you either are doing some crazy module importing... or... you have an ordering problem in your settings.INSTALLED_APPS list. Make sure that 'django.contrib.auth' appears on your list before your app that is replacing the default admin. The list should look something like this:
INSTALLED_APPS = (
# django apps first
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
# your stuff from here on
'yourproject.userstuff',
)
That way django's app registers the User model, and then you unregister and re-register it with your own ModelAdmin.
| Issue with Django admin registering an inline user profile admin | I'm currently working on a django project. I'm attempting to add a UserProfile model inline to my User model. In my models.py I have:
class UserProfile(models.Model):
'''
Extension to the User model in django admin.
'''
user = models.ForeignKey(User)
site_role = models.CharField(max_length=128, choices=SITE_ROLE)
signature = models.CharField(max_length=128)
position_title = models.CharField(max_length=128)
on_duty = models.BooleanField(default=False)
on_duty_order = models.IntegerField()
In my admin.py I have:
class UserProfileInline(admin.StackedInline):
model = UserProfile
class UserAdmin(admin.ModelAdmin):
inlines = [UserProfileInline]
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
When I run the development server (yes, I have restarted it) I get the following exception:
NotRegistered at /admin
The model User is not registered
This exception is coming from the admin.site.unregister(User) line.
However, when I comment out that line, I get the following exception:
AlreadyRegistered at /admin
The model User is already registered
Something about my django setup seems to be a little bi-polar. I've spent an hour or so researching this problem and the code I have seems to work great for others. Does anyone have any insight into why this might be happening?
Thanks,
Travis
| [
"my guess is that you either are doing some crazy module importing... or... you have an ordering problem in your settings.INSTALLED_APPS list. Make sure that 'django.contrib.auth' appears on your list before your app that is replacing the default admin. The list should look something like this:\nINSTALLED_APPS = (\... | [
21
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003729866_django_django_admin_python.txt |
Q:
Why can't I "save as" an Excel file from my Python code?
I have an Python ExcelDocument class that provides basic convenience methods for reading/writing/formatting Excel files, and I'm getting a strange error in seemingly simple Python code. I have a save and saveAs method:
def save(self):
''' Save the file '''
self.workbook.Save()
def saveAs(self, newFileName):
''' Save the file as a new file with a different name '''
self.workbook.SaveAs(newFileName)
The save method works perfectly, but when I try to call the saveAs method - myExcelObject.saveAs("C:/test.xlsx") - I get the following error:
Traceback (most recent call last):
File "C:\workspace\Utilities\src\util\excel.py", line 201, in <module>
excel.saveAs("C:/test.xlx")
File "C:\workspace\Utilities\src\util\excel.py", line 185, in saveAs
self.workbook.SaveAs(newFileName)
File "<COMObject Open>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u"Microsoft Office Excel cannot access the file 'C:\\//8CBD2000'. There are several possible reasons:\n\n\u2022 The file name or path does not exist.\n\u2022 The file is being used by another program.\n\u2022 The workbook you are trying to save has the same name as a currently open workbook.", u'C:\\Program Files\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)
Can anyone explain what is happening?
A:
I've found (the hard way) that SaveAs doesn't support slash /.
Try saveAs("C:\\test.xlx") instead.
| Why can't I "save as" an Excel file from my Python code? | I have an Python ExcelDocument class that provides basic convenience methods for reading/writing/formatting Excel files, and I'm getting a strange error in seemingly simple Python code. I have a save and saveAs method:
def save(self):
''' Save the file '''
self.workbook.Save()
def saveAs(self, newFileName):
''' Save the file as a new file with a different name '''
self.workbook.SaveAs(newFileName)
The save method works perfectly, but when I try to call the saveAs method - myExcelObject.saveAs("C:/test.xlsx") - I get the following error:
Traceback (most recent call last):
File "C:\workspace\Utilities\src\util\excel.py", line 201, in <module>
excel.saveAs("C:/test.xlx")
File "C:\workspace\Utilities\src\util\excel.py", line 185, in saveAs
self.workbook.SaveAs(newFileName)
File "<COMObject Open>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u"Microsoft Office Excel cannot access the file 'C:\\//8CBD2000'. There are several possible reasons:\n\n\u2022 The file name or path does not exist.\n\u2022 The file is being used by another program.\n\u2022 The workbook you are trying to save has the same name as a currently open workbook.", u'C:\\Program Files\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)
Can anyone explain what is happening?
| [
"I've found (the hard way) that SaveAs doesn't support slash /.\nTry saveAs(\"C:\\\\test.xlx\") instead.\n"
] | [
18
] | [] | [] | [
"python",
"save_as"
] | stackoverflow_0003730428_python_save_as.txt |
Q:
Trying to group similar text rows in a column of a million row table - Open to Non-MySQL approaches
I have a large number (about 40 million) of VARCHAR entries in a MySQL table. The length of the string can be anywhere between 5-80 characters. I am trying to group similar text together and thought of a possible approach:
Take a row and calculate a similarity measure (like Edit Distance) with every other row and decide (I am not sure how to decide though) whether each belongs to the same group. For instance, I have the following entries:
The quick brown fox
The qick brwn fox
This is another sentence
Ths is another sntence
I want to be able to convert this into a form where I assign a group ID and then get the best match (so in this case, it would be 'The quick brown fox' and 'This is another sentence' but assign the group ID of 1 to both the 'The quick brown fox' and 'The qick brwn fox' entries and 2 to the other set).
Is there a better approach for such a problem? Like maybe utilize indexing schemes or other database advantages? Also, just a confirmation, I am not trying to find rows containing similar text, but rather rows that are similar to each other. Perhaps, a good reasoning I can give is that some rows are different due to typo errors and I want to correct them.
EDIT 2: Open to other ways not using MySQL that could be reasonably comparable to a DB's performance
So after a little research and the answer given below, this will not be so easy and I might have to look into fuzzy matching. Are there any good approaches for this considering that my data is now stored in a database?
EDIT 1: Attempt using MySQL's FULLTEXT
mysql> create table fulltextsim(id INT PRIMARY KEY AUTO_INCREMENT, text TEXT, FULLTEXT(text));
Query OK, 0 rows affected (0.44 sec)
mysql> insert into fulltextsim(text) VALUES("The quick brown fox");
Query OK, 1 row affected (0.02 sec)
mysql> insert into fulltextsim(text) VALUES("The qick brwn fox");
Query OK, 1 row affected (0.00 sec)
mysql> insert into fulltextsim(text) VALUES("This is another sentence");
Query OK, 1 row affected (0.00 sec)
mysql> insert into fulltextsim(text) VALUES("Ths is anther sntence");
Query OK, 1 row affected (0.00 sec)
mysql> SELECT * FROM fulltextsim WHERE MATCH(text) AGAINST ('The qick brwn');
+----+-------------------+
| id | text |
+----+-------------------+
| 2 | The qick brwn fox |
+----+-------------------+
1 row in set (0.02 sec)
mysql> SELECT * FROM fulltextsim WHERE MATCH(text) AGAINST ('The qick fox');
+----+-------------------+
| id | text |
+----+-------------------+
| 2 | The qick brwn fox |
+----+-------------------+
1 row in set (0.00 sec)
I wanted the 'The quick brown fox' row as well.
A:
Have you looked at MySQL's FULLTEXT functiality?
UPDATE -- MySQL's FULLTEXT doesn't seem to support fuzzy searching, which is what you are looking for here. Check out MySQL Full Text Search Boolean Mode Partial Match
MySQL does support the SOUNDEX() function, which will match words that sound similar to what is entered, but this does not work for phrases.
So, I think you may be out of luck.
| Trying to group similar text rows in a column of a million row table - Open to Non-MySQL approaches | I have a large number (about 40 million) of VARCHAR entries in a MySQL table. The length of the string can be anywhere between 5-80 characters. I am trying to group similar text together and thought of a possible approach:
Take a row and calculate a similarity measure (like Edit Distance) with every other row and decide (I am not sure how to decide though) whether each belongs to the same group. For instance, I have the following entries:
The quick brown fox
The qick brwn fox
This is another sentence
Ths is another sntence
I want to be able to convert this into a form where I assign a group ID and then get the best match (so in this case, it would be 'The quick brown fox' and 'This is another sentence' but assign the group ID of 1 to both the 'The quick brown fox' and 'The qick brwn fox' entries and 2 to the other set).
Is there a better approach for such a problem? Like maybe utilize indexing schemes or other database advantages? Also, just a confirmation, I am not trying to find rows containing similar text, but rather rows that are similar to each other. Perhaps, a good reasoning I can give is that some rows are different due to typo errors and I want to correct them.
EDIT 2: Open to other ways not using MySQL that could be reasonably comparable to a DB's performance
So after a little research and the answer given below, this will not be so easy and I might have to look into fuzzy matching. Are there any good approaches for this considering that my data is now stored in a database?
EDIT 1: Attempt using MySQL's FULLTEXT
mysql> create table fulltextsim(id INT PRIMARY KEY AUTO_INCREMENT, text TEXT, FULLTEXT(text));
Query OK, 0 rows affected (0.44 sec)
mysql> insert into fulltextsim(text) VALUES("The quick brown fox");
Query OK, 1 row affected (0.02 sec)
mysql> insert into fulltextsim(text) VALUES("The qick brwn fox");
Query OK, 1 row affected (0.00 sec)
mysql> insert into fulltextsim(text) VALUES("This is another sentence");
Query OK, 1 row affected (0.00 sec)
mysql> insert into fulltextsim(text) VALUES("Ths is anther sntence");
Query OK, 1 row affected (0.00 sec)
mysql> SELECT * FROM fulltextsim WHERE MATCH(text) AGAINST ('The qick brwn');
+----+-------------------+
| id | text |
+----+-------------------+
| 2 | The qick brwn fox |
+----+-------------------+
1 row in set (0.02 sec)
mysql> SELECT * FROM fulltextsim WHERE MATCH(text) AGAINST ('The qick fox');
+----+-------------------+
| id | text |
+----+-------------------+
| 2 | The qick brwn fox |
+----+-------------------+
1 row in set (0.00 sec)
I wanted the 'The quick brown fox' row as well.
| [
"Have you looked at MySQL's FULLTEXT functiality?\nUPDATE -- MySQL's FULLTEXT doesn't seem to support fuzzy searching, which is what you are looking for here. Check out MySQL Full Text Search Boolean Mode Partial Match\nMySQL does support the SOUNDEX() function, which will match words that sound similar to what is... | [
1
] | [] | [] | [
"database",
"mysql",
"php",
"python",
"text"
] | stackoverflow_0003730643_database_mysql_php_python_text.txt |
Q:
How can I store testing data for python nosetests?
I want to write some tests for a python MFCC feature extractor for running with nosetest. As well as some lower-level tests, I would also like to be able to store some standard input and expected-output files with the unit tests.
At the moment we are hard-coding the paths to the files on our servers, but I would prefer the testing files (both input and expected-output) to be somewhere in the code repository so they can be kept under source control alongside the testing code.
The problem I am having is that I'm not sure where the best place to put the testing files would be, and how to know what that path is when nosetest calls each testing function. At the moment I am thinking of storing the testing data in the same folder as the tests and using __file__ to work out where that is (would that work?), but I am open to other suggestions.
A:
I think that using __file__ to figure out where the test is located and storing data alongside the it is a good idea. I'm doing the same for some tests that I write.
This:
os.path.dirname(os.path.abspath(__file__))
is probably the best you are going to get, and that's not bad. :-)
A:
Based on the idea of using __file__, maybe you could use a module to help with the path construction. You could find all the files contained in the module directory, gather their name and path in a dictionnary for later use.
Create a module accessible to your tests, i.e. a directory besides your test such as testData, where you can put your data files. In the __init__.py of this module, insert the following code.
import os
from os.path import join,dirname,abspath
testDataFiles = dict()
baseDir = dirname(abspath(__file__)) + os.path.sep
for root, dirs, files in os.walk(baseDir):
localDataFiles = [(join(root.replace(baseDir,""),name), join(root,name)) for name in files]
testDataFiles.update( dict(localDataFiles))
Assuming you called your module testData and it contains a file called data.txt you can then use the following construct in your test to obtain the path to the file. aFileOperation is assumed to be a function that take a parameter path
import unittest
from testData import testDataFiles
class ATestCase(unittest.TestCase):
def test_Something(self):
self.assertEqual( 0, aFileOperation(testDataFiles['data.txt'] )
It will also allow you to use subdirectories such as
def test_SomethingInASubDir(self):
self.assertEqual( 0, aFileOperation(testDataFiles['subdir\\data.txt'] )
| How can I store testing data for python nosetests? | I want to write some tests for a python MFCC feature extractor for running with nosetest. As well as some lower-level tests, I would also like to be able to store some standard input and expected-output files with the unit tests.
At the moment we are hard-coding the paths to the files on our servers, but I would prefer the testing files (both input and expected-output) to be somewhere in the code repository so they can be kept under source control alongside the testing code.
The problem I am having is that I'm not sure where the best place to put the testing files would be, and how to know what that path is when nosetest calls each testing function. At the moment I am thinking of storing the testing data in the same folder as the tests and using __file__ to work out where that is (would that work?), but I am open to other suggestions.
| [
"I think that using __file__ to figure out where the test is located and storing data alongside the it is a good idea. I'm doing the same for some tests that I write.\nThis:\nos.path.dirname(os.path.abspath(__file__))\n\nis probably the best you are going to get, and that's not bad. :-)\n",
"Based on the idea of ... | [
6,
0
] | [] | [] | [
"nosetests",
"python",
"unit_testing"
] | stackoverflow_0003724072_nosetests_python_unit_testing.txt |
Q:
need Advice on ID3 implementation and Datatype to be used
Need advice:
I am implementing ID3 algorithm in Machine Learning. I am using dictionary to read the training file and store into. But as I am going forward I am understanding that in dictionary v dont have fixed places for each key,value pair as in list or array. Now I might have problem in getting the position of the final attribute and passing it dynamically to other functions. Should i change to some other data structure?
A:
Python 2.7 and 3.x have an OrderedDict that could be an option for you.
| need Advice on ID3 implementation and Datatype to be used | Need advice:
I am implementing ID3 algorithm in Machine Learning. I am using dictionary to read the training file and store into. But as I am going forward I am understanding that in dictionary v dont have fixed places for each key,value pair as in list or array. Now I might have problem in getting the position of the final attribute and passing it dynamically to other functions. Should i change to some other data structure?
| [
"Python 2.7 and 3.x have an OrderedDict that could be an option for you.\n"
] | [
2
] | [] | [] | [
"machine_learning",
"python"
] | stackoverflow_0003730118_machine_learning_python.txt |
Q:
Using a loop to generate unique bitmap buttons with separate events when clicked
I'm pretty new to Python, so I'll hope you forgive me for such amateurish code. I've tried pouring over examples that do similar things but I'm having trouble figuring out what they're doing that is different. In examples I've seen each button generated with the loop had a different action, for mine only the last button in the loop is affected by the click, no matter which button I press. Here's the code:
import wx
import mmap
class pt:
Note = open('note.txt', "r+")
buf = mmap.mmap(Note.fileno(), 0)
TL = 0
readline = buf.readline
while readline():
TL += 1
class MainWindow(wx.Frame):
def __init__(self, parent, title):
w, h = wx.GetDisplaySize()
x = w * 0
y = h - bdepth
wx.Frame.__init__(self, parent, title = title, pos = (x, y), size = (200,bdepth), style = wx.STAY_ON_TOP)
self.__DoLayout()
self.Bind(wx.EVT_BUTTON, self.OnClick)
self.Show(True)
def __DoLayout(self):
self.__DoButtons(wx.Panel(self, size=(200,bdepth), pos=(0,0), name='panel'), 'Cheese')
def __DoButtons(self, panel, label):
for i, line in enumerate(pt.Note):
solid = wx.EmptyBitmap(200,50,-1)
dc = wx.MemoryDC()
dc.SelectObject(solid)
solidbrush = wx.Brush(wx.Colour(75,75,75),wx.SOLID)
solidpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetBrush(solidbrush)
dc.SetPen(solidpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawText(line.rstrip(), 30, 17)
dc.SelectObject(wx.NullBitmap)
self.checked = wx.Image('buttonchecked.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
dc = wx.MemoryDC()
dc.SelectObject(self.checked)
dc.SetTextForeground(wx.Colour(200, 255, 0))
dc.DrawText(line.rstrip(), 30, 17)
dc.SelectObject(wx.NullBitmap)
self.b = wx.BitmapButton(panel, i + 800, solid, (0, i * 50), (solid.GetWidth(), solid.GetHeight()), style = wx.NO_BORDER, name=line.rstrip())
def OnClick(self, event):
self.b.SetBitmapDisabled(self.checked)
self.b.Enable(False)
print('cheese')
bdepth = pt.TL * 50
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()enter code here
A:
Only the last button is working because each time you go through the __DoButtons loop you reassign self.b to a different button. So after the loop has finished self.b is only assigned to the last button. You can get the button pressed using the event.GetEventObject() method.
Change your OnClick method to:
def OnClick(self, event):
button = event.GetEventObject()
button.SetBitmapDisabled(self.checked)
button.Enable(False)
print('cheese')
| Using a loop to generate unique bitmap buttons with separate events when clicked | I'm pretty new to Python, so I'll hope you forgive me for such amateurish code. I've tried pouring over examples that do similar things but I'm having trouble figuring out what they're doing that is different. In examples I've seen each button generated with the loop had a different action, for mine only the last button in the loop is affected by the click, no matter which button I press. Here's the code:
import wx
import mmap
class pt:
Note = open('note.txt', "r+")
buf = mmap.mmap(Note.fileno(), 0)
TL = 0
readline = buf.readline
while readline():
TL += 1
class MainWindow(wx.Frame):
def __init__(self, parent, title):
w, h = wx.GetDisplaySize()
x = w * 0
y = h - bdepth
wx.Frame.__init__(self, parent, title = title, pos = (x, y), size = (200,bdepth), style = wx.STAY_ON_TOP)
self.__DoLayout()
self.Bind(wx.EVT_BUTTON, self.OnClick)
self.Show(True)
def __DoLayout(self):
self.__DoButtons(wx.Panel(self, size=(200,bdepth), pos=(0,0), name='panel'), 'Cheese')
def __DoButtons(self, panel, label):
for i, line in enumerate(pt.Note):
solid = wx.EmptyBitmap(200,50,-1)
dc = wx.MemoryDC()
dc.SelectObject(solid)
solidbrush = wx.Brush(wx.Colour(75,75,75),wx.SOLID)
solidpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetBrush(solidbrush)
dc.SetPen(solidpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawText(line.rstrip(), 30, 17)
dc.SelectObject(wx.NullBitmap)
self.checked = wx.Image('buttonchecked.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
dc = wx.MemoryDC()
dc.SelectObject(self.checked)
dc.SetTextForeground(wx.Colour(200, 255, 0))
dc.DrawText(line.rstrip(), 30, 17)
dc.SelectObject(wx.NullBitmap)
self.b = wx.BitmapButton(panel, i + 800, solid, (0, i * 50), (solid.GetWidth(), solid.GetHeight()), style = wx.NO_BORDER, name=line.rstrip())
def OnClick(self, event):
self.b.SetBitmapDisabled(self.checked)
self.b.Enable(False)
print('cheese')
bdepth = pt.TL * 50
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()enter code here
| [
"Only the last button is working because each time you go through the __DoButtons loop you reassign self.b to a different button. So after the loop has finished self.b is only assigned to the last button. You can get the button pressed using the event.GetEventObject() method.\nChange your OnClick method to:\ndef O... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003730448_python_wxpython.txt |
Q:
Equivalent of objects.latest() in App Engine
What would be the best way to get the latest inserted object using AppEngine ?
I know in Django this can be done using
MyObject.objects.latest()
in AppEngine I'd like to be able to do this
class MyObject(db.Model):
time = db.DateTimeProperty(auto_now_add=True)
# Return latest entry from MyObject.
MyObject.all().latest()
Any idea ?
A:
Your best bet will be to implement a latest() classmethod directly on MyObject and call it like
latest = MyObject.latest()
Anything else would require monkeypatching the built-in Query class.
Update
I thought I'd see how ugly it would be to implement this functionality. Here's a mixin class you can use if you really want to be able to call MyObject.all().latest():
class LatestMixin(object):
"""A mixin for db.Model objects that will add a `latest` method to the
`Query` object returned by cls.all(). Requires that the ORDER_FIELD
contain the name of the field by which to order the query to determine the
latest object."""
# What field do we order by?
ORDER_FIELD = None
@classmethod
def all(cls):
# Get the real query
q = super(LatestMixin, cls).all()
# Define our custom latest method
def latest():
if cls.ORDER_FIELD is None:
raise ValueError('ORDER_FIELD must be defined')
return q.order('-' + cls.ORDER_FIELD).get()
# Attach it to the query
q.latest = latest
return q
# How to use it
class Foo(LatestMixin, db.Model):
ORDER_FIELD = 'timestamp'
timestamp = db.DateTimeProperty(auto_now_add=True)
latest = Foo.all().latest()
A:
MyObject.all() returns an instance of the Query class
Order the results by time:
MyObject.all().order('-time')
So, assuming there is at least one entry, you can get the most recent MyObject directly by:
MyObject.all().order('-time')[0]
or
MyObject.all().order('-time').fetch(limit=1)[0]
| Equivalent of objects.latest() in App Engine | What would be the best way to get the latest inserted object using AppEngine ?
I know in Django this can be done using
MyObject.objects.latest()
in AppEngine I'd like to be able to do this
class MyObject(db.Model):
time = db.DateTimeProperty(auto_now_add=True)
# Return latest entry from MyObject.
MyObject.all().latest()
Any idea ?
| [
"Your best bet will be to implement a latest() classmethod directly on MyObject and call it like\nlatest = MyObject.latest()\n\nAnything else would require monkeypatching the built-in Query class.\nUpdate\nI thought I'd see how ugly it would be to implement this functionality. Here's a mixin class you can use if y... | [
5,
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003730810_django_google_app_engine_python.txt |
Q:
How to update $PATH
I am writing a python/pygtk application that is adding some custom scripts (bash) in a certain folder in $HOME (eg. ~/.custom_scripts).
I want to make that folder available in $PATH. So every time the python app is adding the script, that script could be instantly available when the user is opening a terminal (eg. gnome-terminal).
Where do you suggest to "inject" that $PATH dependecy ? .bashrc, /etc/profile.d, etc. ?
What advantages / disadvantages I might encounter ?
For example if i add a script to export the new path in /etc/profile.d, the path is not being updated until I re-login.
Thanks
A:
.profile would be a reasonable place if it's a per-user install; /etc/profile.d for system-wide installs. (You'll need root to do that, of course.)
Your installer won't be able to change the path of the current shell (unless it's being run via source, which would be...odd.)
A:
For scripts that go in the $HOME directory you'd typically use $HOME/bin folder instead which is (usually) on the path.
A:
/etc/profile.d would add it to every user's path
~/.bashrc would just be your own
you can always do "$ source ~/.bashrc" to re-read the config files.
A:
Edit: I misread the original question, so this snippet is only useful for modifying PATH, but not for persisting it...
This can all be done using the os module:
import os
USER_HOME = os.path.expanduser('~')
os.environ['PATH'] += ":" + os.path.join(USER_HOME, '.custom_scripts')
This appends :~/.custom_scripts to the end of the $PATH, since PATH must always be colon-delimited.
A:
~/.bashrc is read every time gnome-terminal is opened, (assuming the user has SHELL set to /bin/bash).
Be sure to check os.environ['PATH'] to see if the directory has already been added, so that the script doesn't add it more than once.
A:
You shouldn't. It's the user choice whether he wants that in the PATH, in what cases and how to achieve that. What you can do is inform the user about the directory where your scripts reside and suggest putting it to the PATH.
Or maybe you're asking from the user's perspective?
| How to update $PATH | I am writing a python/pygtk application that is adding some custom scripts (bash) in a certain folder in $HOME (eg. ~/.custom_scripts).
I want to make that folder available in $PATH. So every time the python app is adding the script, that script could be instantly available when the user is opening a terminal (eg. gnome-terminal).
Where do you suggest to "inject" that $PATH dependecy ? .bashrc, /etc/profile.d, etc. ?
What advantages / disadvantages I might encounter ?
For example if i add a script to export the new path in /etc/profile.d, the path is not being updated until I re-login.
Thanks
| [
".profile would be a reasonable place if it's a per-user install; /etc/profile.d for system-wide installs. (You'll need root to do that, of course.) \nYour installer won't be able to change the path of the current shell (unless it's being run via source, which would be...odd.)\n",
"For scripts that go in the $H... | [
2,
2,
1,
1,
1,
1
] | [
"Why don't you establish the appropriate PATH upon the first call to your module (i.e. in your module's __init__.py):\n# this is your module's __init__.py\nimport sys\neggs = ['/path/to/egg/1.egg', '/path/to/egg/2.egg']\nfor egg in eggs:\n sys.path.append(egg)\n\n"
] | [
-1
] | [
"bash",
"path",
"python",
"scripting"
] | stackoverflow_0003729965_bash_path_python_scripting.txt |
Q:
Send from Twisted client to Twisted server, only this one way
I want to use Twisted to rebuild the communication part of an existing application. This application does send data from the client to the server, only this way round, the server does not send anything.
How do I accomplish this with the event-driven concept of Twisted? I currently use the connectionMade method of Protocol, but I don't think this is the right way.
class Send(Protocol):
def connectionMade(self):
while True:
data = queue.get()
self.transport.write(data + "\n")
self.transport.doWrite()
I'm pretty sure, this is not the way to do that. ;-)
Addition:
My problem is, I cannot imaging what event to use for this. I think the connectionMade event is not the right one, but I will never reach any other event than connectionLost in my case, because the server does not send anything to the client. Should I change this behavior?
A:
No, that is definitely not the right way to do that. Never, ever call doWrite.
The problem here is that I bet queue.get() just blocks until there is some data. If possible, use a non-blocking means of message passing rather than threads. For example, have your thread just callFromThread to your Send protocol to do something.
But, assuming a blocking 'get' call, something like this might work :
from twisted.internet.protocol import Protocol
from twisted.internet.threads import deferToThread
class Send(Protocol):
def connectionMade(self):
self.qget()
def qget(self, data=None):
if data is not None:
self.transport.write(data)
deferToThread(queue.get).addCallback(self.qget)
A:
Here is an another question which uses UDP / Multicast to talk between server and client
UDP client and server with Twisted Python
I would also suggest some additional reading and examples from the twisted documentation it self.
http://krondo.com/?page_id=1327
| Send from Twisted client to Twisted server, only this one way | I want to use Twisted to rebuild the communication part of an existing application. This application does send data from the client to the server, only this way round, the server does not send anything.
How do I accomplish this with the event-driven concept of Twisted? I currently use the connectionMade method of Protocol, but I don't think this is the right way.
class Send(Protocol):
def connectionMade(self):
while True:
data = queue.get()
self.transport.write(data + "\n")
self.transport.doWrite()
I'm pretty sure, this is not the way to do that. ;-)
Addition:
My problem is, I cannot imaging what event to use for this. I think the connectionMade event is not the right one, but I will never reach any other event than connectionLost in my case, because the server does not send anything to the client. Should I change this behavior?
| [
"No, that is definitely not the right way to do that. Never, ever call doWrite.\nThe problem here is that I bet queue.get() just blocks until there is some data. If possible, use a non-blocking means of message passing rather than threads. For example, have your thread just callFromThread to your Send protocol t... | [
2,
1
] | [] | [] | [
"networking",
"python",
"twisted"
] | stackoverflow_0003730951_networking_python_twisted.txt |
Q:
Passing 'None' as function parameter (where parameter is a function)
I am writing a small app that has to perform some 'sanity checks' before entering execution. (eg. of a sanity check: test if a certain path is readable / writable / exists)
The code:
import logging
import os
import shutil
import sys
from paths import PATH
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('sf.core.sanity')
def sanity_access(path, mode):
ret = os.access(path, mode)
logfunc = log.debug if ret else log.warning
loginfo = (os.access.__name__, path, mode, ret)
logfunc('%s(\'%s\', %s)==%s' % loginfo)
return ret
def sanity_check(bool_func, true_func, false_func):
ret = bool_func()
(logfunc, execfunc) = (log.debug, true_func) if ret else \
(log.warning, false_func)
logfunc('exec: %s', execfunc.__name__)
execfunc()
def sanity_checks():
sanity_check(lambda: sanity_access(PATH['userhome'], os.F_OK), \
lambda: None, sys.exit)
My question is related to the sanity_check function.
This function takes 3 parameters (bool_func, true_func, false_func). If the bool_func (which is the test function, returning a boolean value) fails, true_func gets executed, else the false_func gets executed.
1) lambda: None is a little lame , because for example if the sanity_access returns True, lambda: None gets executed, and the output printed will be:
DEBUG:sf.core.sanity:access('/home/nomemory', 0)==True
DEBUG:sf.core.sanity:exec: <lambda>
So it won't be very clear in the logs what function got executed. The log will only contain <lambda> . Is there a default function that does nothing and can be passed as a parameter ? Is it a way to return the name of the first function that is being executed inside a lambda ?
Or a way not to log that "exec" if 'nothing' is sent as a paramter ?
What's the none / do-nothing equivalent for functions ?
sanity_check(lambda: sanity_access(PATH['userhome'], os.F_OK), \
<do nothing, but show something more useful than <lambda>>, sys.exit)
Additional question, why is lambda: pass instead of lambda: None not working ?
A:
update
I would normally delete this post because THC4k saw through all the complexity and rewrote your function correctly. However in a different context, the K combinator trick might come in handy, so I'll leave it up.
There is no builtin that does what you want AFIK. I believe that you want the K combinator (the link came up on another question) which can be encoded as
def K_combinator(x, name):
def f():
return x
f.__name__ = name
return f
none_function = K_combinator(None, 'none_function')
print none_function()
of course if this is just a one off then you could just do
def none_function():
return None
But then you don't get to say "K combinator". Another advantage of the 'K_combinator' approach is that you can pass it to functions, for example,
foo(call_back1, K_combinator(None, 'name_for_logging'))
as for your second statement, only expressions are allowed in lambda. pass is a statement. Hence, lambda: pass fails.
You can slightly simplify your call to sanity check by removing the lambda around the first argument.
def sanity_check(b, true_func, false_func):
if b:
logfunc = log.debug
execfunc = true_func
else:
logfunc = log.warning
execfunc = false_func
logfunc('exec: %s', execfunc.__name__)
execfunc()
def sanity_checks():
sanity_check(sanity_access(PATH['userhome'], os.F_OK),
K_combinator(None, 'none_func'), sys.exit)
This is more readable (largely from expanding the ternary operator into an if). the boolfunc wasn't doing anything because sanity_check wasn't adding any arguments to the call. Might as well just call instead of wrapping it in a lambda.
A:
What's with all the lambdas that serve no purpose? Well, maybe optional arguments will help you a bit:
def sanity_check( test, name='undefined', ontrue=None, onfalse=None ):
if test:
log.debug(name)
if ontrue is not None:
ontrue()
else:
log.warn( name )
if onfalse is not None:
onfalse()
def sanity_checks():
sanity_check(sanity_access(PATH['userhome'], os.F_OK), 'test home',
onfalse=sys.exit)
But you are really overcomplicating things.
A:
You might want to rethink this.
class SanityCheck( object ):
def __call__( self ):
if self.check():
logger.debug(...)
self.ok()
else:
logger.warning(...)
self.not_ok()
def check( self ):
return True
def ok( self ):
pass
def not_ok( self ):
sys.exit(1)
class PathSanityCheck(SanityCheck):
path = "/path/to/resource"
def check( self ):
return os.access( path, os.F_OK )
class AnotherPathSanityCheck(SanityCheck):
path = "/another/path"
def startup():
checks = ( PathSanityCheck(), AnotherPathSanityCheck() )
for c in checks:
c()
Callable objects can simplify your life.
A:
>>> import dis
>>> f = lambda: None
>>> dis.dis(f)
1 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
>>> g = lambda: Pass
>>>
>>>
>>> dis.dis(g)
1 0 LOAD_GLOBAL 0 (Pass)
3 RETURN_VALUE
>>> g = lambda: pass
File "<stdin>", line 1
g = lambda: pass
^
SyntaxError: invalid syntax
A:
Actually, what you want is a function which does nothing, but has a __name__ which is useful to the log. The lambda function is doing exactly what you want, but execfunc.__name__ is giving "<lambda>". Try one of these:
def nothing_func():
return
def ThisAppearsInTheLog():
return
You can also put your own attributes on functions:
def log_nothing():
return
log_nothing.log_info = "nothing interesting"
Then change execfunc.__name__ to getattr(execfunc,'log_info', '')
| Passing 'None' as function parameter (where parameter is a function) | I am writing a small app that has to perform some 'sanity checks' before entering execution. (eg. of a sanity check: test if a certain path is readable / writable / exists)
The code:
import logging
import os
import shutil
import sys
from paths import PATH
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('sf.core.sanity')
def sanity_access(path, mode):
ret = os.access(path, mode)
logfunc = log.debug if ret else log.warning
loginfo = (os.access.__name__, path, mode, ret)
logfunc('%s(\'%s\', %s)==%s' % loginfo)
return ret
def sanity_check(bool_func, true_func, false_func):
ret = bool_func()
(logfunc, execfunc) = (log.debug, true_func) if ret else \
(log.warning, false_func)
logfunc('exec: %s', execfunc.__name__)
execfunc()
def sanity_checks():
sanity_check(lambda: sanity_access(PATH['userhome'], os.F_OK), \
lambda: None, sys.exit)
My question is related to the sanity_check function.
This function takes 3 parameters (bool_func, true_func, false_func). If the bool_func (which is the test function, returning a boolean value) fails, true_func gets executed, else the false_func gets executed.
1) lambda: None is a little lame , because for example if the sanity_access returns True, lambda: None gets executed, and the output printed will be:
DEBUG:sf.core.sanity:access('/home/nomemory', 0)==True
DEBUG:sf.core.sanity:exec: <lambda>
So it won't be very clear in the logs what function got executed. The log will only contain <lambda> . Is there a default function that does nothing and can be passed as a parameter ? Is it a way to return the name of the first function that is being executed inside a lambda ?
Or a way not to log that "exec" if 'nothing' is sent as a paramter ?
What's the none / do-nothing equivalent for functions ?
sanity_check(lambda: sanity_access(PATH['userhome'], os.F_OK), \
<do nothing, but show something more useful than <lambda>>, sys.exit)
Additional question, why is lambda: pass instead of lambda: None not working ?
| [
"update\nI would normally delete this post because THC4k saw through all the complexity and rewrote your function correctly. However in a different context, the K combinator trick might come in handy, so I'll leave it up.\n\nThere is no builtin that does what you want AFIK. I believe that you want the K combinator ... | [
8,
8,
3,
1,
1
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0003730831_lambda_python.txt |
Q:
Python: binascii.a2b_hex gives "Odd-length string"
I have a hex value that I'm grabbing from a text file, then I'm passing it to a2b_hex to convert it to the proper binary representation. Here is what I have:
k = open('./' + basefile + '.key', 'r')
k1 = k.read()
k.close()
my_key = binascii.a2b_hex(k1)
When I print k1, it is as expected: 81e3d6df
Here is the error message:
Traceback (most recent call last):
File "xor.py", line 26, in <module>
my_key = binascii.a2b_hex(k1)
TypeError: Odd-length string
Any suggestions? Thanks!
A:
Are you sure the file doesn't have something extra in it? Whitespace, for instance?
Try k1.strip()
A:
I suspect there is a trailing newline at the end of the file. Strip the string before passing it to binascii.
Note there's now also a simpler spelling: k1.strip().decode('hex').
A:
I'm more interested what happens if you execute the following code:
with open("./" + basefile + ".key") as key_file:
key = key_file.read()
print len(key), key
Care to tell? There is probably some extra character you just don't see when printing. In these cases, make sure to print the length of the string.
A:
read() doesn't strip newlines. If there's a '\n' at the end of your file, it'll be in k1.
Try binascii.a2b_hex(k1.strip()) or possibly binascii.a2b_hex(k1[:8]).
| Python: binascii.a2b_hex gives "Odd-length string" | I have a hex value that I'm grabbing from a text file, then I'm passing it to a2b_hex to convert it to the proper binary representation. Here is what I have:
k = open('./' + basefile + '.key', 'r')
k1 = k.read()
k.close()
my_key = binascii.a2b_hex(k1)
When I print k1, it is as expected: 81e3d6df
Here is the error message:
Traceback (most recent call last):
File "xor.py", line 26, in <module>
my_key = binascii.a2b_hex(k1)
TypeError: Odd-length string
Any suggestions? Thanks!
| [
"Are you sure the file doesn't have something extra in it? Whitespace, for instance?\nTry k1.strip()\n",
"I suspect there is a trailing newline at the end of the file. Strip the string before passing it to binascii.\nNote there's now also a simpler spelling: k1.strip().decode('hex').\n",
"I'm more interested wh... | [
8,
6,
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0003731278_python.txt |
Q:
Python runs a if-case that it should not!
I have this code:
def random_answerlist(self):
self.li = []
self.winning_button = random.randint(0, 3)
i = 0
while i < 20 and len(self.li) is not 4:
if i == self.winning_button:
self.li.append(self.flags[self.current_flag][0])
else:
new_value = self.random_value()
if self.flags[new_value][0] not in self.li:
self.li.append(self.flags[new_value][0])
i += 1
return self.li
The only problem with it is that the first if-case may happen several times which should be impossible. I have searched for a good explanation to this and I can't find any.
Oh, I know the code isn't the best. But I'm kind of new to python (just a month or so) and thought this might work, but it didn't!
Do you guys know why? =)
A:
One glaring problem is the usage of is not for a value comparision against len(self.li). The tests is not and != are not the same. is tests for identity (are these references to the same object?), != tests for equality (do these objects have the same value?).
Change your while to:
while i < 20 and len(self.li) != 4:
Does that address the issue?
A:
Yes, sorry.
I were out smoking when I realized I were the one failing:
The problem is not the if-case as you guys stated. The problem is that the else case generates randomly from the same list as the first if-case does. And then the same value is getting into the list sometimes as the one in the first if-case.
You couldn't solve it since I didn't post the whole code.
Well thanks anyway :)
| Python runs a if-case that it should not! | I have this code:
def random_answerlist(self):
self.li = []
self.winning_button = random.randint(0, 3)
i = 0
while i < 20 and len(self.li) is not 4:
if i == self.winning_button:
self.li.append(self.flags[self.current_flag][0])
else:
new_value = self.random_value()
if self.flags[new_value][0] not in self.li:
self.li.append(self.flags[new_value][0])
i += 1
return self.li
The only problem with it is that the first if-case may happen several times which should be impossible. I have searched for a good explanation to this and I can't find any.
Oh, I know the code isn't the best. But I'm kind of new to python (just a month or so) and thought this might work, but it didn't!
Do you guys know why? =)
| [
"One glaring problem is the usage of is not for a value comparision against len(self.li). The tests is not and != are not the same. is tests for identity (are these references to the same object?), != tests for equality (do these objects have the same value?).\nChange your while to:\nwhile i < 20 and len(self.li) !... | [
1,
0
] | [] | [] | [
"case",
"if_statement",
"loops",
"python",
"while_loop"
] | stackoverflow_0003731228_case_if_statement_loops_python_while_loop.txt |
Q:
How do I create a url pattern like controller/action/id in django?
I'm trying to create a url pattern that will behave like controller/action/id route in rails. So far here is what I have :
from django.conf.urls.defaults import *
import views
urlpatterns = ('',
(r'^(?P<app>\w+)/(?P<view>\w+)/$', views.select_view),
)
Here is my 'views.py':
def select_view(request, app, view):
return globals()['%s.%s', % (app, view,)]()
So far this hasn't worked. I get a key error exception in the 'globals' function. Am I going in the right direction here?
A:
Try something like this:
from django.utils.importlib import import_module
def select_view(request, app, view):
mod = import_module('%s.views' % app)
return getattr(mod, view)(request)
It is obviously oversimplified example, what you do is import views.py from your app and see if it has view function, and if it does execute that function giving request as the first argument.
See some examples of how Django does it with get_callable and autodiscover methods.
| How do I create a url pattern like controller/action/id in django? | I'm trying to create a url pattern that will behave like controller/action/id route in rails. So far here is what I have :
from django.conf.urls.defaults import *
import views
urlpatterns = ('',
(r'^(?P<app>\w+)/(?P<view>\w+)/$', views.select_view),
)
Here is my 'views.py':
def select_view(request, app, view):
return globals()['%s.%s', % (app, view,)]()
So far this hasn't worked. I get a key error exception in the 'globals' function. Am I going in the right direction here?
| [
"Try something like this:\nfrom django.utils.importlib import import_module\n\ndef select_view(request, app, view):\n mod = import_module('%s.views' % app)\n return getattr(mod, view)(request)\n\nIt is obviously oversimplified example, what you do is import views.py from your app and see if it has view functi... | [
1
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0003731132_django_django_urls_python.txt |
Q:
how to replace the characters in strings with '#'s by using regex in Python
How can I replace the contents of strings with #'s in Python? Assume no comments, no multiple lines for one string. Like if there is a line in a python file:
print 'Hello' + "her mom's shirt".
This will be translated into:
print '#####' + "###############".
It's like a filter to deal with every line in a python file.
A:
If you're using Python and the thing you're parsing is Python there's no need to use regexp since there's a built-in parser.
A:
>>> import re
>>> s="The Strings"
>>> s=re.sub("\w","#",s)
>>> s
'### #######'
>>> s='Hello' + "her mom's shirt"
>>> s
"Helloher mom's shirt"
>>> re.sub("\w","#",s)
"######## ###'# #####"
----Edit
OK, Now I understand that you want the output to be from a Python file. Try:
import fileinput
import re
for line in fileinput.input():
iter = re.finditer(r'(\'[^\']+\'|"[^"]+")',line)
for m in iter:
span = m.span()
paren = m.group()[0]
line = line[:span[0]]+paren+'#'*(span[1]-span[0]-2)+paren+line[span[1]:]
print line.rstrip()
This does not deal with line breaks, the """ form, and is only tested again 1 or two files I have...
In general, it is better to use a parser for this kind of job.
Best
A:
Don't need a regex to replace "I'm superman" with "############"
Try
input = "I'm superman"
print "#" * len(input)
| how to replace the characters in strings with '#'s by using regex in Python | How can I replace the contents of strings with #'s in Python? Assume no comments, no multiple lines for one string. Like if there is a line in a python file:
print 'Hello' + "her mom's shirt".
This will be translated into:
print '#####' + "###############".
It's like a filter to deal with every line in a python file.
| [
"If you're using Python and the thing you're parsing is Python there's no need to use regexp since there's a built-in parser.\n",
">>> import re\n>>> s=\"The Strings\"\n>>> s=re.sub(\"\\w\",\"#\",s)\n>>> s\n'### #######'\n>>> s='Hello' + \"her mom's shirt\"\n>>> s\n\"Helloher mom's shirt\"\n>>> re.sub(\"\\w\",\"#... | [
5,
2,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003731341_python_regex_string.txt |
Q:
Conditional Class Creation (Python)
From the tutorial: "A class definition is an executable statement."
Is the following recommended in a script?
my_switch = False
if my_switch:
class Hello:
def __init__(self):
self.greeting = "Hello!"
else:
class Hello:
def __init__(self):
self.greeting = "Salut!"
A:
You can even do
class Hello:
def __init__(self):
self.greeting = "Hello!"
class Salut:
def __init__(self):
self.greeting = "Salut!"
if my_switch:
Hello = Salut
(note that your code needs lower-case Class keywords...)
A:
If you like it better, you could put each class definition in a separate .py file and just import the one you want. Something like the following:
if my_switch:
from hello_en import Hello
else:
from hello_fr import Hello
h = Hello()
A:
Yes, the code is valid. but why not just run the code to find out?
You can also do this with function definitions.
A:
You can also put conditions around the "declarations" inside the class, since those are executed as part of the class construction:
class Hello:
if my_switch:
igreeting = "Hello!"
else:
igreeting = "Salut!"
def __init__(self, greeting):
self.greeting = self.igreeting
(igreeting here is a class variable, greeting a member variable)
or just plain
class Hello:
if my_switch:
greeting = "Hello!"
else:
greeting = "Salut!"
... will usually give the same effect.
A:
It's certainly not recommended for localization, as in your example.
The main thing to consider is how much of the code is going to be similar versus different in the specialized versions of the class. If only a small amount of code is different, or if only data is different ("Hello" vs "Salut"), there are better ways.
One case where I might consider conditional declaration of classes is if I'm providing functionality on two different OSes, and getting that functionality is very different between the two. As an example, maybe I'm trying to drive iTunes from a script, and on MacOS I'm using AppleScript to drive it, but on Windows I have to use COM. I might create a wrapper class that the rest of my code could use without caring about which OS was in use.
A:
It is valid code but not really recommended in that format (assuming that code would follow the class declaration). Since you will eventually use the class. Assuming that you still use two classes named the same, it might be confusing afterward. Maybe you should have the code wrapped in a function to return the class that you have created. Now you have a basic factory.
def HelloFactory(my_switch)
if my_switch:
class Hello:
def __init__(self):
self.greeting = "Hello!"
else:
class Hello:
def __init__(self):
self.greeting = "Salut!"
return Hello
helloClass = HelloFactory(False)
hello = helloClass()
hello.greeting
Would output "Salut!"
A:
You may not need to repeat the code as you do. Ask yourself if you need to repeat the class construction code, or just variables within the class itself? If it's the latter, then you could use the same class for both cases using an argument in __init__(), and then conditionally return an instance of the class with the desired variable:
my_switch = False
class Hello:
def __init__(self, greeting):
self.greeting = greeting
if my_switch:
mygreeting = "Hello!"
else:
mygreeting = "Salut!"
hello = Hello(mygreeting)
print hello.greeting
# => Salut!
| Conditional Class Creation (Python) | From the tutorial: "A class definition is an executable statement."
Is the following recommended in a script?
my_switch = False
if my_switch:
class Hello:
def __init__(self):
self.greeting = "Hello!"
else:
class Hello:
def __init__(self):
self.greeting = "Salut!"
| [
"You can even do\nclass Hello:\n def __init__(self):\n self.greeting = \"Hello!\"\n\nclass Salut:\n def __init__(self):\n self.greeting = \"Salut!\"\n\nif my_switch:\n Hello = Salut\n\n(note that your code needs lower-case Class keywords...)\n",
"If you like it better, you could put each cl... | [
11,
6,
5,
5,
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003729419_python.txt |
Q:
How do I divide the members of a list by the corresponding members of another list in Python?
Let's say I have two data sets. I have a week-by-week tally of users who tried my service.
trials = [2,2,2,8,8,4]
And I have a week by week tally of trial users who signed up.
conversions = [1,0,2,4,8,3]
I can do it pretty quickly this way:
conversion_rate = []
for n in range(len(trials)):
conversion_rate.append(conversions[n]/trials[n])
Can you think of a more elegant way?
Bonus: The result of this is a list of ints [0, 0, 1, 0, 1, 0]
, not a list of floats. What's the easiest way to get a list of floats?
A:
Use zip:
[c/t for c,t in zip(conversions, trials)]
The most elegant way to get floats is to upgrade to Python 3.x.
If you need to use Python 2.x then you could write this:
>>> [float(c)/t for c,t in zip(conversions, trials)]
[0.5, 0.0, 1.0, 0.5, 1.0, 0.75]
Alternatively you could add this at the start of your file:
from __future__ import division
But note that this will affect the behaviour of division everywhere in your program, so you need to check carefully to see if there are any places where you want integer division and if so write // instead of /.
A:
How about
trials = [2,2,2,8,8,4]
conversions = [1,0,2,4,8,3]
conversion_rate = [conversion / trials[n] for n, conversion in enumerate(conversions)]
A:
Without using zip and float:
[1.0*conversions[n]/trials[n] for n in xrange(len(trials))]
A:
If you happen to be using numpy, you can use the following ideas:
import numpy as np
conversion_rate = np.divide(trials, conversions)
or, using broadcasting:
import numpy as np
trials = np.array([2, 2, 2, 8, 8, 4])
conversions = np.array([1, 0, 2, 4, 8, 3])
conversion_rate = 1.0 * trials / conversions
| How do I divide the members of a list by the corresponding members of another list in Python? | Let's say I have two data sets. I have a week-by-week tally of users who tried my service.
trials = [2,2,2,8,8,4]
And I have a week by week tally of trial users who signed up.
conversions = [1,0,2,4,8,3]
I can do it pretty quickly this way:
conversion_rate = []
for n in range(len(trials)):
conversion_rate.append(conversions[n]/trials[n])
Can you think of a more elegant way?
Bonus: The result of this is a list of ints [0, 0, 1, 0, 1, 0]
, not a list of floats. What's the easiest way to get a list of floats?
| [
"Use zip:\n[c/t for c,t in zip(conversions, trials)]\n\nThe most elegant way to get floats is to upgrade to Python 3.x.\nIf you need to use Python 2.x then you could write this:\n>>> [float(c)/t for c,t in zip(conversions, trials)]\n[0.5, 0.0, 1.0, 0.5, 1.0, 0.75]\n\nAlternatively you could add this at the start of... | [
15,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003731426_python.txt |
Q:
Getting Started with PyQt
I'm testing out some of the examples in Rapid GUI Programming with Python and Qt, but running into a stumbling block here or where. When I copied to following exercise (verbatim, from the book):
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = QApplication(sys.argv)
try:
due = QTime.currentTime()
message = "Alert!"
if len(sys.argv) < 2:
raise ValueError
hours, mins = sys.argv[1].split(":")
due = QTime(int(hours), int(mins))
if not due.isValid():
raise ValueError
if len(sys.argv) > 2:
message = " ".join(sys.argv[2:])
except ValueError:
message = "Usage: alert.pyw HH:MM [optional message*]" # 24hr Clock
while QTime.currentTime() < due:
time.sleep(20) # 20 seconds
label = QLabel("<font color=red size=72><b>" + message + "</b></font>")
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000, app.quit) # 1 minute
app.exec_()
I get the following error:
andy@ASUSix:~/Documents/Programming/Python/PyQt$ from: can't read /var/mail/PyQt4.QtCore
from: can't read /var/mail/PyQt4.QtGui
./alert.pyw: line 6: syntax error near unexpected token `('
./alert.pyw: line 6: `app = QApplication(sys.argv)
What's going wrong here? Is my PATH set up incorrectly?
A:
You probably forgot to add a shebang to your script, to tell your shell to actually run it with the Python interpreter. Try adding
#!/usr/bin/python
as the first line in your script, provided that's where your Python interpreter is installed. You might want to try
which python
in case you're not sure.
| Getting Started with PyQt | I'm testing out some of the examples in Rapid GUI Programming with Python and Qt, but running into a stumbling block here or where. When I copied to following exercise (verbatim, from the book):
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = QApplication(sys.argv)
try:
due = QTime.currentTime()
message = "Alert!"
if len(sys.argv) < 2:
raise ValueError
hours, mins = sys.argv[1].split(":")
due = QTime(int(hours), int(mins))
if not due.isValid():
raise ValueError
if len(sys.argv) > 2:
message = " ".join(sys.argv[2:])
except ValueError:
message = "Usage: alert.pyw HH:MM [optional message*]" # 24hr Clock
while QTime.currentTime() < due:
time.sleep(20) # 20 seconds
label = QLabel("<font color=red size=72><b>" + message + "</b></font>")
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000, app.quit) # 1 minute
app.exec_()
I get the following error:
andy@ASUSix:~/Documents/Programming/Python/PyQt$ from: can't read /var/mail/PyQt4.QtCore
from: can't read /var/mail/PyQt4.QtGui
./alert.pyw: line 6: syntax error near unexpected token `('
./alert.pyw: line 6: `app = QApplication(sys.argv)
What's going wrong here? Is my PATH set up incorrectly?
| [
"You probably forgot to add a shebang to your script, to tell your shell to actually run it with the Python interpreter. Try adding\n#!/usr/bin/python\n\nas the first line in your script, provided that's where your Python interpreter is installed. You might want to try\nwhich python\n\nin case you're not sure.\n"
] | [
8
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0003731558_pyqt_python_qt.txt |
Q:
beep sound in python audiolab
How do i generate a gentle "beep" sound in python audiolab, without the use of external .wav files? I found the following example to generate random noise:
play(0.05 * np.random.randn(2, 48000))
Unfortunately i do not have enough knowledge of audio representations to create a beep (of a certain frequency) and i have no idea where to find some understandable documentation.
Any help on this would really be appreciated!
A:
To be precise:
import audiolab
import scipy
x = scipy.cos((2*scipy.pi*f/fs)*scipy.arange(fs*T))
audiolab.play(x, fs)
where f is the frequency of the tone in Hertz, fs is the sampling rate, and T is the length of the tone in seconds.
A:
I figured it out:
play(0.05 * np.array([math.cos(x/40) for x in range(10000)]))
generates a pretty nice tone, in wich the values:
0.05 defines the volume;
40 the frequency;
10000 the length of the tone.
Ciau!
| beep sound in python audiolab | How do i generate a gentle "beep" sound in python audiolab, without the use of external .wav files? I found the following example to generate random noise:
play(0.05 * np.random.randn(2, 48000))
Unfortunately i do not have enough knowledge of audio representations to create a beep (of a certain frequency) and i have no idea where to find some understandable documentation.
Any help on this would really be appreciated!
| [
"To be precise:\nimport audiolab\nimport scipy\nx = scipy.cos((2*scipy.pi*f/fs)*scipy.arange(fs*T))\naudiolab.play(x, fs)\n\nwhere f is the frequency of the tone in Hertz, fs is the sampling rate, and T is the length of the tone in seconds.\n",
"I figured it out:\nplay(0.05 * np.array([math.cos(x/40) for x in ran... | [
3,
0
] | [] | [] | [
"audio",
"numpy",
"python"
] | stackoverflow_0003725173_audio_numpy_python.txt |
Q:
Python import problem with Django management commands
For whatever reason, when I was new to Python and Django, I wrote some import statements like this at the top of a models.py file:
from django.contrib import auth
And I'd use it like this:
class MyModel(models.Model):
user = models.ForeignKey(auth.models.User)
# ...
This worked fine. A long time later, I wrote a custom management command, and it would do this:
from myapp.models import MyModel
When I ran my custom command (python manage.py my_command) this would result in Python complaining that the module auth had no attribute models on the line declaring the ForeignKey in models.py.
To work around this problem, I changed my models.py to the more usual:
from django.contrib.auth.models import User
class MyModel(models.Model):
user = models.ForeignKey(User)
# ...
Can someone explain to me what I am missing? Is there something different in the environment when you run a management command? Or was I just doing it wrong the whole time? Thanks!
Edit: Following dmitko's hunch about circular imports, here are the imports used in my models.py file. I'm showing the original import of auth commented out, along with the only model that has a foreign key to the auth user model:
import datetime
from django.db import models
# from django.contrib import auth
from django.contrib.auth.models import User
class UserLastVisit(models.Model):
# user = models.ForeignKey(auth.models.User, unique=True)
# ^^^^^^^^^^^^^^^^
# after adding mgmt command, error occurred here; change to the line below
user = models.ForeignKey(User, unique=True)
last_visit = models.DateTimeField(db_index=True)
And here are the imports of the management command that uncovered the problem:
import datetime
from django.core.management.base import NoArgsCommand
from core.models import UserLastVisit, AnonLastVisit, Statistic
Was this setting up a circular import type situation?
A:
If some random module ever imports module x.y.z, then a later person who imports just x.y will see a z in the x.y namespace.
The reason this happens is that import x.y.z is actually three import statements in one. It works something like this:
x = __internal_import('x')
x.y = __internal_import('x/y')
x.y.z = __internal_import('x/y/z')
Next time someone does __internal_import('x/y'), they'll get the same object, because python is smart enough not to import the same one twice. That object already has its z member assigned to the z module.
In your full app, probably you had a module that did import django.contrib.auth.models. But your minimal standalone program didn't import that module, so the name was never assigned.
(Note: there's no such thing as __internal_import. It's just an illustration. The real function has some other name that you would have to look up.)
A:
I guess that if you do from django.contrib import auth that means you're importing auth package as a module and what it exports is driven by __init__.py in the auth folder:
>>> from django.contrib import auth
>>> dir(auth)
['BACKEND_SESSION_KEY', 'ImproperlyConfigured', 'REDIRECT_FIELD_NAME', 'SESSION_
KEY', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'authentica
te', 'datetime', 'get_backends', 'get_user', 'import_module', 'load_backend', 'l
ogin', 'logout']
You can check __init__.py in django\contrib\auth and see the same function list. When you import from django.contrib.auth.models import User that means that you're importing a submodule from the auth package and it works.
BTW. I was unable to use auth.models.User in any case - whether I run from console or from my django app.
A:
It's hard to say exactly what's going on without seeing the new manage.py command that you added. However, I often see the " has no attribute " in cases with circular imports, and it's almost always fixed by changing the module-level imports to function- or class-level imports, as you did here. You might check if anything like that is going on here.
| Python import problem with Django management commands | For whatever reason, when I was new to Python and Django, I wrote some import statements like this at the top of a models.py file:
from django.contrib import auth
And I'd use it like this:
class MyModel(models.Model):
user = models.ForeignKey(auth.models.User)
# ...
This worked fine. A long time later, I wrote a custom management command, and it would do this:
from myapp.models import MyModel
When I ran my custom command (python manage.py my_command) this would result in Python complaining that the module auth had no attribute models on the line declaring the ForeignKey in models.py.
To work around this problem, I changed my models.py to the more usual:
from django.contrib.auth.models import User
class MyModel(models.Model):
user = models.ForeignKey(User)
# ...
Can someone explain to me what I am missing? Is there something different in the environment when you run a management command? Or was I just doing it wrong the whole time? Thanks!
Edit: Following dmitko's hunch about circular imports, here are the imports used in my models.py file. I'm showing the original import of auth commented out, along with the only model that has a foreign key to the auth user model:
import datetime
from django.db import models
# from django.contrib import auth
from django.contrib.auth.models import User
class UserLastVisit(models.Model):
# user = models.ForeignKey(auth.models.User, unique=True)
# ^^^^^^^^^^^^^^^^
# after adding mgmt command, error occurred here; change to the line below
user = models.ForeignKey(User, unique=True)
last_visit = models.DateTimeField(db_index=True)
And here are the imports of the management command that uncovered the problem:
import datetime
from django.core.management.base import NoArgsCommand
from core.models import UserLastVisit, AnonLastVisit, Statistic
Was this setting up a circular import type situation?
| [
"If some random module ever imports module x.y.z, then a later person who imports just x.y will see a z in the x.y namespace.\nThe reason this happens is that import x.y.z is actually three import statements in one. It works something like this:\nx = __internal_import('x')\nx.y = __internal_import('x/y')\nx.y.z = ... | [
5,
0,
0
] | [] | [] | [
"django",
"import",
"python"
] | stackoverflow_0003711869_django_import_python.txt |
Q:
Is there a ready-to-use form to display lists of objects in the django forms api?
Is there a form(or any other solution) that allows me to quickly build forms that display lists of models(with filtering, ordering etc) like the django admin site does?
A:
Short answer: Yes.
Long answer: Yes, but the filtering, ordering, etc. are left up to you to come up with. In Django "generic view" really does mean generic.
| Is there a ready-to-use form to display lists of objects in the django forms api? | Is there a form(or any other solution) that allows me to quickly build forms that display lists of models(with filtering, ordering etc) like the django admin site does?
| [
"Short answer: Yes. \nLong answer: Yes, but the filtering, ordering, etc. are left up to you to come up with. In Django \"generic view\" really does mean generic.\n"
] | [
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0003731808_django_django_admin_django_models_python.txt |
Q:
Reading a file in Python while logging data in screen
Background
To capture data from a logic controller, I'm using screen as a terminal emulator and connecting my MacBook via the KeySpan USA-19HS USB Serial Adapter. I've created the following bash script, so that I can type talk2controller <filename> where filename is the name of the data file.
#!/bin/bash
if [ -z "$1" ]; then
echo Please provide the filename to save the logfile
exit
fi
LOGFILE=$1
echo "logfile $1" > screenrc # Set the logfile filename
echo "logfile flush 1" >> screenrc # Wait 1 sec before flushing buffer to filesystem
screen -L -c screenrc /dev/tty.KeySerial1 19200
I've changed the filename for the logfile and changed from the default of 10 seconds to 1 second for waiting before flushing the logfile buffer to the filesystem. I save those commands to screenrc. Then I call screen with:
-L — logging enabled
-c screenrc — override the default configuration file
/dev/tty.KeySerial1 19200 — talk to the serial port using a baud rate of 19200
Each test that I log takes about 3–6 minutes and contains speed, acceleration, and position information. I'll know that the test was valid based on the acceleration rate. Currently, I'm waiting until after the test to then run a Python matplotlib script to plot the speed, acceleration, and position to see if the test was valid before moving on to the next test.
To save time, I would prefer to plot the data about halfway through the test, while data is still being captured.
Questions
In my mind there are two options to plotting the data while more data is still being captured:
Option 1: Use screen to log the data and have the Python matplotlib script read the partial logfile.
Question 1: What concerns are there if the Python script reads the logfile, while screen is still writing data to it?
Option 2: Switch from using screen to using pySerial. However, plotting the data during the test is a lower priority than simply capturing the data during the test. I can't afford for an exception in the plotting portion of the code to cause the data logging to fail. That's what's great about screen—it just dumps the data and doesn't try to do anything else.
Question 2: If I were to switch to pySerial, could I run two threads to reduce the chance that the plotting portion of the code doesn't impact the data capture code? Does this buy me anything?
Question 3: Is there a better option that I haven't thought of?
A:
Both option 1 and 2 will work, but oh boy, in the name of all things good, avoid using threads for this! You'll end up with the worst of both worlds: locking problems, and an exception in the graphing thread will kill the whole program (including the logging thread) anyway. As someone else mentioned, using two separate processes for this is fine. screen is a bit of an odd choice of tools for this purpose, as is writing code by hand in python. I'd just rewrite the talk2controller script as this trivial one:
stty -F /dev/tty.KeySerial1 19200 raw
cat </dev/tty.KeySerial1 >logfile
(You could also use >>logfile if you want each run of the script to append to the file, rather than rewriting it from scratch.)
The other question is about whether it's okay to have a program reading from the file as long as someone else is writing to it. A more specific version of this question is: what if a line of the log is half-written at the time you try to read it?
The answer is: you're allowed to do this, but you're right, you can't guarantee that a line won't be half-written at the time you read it. (If you write your own replacement for cat or screen you could actually make this guarantee by always writing to the file using os.read() instead of sys.stdout.write() or print.)
However, that guarantee isn't needed anyway. You only need to be careful when reading the file and you'll never have a problem. Essentially, an incomplete line is just one that doesn't end with a \n newline character. Thus:
for line in open('logfile'):
if not line.endswith('\n'): break
...handle valid line...
Since the \n character is the last thing written by each line of the log, you know for sure that if you read a \n character, everything before it was written correctly.
A:
I think Option 1 is totally feasible because you can easily have Python "tail" the logfile in a read-only pipe so that no harm is done to it while screen is still writing to it. While tailing the file, you can perform a specified action any time a new log event is detected in the log file.
If you are curious and would like to see some working code, a personal project of mine utilizes this functionality. The project is called thrasher-logdrop and the guts are logdrop.py. The basic flow is:
Tail a file with do_tail()
Watch for log events with tail_lines()
Perform an action on events with handle_line()
A:
I'd say option 2 is the way to go. You have complete control over what you do with each byte of input, as you receive it. You can have a very simple Python script which simply writes the data to disk as it reads it. Your plotting code can run in an entirely separate process created by fork()ing the first. To get the data from one to the other, you can either (a) have the first process also write to a socketpair() or other IPC mechanism; or (b) configure the output file object to be line-buffered -- causing it to explicitly sync after every full line is written -- and monitor it for new content in the second process.
The problem with option 1 is that you have no control over screen's buffering behavior. You can monitor its logfile for new content, but your logging code needs to be prepared to handle both incomplete lines and large chunks of data all at once. Depending on the exact buffering behavior, you might not even see any data at all until the screen process exits!
| Reading a file in Python while logging data in screen | Background
To capture data from a logic controller, I'm using screen as a terminal emulator and connecting my MacBook via the KeySpan USA-19HS USB Serial Adapter. I've created the following bash script, so that I can type talk2controller <filename> where filename is the name of the data file.
#!/bin/bash
if [ -z "$1" ]; then
echo Please provide the filename to save the logfile
exit
fi
LOGFILE=$1
echo "logfile $1" > screenrc # Set the logfile filename
echo "logfile flush 1" >> screenrc # Wait 1 sec before flushing buffer to filesystem
screen -L -c screenrc /dev/tty.KeySerial1 19200
I've changed the filename for the logfile and changed from the default of 10 seconds to 1 second for waiting before flushing the logfile buffer to the filesystem. I save those commands to screenrc. Then I call screen with:
-L — logging enabled
-c screenrc — override the default configuration file
/dev/tty.KeySerial1 19200 — talk to the serial port using a baud rate of 19200
Each test that I log takes about 3–6 minutes and contains speed, acceleration, and position information. I'll know that the test was valid based on the acceleration rate. Currently, I'm waiting until after the test to then run a Python matplotlib script to plot the speed, acceleration, and position to see if the test was valid before moving on to the next test.
To save time, I would prefer to plot the data about halfway through the test, while data is still being captured.
Questions
In my mind there are two options to plotting the data while more data is still being captured:
Option 1: Use screen to log the data and have the Python matplotlib script read the partial logfile.
Question 1: What concerns are there if the Python script reads the logfile, while screen is still writing data to it?
Option 2: Switch from using screen to using pySerial. However, plotting the data during the test is a lower priority than simply capturing the data during the test. I can't afford for an exception in the plotting portion of the code to cause the data logging to fail. That's what's great about screen—it just dumps the data and doesn't try to do anything else.
Question 2: If I were to switch to pySerial, could I run two threads to reduce the chance that the plotting portion of the code doesn't impact the data capture code? Does this buy me anything?
Question 3: Is there a better option that I haven't thought of?
| [
"Both option 1 and 2 will work, but oh boy, in the name of all things good, avoid using threads for this! You'll end up with the worst of both worlds: locking problems, and an exception in the graphing thread will kill the whole program (including the logging thread) anyway. As someone else mentioned, using two s... | [
3,
1,
1
] | [] | [] | [
"gnu_screen",
"logging",
"matplotlib",
"python"
] | stackoverflow_0003709698_gnu_screen_logging_matplotlib_python.txt |
Q:
Qt4: Write a function that creates a dialog and returns the choice of the user
Not sure if this has a straightforward solution, but I want to write a function that shows a dialog (defined elsewhere in a class that inherits QDialog) and returns the user input when the user has finished interacting with the dialog. In other words, something similar to the QFileDialog::getOpenFileName static method, where a single line can open the dialog and return the user's input, instead of employing the cumbersome (in this case) signal/slot mechanism.
Intended use:
/* Shows the dialog, waits until user presses OK or Cancel,
then returns the user's choice.
*/
result = createDialogAndReturnUserChoice()
I am currently working in PyQt but I'm fine with answers in the traditional Qt4 C++ framework.
EDIT//
Here's how to do it:
dialog = CustomDialog() # creates the custom dialog we have defined in a class inheriting QDialog
if dialog.exec_(): # on exec_(), the whole program freezes until the user is done with the dialog; it returns the response of the user
# success
else:
# failure
A:
It sounds like you have everything in place that you need. You can make a static function in your QDialog derived class that does what you want. You can create a struct or class that encapsulates the data the user will generate and return it from your static function. Qt includes all the source code so you can look at QFileDialog::getOpenFileName() in qfiledialog.cpp and see what they do.
Edit: Sorry, I missed that you are working in Python. I don't know what facilities the language has for extending a C++ class and static methods.
| Qt4: Write a function that creates a dialog and returns the choice of the user | Not sure if this has a straightforward solution, but I want to write a function that shows a dialog (defined elsewhere in a class that inherits QDialog) and returns the user input when the user has finished interacting with the dialog. In other words, something similar to the QFileDialog::getOpenFileName static method, where a single line can open the dialog and return the user's input, instead of employing the cumbersome (in this case) signal/slot mechanism.
Intended use:
/* Shows the dialog, waits until user presses OK or Cancel,
then returns the user's choice.
*/
result = createDialogAndReturnUserChoice()
I am currently working in PyQt but I'm fine with answers in the traditional Qt4 C++ framework.
EDIT//
Here's how to do it:
dialog = CustomDialog() # creates the custom dialog we have defined in a class inheriting QDialog
if dialog.exec_(): # on exec_(), the whole program freezes until the user is done with the dialog; it returns the response of the user
# success
else:
# failure
| [
"It sounds like you have everything in place that you need. You can make a static function in your QDialog derived class that does what you want. You can create a struct or class that encapsulates the data the user will generate and return it from your static function. Qt includes all the source code so you can loo... | [
1
] | [] | [] | [
"python",
"qt",
"user_interface"
] | stackoverflow_0003731702_python_qt_user_interface.txt |
Q:
Appengine - how to get an entity and display values
I'm having trouble with my project. I have 2 models
class UserPrefs(db.Model):
user = db.UserProperty()
name = db.StringProperty()
class Person(db.Model):
name = db.StringProperty()
phone = db.PhoneNumberProperty()
userPrefs = db.ReferenceProperty(UserPrefs)
class PersonHandler(webapp.RequestHandler):
def get(self):
users.get_current_user user = ()
if user:
greeting = ......
else:
greeting = ......
if self.request.GET.has_key ('id'):
id = int (self.request.get ['id'])
person = models.Person.get = (db.Key.from_path ('Person', id))
path = os.path.join (os.path.dirname (__file__), 'templates / doStuff.html')
self.response.out.write (template.render (path, locals (), debug = True))
def post (self):
if self.request.get ('Person'):
id = int (self.request.get ('Person'))
person = models.Person.get (db.Key.from_path ('Person', id))
else:
person= models.Person = ()
data = forms.PersonForm date = (data = self.request.POST)
if data.is_valid ():
if self.request.get ('photo'):
Person.foto db.Blob = (self.request.get ('photo'))
person.nome self.request.get = ('name')
person.apelido self.request.get = ('name')
person.unidade self.request.get = ('unit')
person.put ()
self.redirect ('/ doSomeStuff')
else:
self.redirect ('doOtherStuff')
To See the data in database i use this handler:
class SeePersonHandler (webapp.RequestHandler):
def get (self):
users.get_current_user user = ()
if user:
greeting = ......
else:
greeting = ......
person= db.Query(models.Pocente)
persons = person.fetch(limit = 1)
path = os.path.join(os.path.dirname(__file__), 'templates/SeeStuff.html')
self.response.out.write(template.render(path, locals(), debug = True))
Question:
I knows that the data is put corectly. I used the SDK Console with this url: http://localhost:8080/_ah/admin/datastore and the entity is created correctly. I don´t know what i am missing to retrieve the dadta already put
My Template:
{% if user %}
{% if person%}
<table align="center">
<tbody>
<tr>
<td><input type="button" value="Criar Pessoa" onclick="redirect(3)" /></td>
</tr>
</tbody>
</table>
<table align="center">
<tbody>
<tr>
<td colspan="2"><center><strong><p>O meu Curriculum Vitae</p></strong></center></td>
</tr>
<tr>
<td>Nome: </td>
<td>{{ person.name}}</td>
</tr>
<tr>
<td>Apelido: </td>
<td>{{ person.phone}}</td>
</tr>
<tr>
<td></td>
<td>
<input type ="button" value="Editar" onclick="editarCv({{ person.key.id }})" />
</td>
</tr>
</tbody>
</table>
{% endif %}
{% endif %}
A:
Your code is a bit disorganised.
Debugging is generally easier with better-organised code.
Anyway, enough of the trash-talking.
You're assigning the result of a datastore query to persons...
persons = person.fetch(limit = 1)
...but then in your template you use person:
<tr>
<td>Nome: </td>
<td>{{ person.name}}</td>
</tr>
<tr>
<td>Apelido: </td>
<td>{{ person.phone}}</td>
</tr>
It is difficult to tell if this is your only problem (I highly doubt it), but perhaps you can try fixing that and get back to us. Best of luck to you.
Aside: instead of .fetch(limit=1) you can simply use .get() as mentioned in the documentation:
get() implies a "limit" of 1. At most
1 result is fetched from the
datastore.
| Appengine - how to get an entity and display values | I'm having trouble with my project. I have 2 models
class UserPrefs(db.Model):
user = db.UserProperty()
name = db.StringProperty()
class Person(db.Model):
name = db.StringProperty()
phone = db.PhoneNumberProperty()
userPrefs = db.ReferenceProperty(UserPrefs)
class PersonHandler(webapp.RequestHandler):
def get(self):
users.get_current_user user = ()
if user:
greeting = ......
else:
greeting = ......
if self.request.GET.has_key ('id'):
id = int (self.request.get ['id'])
person = models.Person.get = (db.Key.from_path ('Person', id))
path = os.path.join (os.path.dirname (__file__), 'templates / doStuff.html')
self.response.out.write (template.render (path, locals (), debug = True))
def post (self):
if self.request.get ('Person'):
id = int (self.request.get ('Person'))
person = models.Person.get (db.Key.from_path ('Person', id))
else:
person= models.Person = ()
data = forms.PersonForm date = (data = self.request.POST)
if data.is_valid ():
if self.request.get ('photo'):
Person.foto db.Blob = (self.request.get ('photo'))
person.nome self.request.get = ('name')
person.apelido self.request.get = ('name')
person.unidade self.request.get = ('unit')
person.put ()
self.redirect ('/ doSomeStuff')
else:
self.redirect ('doOtherStuff')
To See the data in database i use this handler:
class SeePersonHandler (webapp.RequestHandler):
def get (self):
users.get_current_user user = ()
if user:
greeting = ......
else:
greeting = ......
person= db.Query(models.Pocente)
persons = person.fetch(limit = 1)
path = os.path.join(os.path.dirname(__file__), 'templates/SeeStuff.html')
self.response.out.write(template.render(path, locals(), debug = True))
Question:
I knows that the data is put corectly. I used the SDK Console with this url: http://localhost:8080/_ah/admin/datastore and the entity is created correctly. I don´t know what i am missing to retrieve the dadta already put
My Template:
{% if user %}
{% if person%}
<table align="center">
<tbody>
<tr>
<td><input type="button" value="Criar Pessoa" onclick="redirect(3)" /></td>
</tr>
</tbody>
</table>
<table align="center">
<tbody>
<tr>
<td colspan="2"><center><strong><p>O meu Curriculum Vitae</p></strong></center></td>
</tr>
<tr>
<td>Nome: </td>
<td>{{ person.name}}</td>
</tr>
<tr>
<td>Apelido: </td>
<td>{{ person.phone}}</td>
</tr>
<tr>
<td></td>
<td>
<input type ="button" value="Editar" onclick="editarCv({{ person.key.id }})" />
</td>
</tr>
</tbody>
</table>
{% endif %}
{% endif %}
| [
"Your code is a bit disorganised.\nDebugging is generally easier with better-organised code.\nAnyway, enough of the trash-talking.\nYou're assigning the result of a datastore query to persons... \npersons = person.fetch(limit = 1)\n\n...but then in your template you use person:\n<tr>\n <td>Nome: </td>\n <td>{{ p... | [
0
] | [] | [] | [
"bigtable",
"djangoappengine",
"google_app_engine",
"python"
] | stackoverflow_0003730575_bigtable_djangoappengine_google_app_engine_python.txt |
Q:
how can i get the geo_pt on another Model using google app engine(python)
this is my code:
class Marker_latlng(db.Model):
geo_pt = db.GeoPtProperty()
class Marker_info(db.Model):
info = db.StringProperty()
marker_latlng =db.ReferenceProperty(Marker_latlng)
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_values={}):
values={
}
template_values.update(values)
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.out.write(template.render(path, template_values))
class HomePage(BaseRequestHandler):
def get(self):
q = Marker_latlng.all()
q.filter("info =", "sss")
self.render_template('3.1.html',{'datas':q})
and the 3.1.html is :
var marker_data=[];
{% for i in datas %}
marker_data.push([{{db.Key(i.marker_latlng).geo_pt}}])
{% endfor %}
but the error is :
TemplateSyntaxError: Could not parse the remainder: (i.marker_latlng).geo_pt
so ,what can i do ?
thanks
A:
Did you mean:
q = Marker_info.all()
q.filter("info =", "sss")
?
Maybe try this:
marker_data.push([{{i.marker_latlng.geo_pt}}])
Or maybe:
marker_data.push([{{i.marker_latlng.geo_pt.lat}}, {{i.marker_latlng.geo_pt.lon}}])
| how can i get the geo_pt on another Model using google app engine(python) | this is my code:
class Marker_latlng(db.Model):
geo_pt = db.GeoPtProperty()
class Marker_info(db.Model):
info = db.StringProperty()
marker_latlng =db.ReferenceProperty(Marker_latlng)
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_values={}):
values={
}
template_values.update(values)
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.out.write(template.render(path, template_values))
class HomePage(BaseRequestHandler):
def get(self):
q = Marker_latlng.all()
q.filter("info =", "sss")
self.render_template('3.1.html',{'datas':q})
and the 3.1.html is :
var marker_data=[];
{% for i in datas %}
marker_data.push([{{db.Key(i.marker_latlng).geo_pt}}])
{% endfor %}
but the error is :
TemplateSyntaxError: Could not parse the remainder: (i.marker_latlng).geo_pt
so ,what can i do ?
thanks
| [
"Did you mean:\nq = Marker_info.all() \nq.filter(\"info =\", \"sss\")\n\n?\nMaybe try this:\nmarker_data.push([{{i.marker_latlng.geo_pt}}]) \n\nOr maybe:\nmarker_data.push([{{i.marker_latlng.geo_pt.lat}}, {{i.marker_latlng.geo_pt.lon}}]) \n\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"javascript",
"model",
"python"
] | stackoverflow_0003732214_google_app_engine_javascript_model_python.txt |
Q:
how to get the info which contains 'sss', not "= ",
this is my code:
class Marker_latlng(db.Model):
geo_pt = db.GeoPtProperty()
class Marker_info(db.Model):
info = db.StringProperty()
marker_latlng =db.ReferenceProperty(Marker_latlng)
q = Marker_info.all()
q.filter("info =", "sss")
but how to get the info which contains 'sss', not "=",
has a method like "contains "?
q = Marker_info.all()
q.filter("info contains", "sss")
A:
Instead of using a StringProperty, you could use a StringListProperty. Before saving the info string, split it into a list of strings, containing each word.
Then, when you use q.filter("info =", "sss") it will match any item which contains a word which is each to "sss".
For something more general, you could look into app engine full text search.
| how to get the info which contains 'sss', not "= ", | this is my code:
class Marker_latlng(db.Model):
geo_pt = db.GeoPtProperty()
class Marker_info(db.Model):
info = db.StringProperty()
marker_latlng =db.ReferenceProperty(Marker_latlng)
q = Marker_info.all()
q.filter("info =", "sss")
but how to get the info which contains 'sss', not "=",
has a method like "contains "?
q = Marker_info.all()
q.filter("info contains", "sss")
| [
"Instead of using a StringProperty, you could use a StringListProperty. Before saving the info string, split it into a list of strings, containing each word.\nThen, when you use q.filter(\"info =\", \"sss\") it will match any item which contains a word which is each to \"sss\".\nFor something more general, you coul... | [
1
] | [] | [] | [
"filter",
"google_app_engine",
"python"
] | stackoverflow_0003732351_filter_google_app_engine_python.txt |
Q:
Using Python quick insert many columns into Sqlite\Mysql
If Newdata is list of x columns, How would get the number unique columns--number of members of first tuple. (Len is not important.) Change the number of "?" to match columns and insert using the statement below.
csr = con.cursor()
csr.execute('Truncate table test.data')
csr.executemany('INSERT INTO test.data VALUES (?,?,?,?)', Newdata)
con.commit()
A:
By "Newdata is list of x columns", I imagine you mean x tuples, since then you continue to speak of "the first tuple". If Newdata is a list of tuples, y = len(Newdata[0]) is the number of items in the first one of those tuples.
Assuming that's the number you want (and all tuples had better have the same number of items, otherwise executemany will fail!), the general idea in @Nathan's answer is right: build the string with the appropriate number of comma-separated question marks:
holders = ','.join('?' * y)
then insert it in the rest of the SQL statement. @Nathan's way to insert is right for most Python 2.any versions, but if you have 2.6 or better,
sql = 'INSERT INTO testdata VALUES({0})'.format(holders)
is currently preferred (it also works in Python 3.any).
Finally,
csr.executemany(sql, Newdata)
will do what you desire. Remember to commit the transaction once you're done!-)
A:
If you're looking for the maximum number of items in all elements in Newdata, it's simply:
num_columns = max(len(t) for t in Newdata)
This, of course, assumes python 2.5 or greater.
Not that I'm sure what you're attempting would work, but the insert statement would then become:
sql = "INSERT INTO test.data VALUES (%s)" % ",".join('?' * num_columns)
| Using Python quick insert many columns into Sqlite\Mysql | If Newdata is list of x columns, How would get the number unique columns--number of members of first tuple. (Len is not important.) Change the number of "?" to match columns and insert using the statement below.
csr = con.cursor()
csr.execute('Truncate table test.data')
csr.executemany('INSERT INTO test.data VALUES (?,?,?,?)', Newdata)
con.commit()
| [
"By \"Newdata is list of x columns\", I imagine you mean x tuples, since then you continue to speak of \"the first tuple\". If Newdata is a list of tuples, y = len(Newdata[0]) is the number of items in the first one of those tuples.\nAssuming that's the number you want (and all tuples had better have the same numb... | [
6,
1
] | [] | [] | [
"mysql",
"python",
"python_db_api",
"sqlite"
] | stackoverflow_0003732490_mysql_python_python_db_api_sqlite.txt |
Q:
Get new selection in a GtkTreeView during the signal
I want to detect whenever the selection of my gtk.TreeView changes and, when it does, to call a function w/ this information. The only way I've found to do it so far is to attach to all these signals:
...
self.sitterView.connect("cursor-changed", self.selectionChanged)
self.sitterView.connect("unselect-all", self.selectionChanged)
self.sitterView.connect("toggle-cursor-row", self.selectionChanged)
self.sitterView.connect("select-all", self.selectionChanged)
...
def selectionChanged(self, treeview):
foo(self.sitterView.get_selection().get_selected())
However, it seems like the selection I get from the callback is "delayed". That is, it shows the selection after the previous callback had completed. For example, if I constantly CTRL+click on a row, when the row goes from deselected to selected, foo is given no selection, and when the row goes from selected to deselected, it is given a selection. If I call get_selection().get_selected() a second later, though, I get the right selection. Any idea how to deal w/ this?
A:
I'm not sure what toggle-cursor-row does (the documentation is frustratingly empty), but I think that's the wrong signal to handle.
Instead, you should connect to the GtkTreeSelection changed signal. It should take care of all selection change events, so you don't need to connect to the other signals either.
| Get new selection in a GtkTreeView during the signal | I want to detect whenever the selection of my gtk.TreeView changes and, when it does, to call a function w/ this information. The only way I've found to do it so far is to attach to all these signals:
...
self.sitterView.connect("cursor-changed", self.selectionChanged)
self.sitterView.connect("unselect-all", self.selectionChanged)
self.sitterView.connect("toggle-cursor-row", self.selectionChanged)
self.sitterView.connect("select-all", self.selectionChanged)
...
def selectionChanged(self, treeview):
foo(self.sitterView.get_selection().get_selected())
However, it seems like the selection I get from the callback is "delayed". That is, it shows the selection after the previous callback had completed. For example, if I constantly CTRL+click on a row, when the row goes from deselected to selected, foo is given no selection, and when the row goes from selected to deselected, it is given a selection. If I call get_selection().get_selected() a second later, though, I get the right selection. Any idea how to deal w/ this?
| [
"I'm not sure what toggle-cursor-row does (the documentation is frustratingly empty), but I think that's the wrong signal to handle.\nInstead, you should connect to the GtkTreeSelection changed signal. It should take care of all selection change events, so you don't need to connect to the other signals either.\n"
] | [
7
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003731549_gtk_gtktreeview_pygtk_python.txt |
Q:
urllib2.proxyhandler in python 2.5
In windows XP, python 2.5 and 2.6 I tested the following code:
import urllib2
proxy= urllib2.ProxyHandler({'http': '127.0.0.1:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com/')
In the above code I get a BadStatusLine exception from line 349 of httplib.py.
I have a proxy running at 127.0.0.1:8080 which works (I can set a browser to use it with proxyswitchy, and when it's on I can get to sites which are blocked when it's off [in China]).
if I change it to a socks proxy,
proxy= urllib2.ProxyHandler({'socks': '127.0.0.1:8080'})
Then the proxy is not used at all.
I got the code from the question at Proxy with urllib2 and it's almost exactly the same - what could be going wrong?
Update: urllib2 doesn't support socks proxies.
Eventually got it working with curl:
c = pycurl.Curl()
#stupid GFW
if settings.CHINA:
c.setopt(pycurl.PROXY, '127.0.0.1')
c.setopt(pycurl.PROXYPORT, 8087)
c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)
A:
The urllib2 ProxyHandler is not designed to support the SOCKS protocol. Perhaps this answer would help.
A:
Assuming your local proxy is an HTTP proxy and not a socks proxy. Try this:
import urllib2
proxy= urllib2.ProxyHandler({'http': 'http://127.0.0.1:8080/'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com/')
A:
UPDATE: I am located behind the great firewall of china. This was compounding the problem. The gfw was both breaking connections and doing DNS poisoning.
I have not managed to get any of the urllib2 solutions working. But pycurl does seem to work and it gets around the "connection reset" problem. fb/twitter were still blocked though.
Adding their IPS to my hosts file works - so for a larger scale solution, setting up a dns proxy is necessary.
| urllib2.proxyhandler in python 2.5 | In windows XP, python 2.5 and 2.6 I tested the following code:
import urllib2
proxy= urllib2.ProxyHandler({'http': '127.0.0.1:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com/')
In the above code I get a BadStatusLine exception from line 349 of httplib.py.
I have a proxy running at 127.0.0.1:8080 which works (I can set a browser to use it with proxyswitchy, and when it's on I can get to sites which are blocked when it's off [in China]).
if I change it to a socks proxy,
proxy= urllib2.ProxyHandler({'socks': '127.0.0.1:8080'})
Then the proxy is not used at all.
I got the code from the question at Proxy with urllib2 and it's almost exactly the same - what could be going wrong?
Update: urllib2 doesn't support socks proxies.
Eventually got it working with curl:
c = pycurl.Curl()
#stupid GFW
if settings.CHINA:
c.setopt(pycurl.PROXY, '127.0.0.1')
c.setopt(pycurl.PROXYPORT, 8087)
c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)
| [
"The urllib2 ProxyHandler is not designed to support the SOCKS protocol. Perhaps this answer would help.\n",
"Assuming your local proxy is an HTTP proxy and not a socks proxy. Try this:\nimport urllib2\nproxy= urllib2.ProxyHandler({'http': 'http://127.0.0.1:8080/'})\nopener = urllib2.build_opener(proxy)\nurllib2.... | [
2,
0,
0
] | [] | [] | [
"httplib",
"python",
"urllib2"
] | stackoverflow_0003726152_httplib_python_urllib2.txt |
Q:
Search Crawling "Bot"?
I am working on a project that requires me to collect a large list of URLs to websites about certain topics. I would like to write a script that will use google to search specific terms, then save the URLs from the results to a file. How would I go about doing this? I have used a module called xgoogle, but it always returned no results.
I am using Python 2.6 on Windows 7.
A:
google has an API library. I'd recommend you use that: http://code.google.com/apis/ajaxsearch/
it's a restful API, which means its easy to grab results via python/js. You're limited to 32 results, I think, but that should be enough. it'll return a nice structured object that you'll be able to work with without having to do anything with html parsing.
if you wanted to 'crawl', you could then use urllib to grab each of those urls and get THEIR contents, and the urls they refer to, and on and on.
A:
Make sure that you change the User-Agent of urllib2. The default one tends to get blocked by Google. Make sure that you obey the terms of use of the search engine that you're scripting.
| Search Crawling "Bot"? | I am working on a project that requires me to collect a large list of URLs to websites about certain topics. I would like to write a script that will use google to search specific terms, then save the URLs from the results to a file. How would I go about doing this? I have used a module called xgoogle, but it always returned no results.
I am using Python 2.6 on Windows 7.
| [
"google has an API library. I'd recommend you use that: http://code.google.com/apis/ajaxsearch/\nit's a restful API, which means its easy to grab results via python/js. You're limited to 32 results, I think, but that should be enough. it'll return a nice structured object that you'll be able to work with without ha... | [
1,
0
] | [] | [] | [
"hyperlink",
"python",
"search",
"windows"
] | stackoverflow_0003732595_hyperlink_python_search_windows.txt |
Q:
Prototype for python?
I just learned Prototype for Javascript. It's super convenient: using the $ shortcut, accessing xml elements is not painful any more!
The question: is there a Prototype-like extension for Python?
A:
Python has lxml which has the xpath method wherein you could use xpath expressions to select elements. As I understand it, $ in prototype searches and returns an element that has a particular id, in which case could be translated in xpath to *[@id=<someid>] like so:
>>> import lxml.etree
>>> tree = lxml.etree.XML("<root><a id='1'/><b id='2'/></root>")
>>> tree.xpath("*[@id=1]")
[<Element a at c3bc30>]
>>> lxml.etree.tostring(tree.xpath("*[@id=1]")[0])
'<a id="1"/>'
I think the Python standard library includes support for a subset of xpath in ElementTree too so you might be able to implement that there somehow if you do not wish to install lxml (which isn't included in stdlib)...
| Prototype for python? | I just learned Prototype for Javascript. It's super convenient: using the $ shortcut, accessing xml elements is not painful any more!
The question: is there a Prototype-like extension for Python?
| [
"Python has lxml which has the xpath method wherein you could use xpath expressions to select elements. As I understand it, $ in prototype searches and returns an element that has a particular id, in which case could be translated in xpath to *[@id=<someid>] like so:\n>>> import lxml.etree\n>>> tree = lxml.etree.XM... | [
1
] | [] | [] | [
"prototypejs",
"python"
] | stackoverflow_0003732740_prototypejs_python.txt |
Q:
What are the errors in this code?
Assume you have written a new function that checks to see if your game character has any life left. If the character does not have any life left, the function should print 'dead', if it has less than or equal to 5 life points left the function should print 'almost dead', otherwise it should print 'alive'.
am_i_alive():
hit_points = 20
if hit_points = 0:
print 'dead'
else hit_points <= 5:
print 'almost dead'
else:
print 'alive'
am_i_alive()
A:
def am_i_alive():
hit_points = 20
if hit_points == 0:
print 'dead'
elif hit_points <= 5:
print 'almost dead'
else:
print 'alive'
am_i_alive()
You need the def keyword to define a function.
You need to use == and not = for comparisons.
You chain if statements using elif.
other than that, it looks good. As in correct and will compile. It will always yield the same value though.
A better way to do it is:
def am_i_alive(hit_points):
if hit_points == 0:
print 'dead'
elif hit_points <= 5:
print 'almost dead'
else:
print 'alive'
am_i_alive(20)
am_i_alive(3)
am_i_alive(0)
Here, we are passing an 'argument' to the function. we call it with am_i_alive(x) where x can be any number. In the code for the function am_i_alive, whatever we put in place of x becomes the value referred to by hit_points.
A function can take two arguments as well. (in fact, up to 255 arguments)
def am_i_alive(hit_points, threshold):
if hit_points == 0:
print 'dead'
elif hit_points <= threshold:
print 'almost dead'
else:
print 'alive'
am_i_alive(20, 5)
am_i_alive(3, 2)
am_i_alive(0, 10)
Can you understand what the last version does?
I didn't read it because python is not my first language, but I'm told that this is a very good introduction to python and programming.
| What are the errors in this code? | Assume you have written a new function that checks to see if your game character has any life left. If the character does not have any life left, the function should print 'dead', if it has less than or equal to 5 life points left the function should print 'almost dead', otherwise it should print 'alive'.
am_i_alive():
hit_points = 20
if hit_points = 0:
print 'dead'
else hit_points <= 5:
print 'almost dead'
else:
print 'alive'
am_i_alive()
| [
"def am_i_alive(): \n hit_points = 20\n if hit_points == 0: \n print 'dead'\n elif hit_points <= 5: \n print 'almost dead'\n else: \n print 'alive'\n\nam_i_alive()\n\n\nYou need the def keyword to define a function.\nYou need to use == and not = for comparisons.\nYou chain if statem... | [
8
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0003732899_error_handling_python.txt |
Q:
TCP server: how to avoid message overlapping
I am going to write a TCP server, the client sends me XML message, I am wondering if below condition will happen and how to avoid that:
1) client sends <cmd ...></cmd>
2) sever is busy doing something
3) clients sends <cmd ...></cmd>
4) server does a recv() and put the string to buffer
Will the buffer be filled with <cmd ...></cmd><cmd ...></cmd> or even worse <cmd ...></cmd><cmd ... if my buffer is not big enough?
What I want is the TCP stack divides the messages to the same pieces as how clients sent them.
Is it doable?
A:
This is impossible to guarantee at the TCP level, since it only knows about streams.
Depending on the XML parser you're using, you should be able to feed it the stream and have it tell you when it has a complete object, leaving the second <cmd... in its buffer until it is closed also.
A:
You need a higher order protocol to delineate message boundaries as you desire. And there are plenty to choose from including the one that you invent yourself.
A:
You often write clients in the plural form: are there several clients connecting to your server? In this case, each client should be using its own TCP stream, and the issue you are describing should never occur.
If the various commands are send from a single client, then you should write your client code so that it waits for the answer to a command before issuing the next one.
| TCP server: how to avoid message overlapping | I am going to write a TCP server, the client sends me XML message, I am wondering if below condition will happen and how to avoid that:
1) client sends <cmd ...></cmd>
2) sever is busy doing something
3) clients sends <cmd ...></cmd>
4) server does a recv() and put the string to buffer
Will the buffer be filled with <cmd ...></cmd><cmd ...></cmd> or even worse <cmd ...></cmd><cmd ... if my buffer is not big enough?
What I want is the TCP stack divides the messages to the same pieces as how clients sent them.
Is it doable?
| [
"This is impossible to guarantee at the TCP level, since it only knows about streams.\nDepending on the XML parser you're using, you should be able to feed it the stream and have it tell you when it has a complete object, leaving the second <cmd... in its buffer until it is closed also.\n",
"You need a higher ord... | [
4,
3,
0
] | [] | [] | [
"networking",
"python",
"tcp"
] | stackoverflow_0003733363_networking_python_tcp.txt |
Q:
Python : how to prevent a class variable that is a function to be understood as a method?
I am currently implementing a django app, for this I try to use a syntax that is consistent with Django's...
So here is what I am trying :
class Blablabla(Model):
#this contains Blablabla's options
class Meta:
sort_key = lambda e: e
sort_key is a key function (for sorting purposes), but of course, it is understood as Meta's method (which is absolutely not what I want)!!!
Any workaround to this, that would still allow me to use this syntax ?
EDIT :
Just an important precision ... the code I wrote is supposed to be written by somebody that uses the library ! That's why I don't want any dirty trick. And YES in Django it is really used just for options... of course Meta IS a class, but I say "it is not seen as a class", because it is not used as a class : you don't instantiate it, you don't put class methods, only class attributes... The Model has a metaclass that extracts everything from this Meta and handles all the options declared... But that's all ! It IS just a placeholder for options.
But OK that's True I never saw an option that is a function in Django... So I'll follow Ned an declare this sorting function as a method of Model that has to be overriden ...
A:
In general,
class Meta(object):
sort_key= staticmethod(lambda e: e)
I've no idea if whatever magic Django does to transplant ‘meta’ members copes OK with decorated methods like this, but I don't see any inherent reason why not.
A:
Why are you trying to put sort_key into Meta? Meta is used for Django options, it isn't a place to put your own methods. Models can have methods defined on them. I think you want something as simple as:
class Blablabla(Model):
def sort_key(self, e):
return e
A:
The OP writes in a comment "'Meta' is not really supposed to be seen as a class". If that's the case, that is, if Django can survive when Meta is indeed not a class (a very big "if"), then it's possible to satisfy the OP's truly weird desire to avoid the simplest solution (just wrapping stqticfunction around the lambda in question).
Essentially, this requires writing a (pretty weird) meta-class that generates an object where attribute lookup bypasses a class's normal use of descriptor objects (every function is a descriptor object: that is, it has a __get__ method which Python normally uses when looking up attribute on the class or an instance thereof).
The general idea of this absurd gyration would be something like...:
class MetaNotAClass(type):
def __new__(mcl, clasname, bases, clasdict):
if bases:
usedict = {}
else:
usedict = clasdict
usedict['__foo'] = clasdict
return type.__new__(mcl, clasname, bases, usedict)
def __getattr__(cls, atname):
try: return getattr(cls, '__foo')[atname]
except KeyError: raise AttributeError, atname
class NotAClass:
__metaclass__ = MetaNotAClass
class Bah(NotAClass):
def f(): return 'weird!'
print Bah.f()
Of course, anything that expects Bah to be a class will break (but then, you do say it's "not really supposed to be seen as a class", so that's basically what you're asking for: to break any code that believes it is "to be seen as a class"!-).
A:
Can't you just create a simple module (meta?) and add sort_key to it? Then go ahead and include it wherever you need it...
| Python : how to prevent a class variable that is a function to be understood as a method? | I am currently implementing a django app, for this I try to use a syntax that is consistent with Django's...
So here is what I am trying :
class Blablabla(Model):
#this contains Blablabla's options
class Meta:
sort_key = lambda e: e
sort_key is a key function (for sorting purposes), but of course, it is understood as Meta's method (which is absolutely not what I want)!!!
Any workaround to this, that would still allow me to use this syntax ?
EDIT :
Just an important precision ... the code I wrote is supposed to be written by somebody that uses the library ! That's why I don't want any dirty trick. And YES in Django it is really used just for options... of course Meta IS a class, but I say "it is not seen as a class", because it is not used as a class : you don't instantiate it, you don't put class methods, only class attributes... The Model has a metaclass that extracts everything from this Meta and handles all the options declared... But that's all ! It IS just a placeholder for options.
But OK that's True I never saw an option that is a function in Django... So I'll follow Ned an declare this sorting function as a method of Model that has to be overriden ...
| [
"In general,\nclass Meta(object):\n sort_key= staticmethod(lambda e: e)\n\nI've no idea if whatever magic Django does to transplant ‘meta’ members copes OK with decorated methods like this, but I don't see any inherent reason why not.\n",
"Why are you trying to put sort_key into Meta? Meta is used for Django ... | [
2,
2,
0,
0
] | [] | [] | [
"django",
"function",
"metaclass",
"methods",
"python"
] | stackoverflow_0003731632_django_function_metaclass_methods_python.txt |
Q:
Django How to show user's name in his profile in admin console
I attached a UserProfile class to User this way:
class UserProfile(models.Model):
url = models.URLField()
home_address = models.TextField()
user = models.ForeignKey(User, unique=True)
I have also implemented auto-creating of UserProfile if needed this way:
def user_post_save(sender, instance, signal, *args, **kwargs):
profile, new = UserProfile.objects.get_or_create(user=instance)
models.signals.post_save.connect(user_post_save, sender=User)
It works fine but I need a small feature - when I go to User Profiles in admin console, I see a list of UserProfiles for existing users. Their titles are shown as UserProfile object. I think it would be nice if I could set titles to corresponding user names, for example, john, kenny etc.
How can I do that?
A:
Define a __unicode__ method for the UserProfile class:
def __unicode__(self):
return u"Profile for %s" % self.user.get_full_name()
| Django How to show user's name in his profile in admin console | I attached a UserProfile class to User this way:
class UserProfile(models.Model):
url = models.URLField()
home_address = models.TextField()
user = models.ForeignKey(User, unique=True)
I have also implemented auto-creating of UserProfile if needed this way:
def user_post_save(sender, instance, signal, *args, **kwargs):
profile, new = UserProfile.objects.get_or_create(user=instance)
models.signals.post_save.connect(user_post_save, sender=User)
It works fine but I need a small feature - when I go to User Profiles in admin console, I see a list of UserProfiles for existing users. Their titles are shown as UserProfile object. I think it would be nice if I could set titles to corresponding user names, for example, john, kenny etc.
How can I do that?
| [
"Define a __unicode__ method for the UserProfile class:\ndef __unicode__(self):\n return u\"Profile for %s\" % self.user.get_full_name() \n\n"
] | [
4
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003733502_django_django_admin_python.txt |
Q:
Is this a good reason to check types in Python?
I know that checking types in Python is bad and you should probably never do it. But I can't seem to find the disadvantage to this.
class O(object):
def __init__(self, name):
'''Can only be called in derived classes.'''
if type(self) is O:
message = "%(class)s cannot be instantiated, it must be derived."
raise TypeError, message % { "class" : O }
self.name = name
def fn(self):
'''Must be populated in derived classes.'''
raise NotImplementedError
Now if someone tries to instantiate O, a class I never meant to be instantiated, they know immediately.
Is this still bad form?
A:
Look at Abstract Base Classes as they will provide more fine grained control over how the subclasses are instantiated if this is something that you really want to do.
All in all, this might be a valid use because you are not preventing me from passing whatever I want to your code but I still wouldn't consider it pythonic. You are telling me that I can't instantiate your class. What If I want to?
Using ABC's, it looks like:
import abc
class O(object):
__metaclass__ = abc.ABCMeta
def __init__(self, name):
self.name = name
@abc.abstractmethod
def fn(self):
pass
This has the advantage of not breaking super on the fn method. As you have it with the raise NotImplementedError, you are breaking super for multiple inheritance. If a class derives from two classes that subclass O and both call super (as they should to allow for multiple inheritance) then it will create the exception that you raise.
So now, you are not just telling me that I can't instantiate your class, you are telling me that I can't use multiple inheritance when subclassing from your class.
A:
Don't check at all, we're are all adults here. Just add a note that O shouldn't be instantiated directly, either as a comment and/or in the documentation.
It's the same as if someone would call a method that requires an int as its parameter with a string instead. If the program crashes, they screwed it up. Otherwise you would need to add type checks to just about everything.
A:
What is that you are trying to achieve with the above code.
In this case self is of type O and will always result in raising the exception.
Look at this snippet to understand it a little better
class O(object):
def __init__(self, name):
self.name = name
o = O("X")
print type(o)
print isinstance(o, O)
if type(o) is O:
print "Yes"
This will output
<class '__main__.O'>
True
Yes
| Is this a good reason to check types in Python? | I know that checking types in Python is bad and you should probably never do it. But I can't seem to find the disadvantage to this.
class O(object):
def __init__(self, name):
'''Can only be called in derived classes.'''
if type(self) is O:
message = "%(class)s cannot be instantiated, it must be derived."
raise TypeError, message % { "class" : O }
self.name = name
def fn(self):
'''Must be populated in derived classes.'''
raise NotImplementedError
Now if someone tries to instantiate O, a class I never meant to be instantiated, they know immediately.
Is this still bad form?
| [
"Look at Abstract Base Classes as they will provide more fine grained control over how the subclasses are instantiated if this is something that you really want to do.\nAll in all, this might be a valid use because you are not preventing me from passing whatever I want to your code but I still wouldn't consider it ... | [
5,
5,
1
] | [] | [] | [
"python",
"typechecking"
] | stackoverflow_0003733730_python_typechecking.txt |
Q:
Using DC to draw wx.BitMapButtons on the fly?
I'm currently able to get this to do most of what I want to. It draws buttons based on lines from a text file as well as handles the way different button states look. What's really tripping me up right now is when self.input writes to the text file I have no idea how to get it to redraw everything to add or update buttons based on the new text. I've tried Update, Refresh, Show (False) then Show(True) and I'm stumped.
import wx
import mmap
import re
class pt:
with open('note.txt', "r+") as Note:
buf = mmap.mmap(Note.fileno(), 0)
TL = 0
readline = buf.readline
while readline():
TL += 1
Note.closed
class MainWindow(wx.Frame):
def __init__(self, parent, title):
w, h = wx.GetDisplaySize()
x = w * 0
y = h - bdepth
wx.Frame.__init__(self, parent, title = title, pos = (x, y), size = (200,bdepth), style = wx.STAY_ON_TOP)
self.input = wx.TextCtrl(self, -1, "", (6, pt.TL * 64 + 4), (184, 24))
self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter, self.input)
self.__DoButtons()
self.Show(True)
def __DoButtons(self):
Note = open('note.txt', "r+")
for i, line in enumerate(Note):
strip = line.rstrip()
todo = strip.lstrip('!')
self.check = re.match('!', strip)
self.priority = re.search('(\!$)', strip)
checkmark = wx.Image('check.bmp', wx.BITMAP_TYPE_BMP)
bullet = wx.Image('bullet.bmp', wx.BITMAP_TYPE_BMP)
exclaim = wx.Image('exclaim.bmp', wx.BITMAP_TYPE_BMP)
solid = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(solid)
solidpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetPen(solidpen)
dc.DrawRectangle(0, 0, 200, 64)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawBitmap(wx.BitmapFromImage(bullet, 32), 10, 28)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
checked = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(checked)
checkedpen = wx.Pen(wx.Colour(50,50,50),wx.SOLID)
dc.SetPen(checkedpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(200, 255, 0))
dc.DrawBitmap(wx.BitmapFromImage(checkmark, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
hover = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(hover)
hoverpen = wx.Pen(wx.Colour(100,100,100),wx.SOLID)
dc.SetPen(hoverpen)
dc.DrawRectangle(0, 0, 200, 64)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawBitmap(wx.BitmapFromImage(bullet, 32), 10, 28)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
important = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(important)
importantpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetPen(importantpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 180, 0))
dc.DrawBitmap(wx.BitmapFromImage(exclaim, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
importanthover = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(importanthover)
importanthoverpen = wx.Pen(wx.Colour(100,100,100),wx.SOLID)
dc.SetPen(importanthoverpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 180, 0))
dc.DrawBitmap(wx.BitmapFromImage(exclaim, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
if self.check is None and self.priority is None:
bmp = solid
elif self.priority is None:
bmp = checked
else:
bmp = important
b = wx.BitmapButton(self, i + 800, bmp, (0, i * 64), (solid.GetWidth(), solid.GetHeight()), style = wx.NO_BORDER)
b.SetBitmapDisabled(checked)
if self.check is None and self.priority is None:
b.SetBitmapHover(hover)
elif self.priority is None:
b.SetBitmapHover(checked)
else:
b.SetBitmapHover(importanthover)
Note.closed
def OnClick(self, event):
button = event.GetEventObject()
button.None
print('cheese')
def OnEnter(self, event):
editnote = open('note.txt', 'r+')
editnote.write(self.input.GetValue())
editnote.close()
self.Update()
bdepth = pt.TL * 64 + 32
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
A:
Theres no point in calling Update() Refresh() etc by themselves. They won't auto-magically create your buttons, you need to do that.
For starters I would refactor your __DoButtons() into two methods, one to create your buttons, and another to get your button data from your file and format it into an appropriate data structure -a list (and process it accordingly if necessary) which you can then pass to your new `__DoButtons method (which does the actual button creation).
In your onEnter() you will need to call your __DoButtons() method and pass in the appropriate data, if you only need to add new buttons why don't you get the data directly from the textEntry widget and save yourself the hassle of reading it from the file.
| Using DC to draw wx.BitMapButtons on the fly? | I'm currently able to get this to do most of what I want to. It draws buttons based on lines from a text file as well as handles the way different button states look. What's really tripping me up right now is when self.input writes to the text file I have no idea how to get it to redraw everything to add or update buttons based on the new text. I've tried Update, Refresh, Show (False) then Show(True) and I'm stumped.
import wx
import mmap
import re
class pt:
with open('note.txt', "r+") as Note:
buf = mmap.mmap(Note.fileno(), 0)
TL = 0
readline = buf.readline
while readline():
TL += 1
Note.closed
class MainWindow(wx.Frame):
def __init__(self, parent, title):
w, h = wx.GetDisplaySize()
x = w * 0
y = h - bdepth
wx.Frame.__init__(self, parent, title = title, pos = (x, y), size = (200,bdepth), style = wx.STAY_ON_TOP)
self.input = wx.TextCtrl(self, -1, "", (6, pt.TL * 64 + 4), (184, 24))
self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter, self.input)
self.__DoButtons()
self.Show(True)
def __DoButtons(self):
Note = open('note.txt', "r+")
for i, line in enumerate(Note):
strip = line.rstrip()
todo = strip.lstrip('!')
self.check = re.match('!', strip)
self.priority = re.search('(\!$)', strip)
checkmark = wx.Image('check.bmp', wx.BITMAP_TYPE_BMP)
bullet = wx.Image('bullet.bmp', wx.BITMAP_TYPE_BMP)
exclaim = wx.Image('exclaim.bmp', wx.BITMAP_TYPE_BMP)
solid = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(solid)
solidpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetPen(solidpen)
dc.DrawRectangle(0, 0, 200, 64)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawBitmap(wx.BitmapFromImage(bullet, 32), 10, 28)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
checked = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(checked)
checkedpen = wx.Pen(wx.Colour(50,50,50),wx.SOLID)
dc.SetPen(checkedpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(200, 255, 0))
dc.DrawBitmap(wx.BitmapFromImage(checkmark, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
hover = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(hover)
hoverpen = wx.Pen(wx.Colour(100,100,100),wx.SOLID)
dc.SetPen(hoverpen)
dc.DrawRectangle(0, 0, 200, 64)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawBitmap(wx.BitmapFromImage(bullet, 32), 10, 28)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
important = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(important)
importantpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetPen(importantpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 180, 0))
dc.DrawBitmap(wx.BitmapFromImage(exclaim, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
importanthover = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(importanthover)
importanthoverpen = wx.Pen(wx.Colour(100,100,100),wx.SOLID)
dc.SetPen(importanthoverpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 180, 0))
dc.DrawBitmap(wx.BitmapFromImage(exclaim, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
if self.check is None and self.priority is None:
bmp = solid
elif self.priority is None:
bmp = checked
else:
bmp = important
b = wx.BitmapButton(self, i + 800, bmp, (0, i * 64), (solid.GetWidth(), solid.GetHeight()), style = wx.NO_BORDER)
b.SetBitmapDisabled(checked)
if self.check is None and self.priority is None:
b.SetBitmapHover(hover)
elif self.priority is None:
b.SetBitmapHover(checked)
else:
b.SetBitmapHover(importanthover)
Note.closed
def OnClick(self, event):
button = event.GetEventObject()
button.None
print('cheese')
def OnEnter(self, event):
editnote = open('note.txt', 'r+')
editnote.write(self.input.GetValue())
editnote.close()
self.Update()
bdepth = pt.TL * 64 + 32
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
| [
"Theres no point in calling Update() Refresh() etc by themselves. They won't auto-magically create your buttons, you need to do that. \nFor starters I would refactor your __DoButtons() into two methods, one to create your buttons, and another to get your button data from your file and format it into an appropriate... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003732907_python_wxpython.txt |
Q:
How to install Trac Plugin and what is a python egg?
In Trac on Admin -> Plugins there is an option to install Plug-ins. Now this option expect you to upload an Python egg.
This would be all well but for the fact that all the Trac plug-ins I found are either plain .py files or zip files and are incompatible with the upload function (I tried it).
This leaves my with a bunch of questions:
Are there any Trac plug-ins which come as an Python egg?
What is an (Trac compatible) Python egg?
Is it difficult to repackage an .py file into a Trac compatible Python egg?
If not: how is it done?
A:
Haven't used trac for a year, but what I remember is that most plugins are available trough subversion and already packed as an egg (which is kind of an installer in the python world, but I am not very familiar with the concept).
Most plugins are available at http://trac-hacks.org/ and the easiest way to install a plugin is
easy_install http://svn.domain.tdl/path/to/plugin/
the folder should contain a setup.py and a setup.cfg file.
easy_install checks the files out from svn and installs the plugin. You can find details here: http://trac.edgewall.org/wiki/TracPlugins
If the plugin makes database changes you have to call
trac-admin upgrade
from console.
http://trac.edgewall.org/wiki/TracAdmin
If I remember right, the install through the webinterface installs the plugin locally (for the instance) while easy_install installs it globally (for all running trac sites) and is the more common way to install a plugin.
Hint: After every plugin install you have to restart trac
Hint2: Most plugins don't tell you how to install and only give a link to the root of their svn. You only have to browse the svn folder and locate the folder containing the setup.py.
The rest is done with easy_install.
Example:
Plugin: http://trac-hacks.org/wiki/GoogleChartPlugin
Wiki pages tells you:
You can check out GoogleChartPlugin from here using Subversion, or browse the source with Trac.
where here links to http://trac-hacks.org/svn/googlechartplugin/
The svn contains two versions. Browse to http://trac-hacks.org/svn/googlechartplugin/0.11/trunk/ and copy the path.
Then do
easy_install http://trac-hacks.org/svn/googlechartplugin/0.11/trunk/
A:
Answers to your questions in order.
Python eggs are binary packages which contain the code for the application and some metadata. They're not very different from debs or rpms in this sense. The egg itself is basically just a zip file which contains all the above mentioned files with specific names and layouts. For more information on eggs (the format and how to create them), please refer to http://www.ibm.com/developerworks/library/l-cppeak3.html. It's probably a little dated since the future (and present) of python packaging is a little hazy.
A trac plugin is a python program that uses the Trac plugin API to extend the functionality of trac. It can be packaged as an egg.
If your package is properly laid out and contains a setuptools/distribute setup.py file, then issuing the command python setup.py bdist_egg will create a .egg file for you. For details on this please refer to this(a little dated but complete) and this (more upto date but still in progress). The Trac Growl plugin mentions this on it's documentation page.
Please see above point.
| How to install Trac Plugin and what is a python egg? | In Trac on Admin -> Plugins there is an option to install Plug-ins. Now this option expect you to upload an Python egg.
This would be all well but for the fact that all the Trac plug-ins I found are either plain .py files or zip files and are incompatible with the upload function (I tried it).
This leaves my with a bunch of questions:
Are there any Trac plug-ins which come as an Python egg?
What is an (Trac compatible) Python egg?
Is it difficult to repackage an .py file into a Trac compatible Python egg?
If not: how is it done?
| [
"Haven't used trac for a year, but what I remember is that most plugins are available trough subversion and already packed as an egg (which is kind of an installer in the python world, but I am not very familiar with the concept).\nMost plugins are available at http://trac-hacks.org/ and the easiest way to install ... | [
4,
3
] | [] | [] | [
"egg",
"python",
"trac"
] | stackoverflow_0003733970_egg_python_trac.txt |
Q:
Trouble using Selenium Grid/RC with Python
I have built a couple of test cases as stand alone python classes using Selenium. I can run each of them using Selenium RC. Ultimately I want to use Selenium Grid to run all of the test cases.
How would I do this?
Do I need some kind of wrapper to hold of of the python test cases together? How do I get Selenium Grid to run a collection of these?
Thanks for your help.
A:
I would suggest having a look at running your tests in Parallel using Nose
There is documentation on how to get it running here
| Trouble using Selenium Grid/RC with Python | I have built a couple of test cases as stand alone python classes using Selenium. I can run each of them using Selenium RC. Ultimately I want to use Selenium Grid to run all of the test cases.
How would I do this?
Do I need some kind of wrapper to hold of of the python test cases together? How do I get Selenium Grid to run a collection of these?
Thanks for your help.
| [
"I would suggest having a look at running your tests in Parallel using Nose\nThere is documentation on how to get it running here\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_grid",
"selenium_rc"
] | stackoverflow_0003731299_python_selenium_selenium_grid_selenium_rc.txt |
Q:
Python RegEx Matching Newline
I have the following regular expression:
[0-9]{8}.*\n.*\n.*\n.*\n.*
Which I have tested in Expresso against the file I am working with and the match is sucessful.
I want to match the following:
Reference number 8 numbers long
Any character, any number of times
New Line
Any character, any number of times
New Line
Any character, any number of times
New Line
Any character, any number of times
New Line
Any character, any number of times
My python code is:
for m in re.findall('[0-9]{8}.*\n.*\n.*\n.*\n.*', l, re.DOTALL):
print m
But no matches are produced, as said in Expresso there are 400+ matches which is what I would expect.
What I am missing here?
A:
Don't use re.DOTALL or the dot will match newlines, too. Also use raw strings (r"...") for regexes:
for m in re.findall(r'[0-9]{8}.*\n.*\n.*\n.*\n.*', l):
print m
However, your version still should have worked (although very inefficiently) if you have read the entire file as binary into memory as one large string.
So the question is, are you reading the file like this:
with open("filename","rb") as myfile:
mydata = myfile.read()
for m in re.findall(r'[0-9]{8}.*\n.*\n.*\n.*\n.*', mydata):
print m
Or are you working with single lines (for line in myfile: or myfile.readlines())? In that case, the regex can't work, of course.
| Python RegEx Matching Newline | I have the following regular expression:
[0-9]{8}.*\n.*\n.*\n.*\n.*
Which I have tested in Expresso against the file I am working with and the match is sucessful.
I want to match the following:
Reference number 8 numbers long
Any character, any number of times
New Line
Any character, any number of times
New Line
Any character, any number of times
New Line
Any character, any number of times
New Line
Any character, any number of times
My python code is:
for m in re.findall('[0-9]{8}.*\n.*\n.*\n.*\n.*', l, re.DOTALL):
print m
But no matches are produced, as said in Expresso there are 400+ matches which is what I would expect.
What I am missing here?
| [
"Don't use re.DOTALL or the dot will match newlines, too. Also use raw strings (r\"...\") for regexes:\nfor m in re.findall(r'[0-9]{8}.*\\n.*\\n.*\\n.*\\n.*', l):\n print m\n\nHowever, your version still should have worked (although very inefficiently) if you have read the entire file as binary into memory as one... | [
12
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003734023_python_regex.txt |
Q:
Serializing IronPython Objects Which Inherit From CLR Types
This may be a bit of a weird question, but is there any reliable way to serialize IronPython objects whose classes extend CLR types?
For instance:
class Foo(System.Collections.Generic.List[str]):
def Test(self):
print "test!"
System.Collections.Generic.List<string> is serializable with Pickle, as it implements the ISerializable interface, but emitted subclasses of serializable CLR types seem to not work, and i get ImportError: No module named Generic in mscorlib, Version=4 when running pickle.dumps(Foo()).
Additionally, running the usual Formatter.Serialize(stream, object) gives me:
SystemError: Type 'IronPython.NewTypes.System.Collections.Generic.List`1_4$4' in Assembly Snippets.scripting, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
How can I implement serialization of IronPython objects when running in an embedded C# environment?
A:
I don't know if it is what you are after, but you could consider the python version of protobuf (here)? I haven't tested it specifically on ironpython, mind. This has the added advantage that there are also C# implementations that may help, while keeping it platform independent. When possible I want to get protobuf-net to support DLR types, but that is a big job.
As a side note, personally I'd recommend having a dedicated DTO type rather than trying to extend the inbuilt types.
A:
Quote from clrtype metaclasses
IronPython doesn’t support Reflection
based APIs or custom attributes today
because IronPython doesn’t emit a
custom CLR types for every Python
class. Instead, it typically shares a
single CLR type across many Python
classes. For example, all three of
these Python classes share a single
underlying CLR type.
class shop(object):
pass
class cheese_shop(shop):
def have_cheese(self, cheese_type):
return False
class argument_clinic(object):
def is_right_room(self, room=12):
return "I've told you once"
import clr
print clr.GetClrType(shop).FullName
print clr.GetClrType(cheese_shop).FullName
print clr.GetClrType(argument_clinic).FullName
Even though cheese_shop inherits from
shop and argument_clinic inherits from
object, all three classes share the
same underlying CLR type
I haven't tried, but maybe you can solve this issue with manual serialization via serialization surrogates.
| Serializing IronPython Objects Which Inherit From CLR Types | This may be a bit of a weird question, but is there any reliable way to serialize IronPython objects whose classes extend CLR types?
For instance:
class Foo(System.Collections.Generic.List[str]):
def Test(self):
print "test!"
System.Collections.Generic.List<string> is serializable with Pickle, as it implements the ISerializable interface, but emitted subclasses of serializable CLR types seem to not work, and i get ImportError: No module named Generic in mscorlib, Version=4 when running pickle.dumps(Foo()).
Additionally, running the usual Formatter.Serialize(stream, object) gives me:
SystemError: Type 'IronPython.NewTypes.System.Collections.Generic.List`1_4$4' in Assembly Snippets.scripting, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
How can I implement serialization of IronPython objects when running in an embedded C# environment?
| [
"I don't know if it is what you are after, but you could consider the python version of protobuf (here)? I haven't tested it specifically on ironpython, mind. This has the added advantage that there are also C# implementations that may help, while keeping it platform independent. When possible I want to get protobu... | [
2,
1
] | [] | [] | [
"c#",
"ironpython",
"pickle",
"python",
"serialization"
] | stackoverflow_0003734063_c#_ironpython_pickle_python_serialization.txt |
Q:
What is the equivalent for heapq of Python in Java?
I would like to know if there is any api available for Java which is just like heapq in Python.
A:
Have you looked at java.util.PriorityQueue?
| What is the equivalent for heapq of Python in Java? | I would like to know if there is any api available for Java which is just like heapq in Python.
| [
"Have you looked at java.util.PriorityQueue?\n"
] | [
2
] | [] | [] | [
"heap",
"java",
"python"
] | stackoverflow_0003734463_heap_java_python.txt |
Q:
unable to compile python program using jython
I'm trying to compile a python program using jython and it's throwing below error
C:\jython2.2.1>jython test.py
Traceback (innermost last):
(no code object) at line 0
File "test.py", line 30
html = html if html else download(url, user_agent).read()
^
SyntaxError: invalid syntax
Below is my python program. Please let me know how to resolve this.
import sys
import re
import urllib2
import urlparse
from optparse import OptionParser
# regular expression data for each website
VIDEO_DATA = [
('youtube.com', '%7C(.*?videoplayback.*?)%2C'),
('metacafe.com', '&mediaURL=(.*?)&'),
]
# default user agent to use when downloading
USER_AGENT = 'pytube'
# size of file to download
CHUNK_SIZE = 1024 * 1024
def scrape(url, html=None, user_agent=None, output=None):
"""Scrape video location from given url.
Use html instead of downloading if passed.
Download file to output if passed.
Return url of video if found, else None
"""
netloc = urlparse.urlsplit(url).netloc
for domain, video_re in VIDEO_DATA:
if domain in netloc:
html = html if html else download(url, user_agent).read()
search = re.search(video_re, html)
if search:
flash_url = urllib2.unquote(search.group(1))
if output:
print "Downloading flash to `%s'" % output,
#open(output, 'wb').write(download(flash_url, user_agent).read())
req = download(flash_url, user_agent)
# testing with keyword in python
with open(output, 'wb') as fp:
chunk = True
while chunk:
chunk = req.read(CHUNK_SIZE)
if chunk:
fp.write(chunk)
#fp.flush()
print '.',
sys.stdout.flush()
print
return flash_url
else:
raise PyTubeException('Failed to locate video regular expression in downloaded HTML')
raise PyTubeException('URL did not match available domains')
def download(url, user_agent=None):
"""Download url and return data
"""
headers = {'User-Agent' : user_agent}
req = urllib2.Request(url, None, headers)
return urllib2.urlopen(req)
class PyTubeException(Exception):
pass
if __name__ == '__main__':
# parse command line options
parser = OptionParser(usage='usage: %prog, [-o <file.flv> -a <user_agent> -s -h] url')
parser.add_option('-o', '--output', dest='output', help='Output file to download flash file to. If this is not specified file will not be downloaded.')
parser.add_option('-s', '--sites', action='store_true', default=False, dest='sites', help='Display sites that pytube supports, then quit.')
parser.add_option('-a', '--agent', dest='user_agent', default=USER_AGENT, help='Set user-agent for downloads.')
options, args = parser.parse_args()
if options.sites:
print '\n'.join(domain for (domain, reg) in VIDEO_DATA)
else:
if args:
flash_url = scrape(args[0], user_agent=options.user_agent, output=options.output)
if flash_url:
print flash_url
else:
print 'Need to pass the url of the video you want to download'
parser.print_help()
A:
Jython 2.2.1 is (AFAIK) equivalent to Cpython 2.2.1 as far as syntax is concerned. The line that causes the problem uses the ternary operator which was introduced later. the solution is to replace it with an if statement.
if not html:
html = download(url, user_agent).read()
That should take care of that syntax error. There is also a with clause that you will need to replace.
with open(output, 'wb') as fp:
chunk = True
while chunk:
chunk = req.read(CHUNK_SIZE)
if chunk:
fp.write(chunk)
#fp.flush()
print '.',
sys.stdout.flush()
You can replace this with
try:
fp = open(output, 'w')
chunk = True
while chunk:
chunk = req.read(CHUNK_SIZE)
if chunk:
fp.write(chunk)
#fp.flush()
print '.',
sys.stdout.flush()
finally:
fp.close()
| unable to compile python program using jython | I'm trying to compile a python program using jython and it's throwing below error
C:\jython2.2.1>jython test.py
Traceback (innermost last):
(no code object) at line 0
File "test.py", line 30
html = html if html else download(url, user_agent).read()
^
SyntaxError: invalid syntax
Below is my python program. Please let me know how to resolve this.
import sys
import re
import urllib2
import urlparse
from optparse import OptionParser
# regular expression data for each website
VIDEO_DATA = [
('youtube.com', '%7C(.*?videoplayback.*?)%2C'),
('metacafe.com', '&mediaURL=(.*?)&'),
]
# default user agent to use when downloading
USER_AGENT = 'pytube'
# size of file to download
CHUNK_SIZE = 1024 * 1024
def scrape(url, html=None, user_agent=None, output=None):
"""Scrape video location from given url.
Use html instead of downloading if passed.
Download file to output if passed.
Return url of video if found, else None
"""
netloc = urlparse.urlsplit(url).netloc
for domain, video_re in VIDEO_DATA:
if domain in netloc:
html = html if html else download(url, user_agent).read()
search = re.search(video_re, html)
if search:
flash_url = urllib2.unquote(search.group(1))
if output:
print "Downloading flash to `%s'" % output,
#open(output, 'wb').write(download(flash_url, user_agent).read())
req = download(flash_url, user_agent)
# testing with keyword in python
with open(output, 'wb') as fp:
chunk = True
while chunk:
chunk = req.read(CHUNK_SIZE)
if chunk:
fp.write(chunk)
#fp.flush()
print '.',
sys.stdout.flush()
print
return flash_url
else:
raise PyTubeException('Failed to locate video regular expression in downloaded HTML')
raise PyTubeException('URL did not match available domains')
def download(url, user_agent=None):
"""Download url and return data
"""
headers = {'User-Agent' : user_agent}
req = urllib2.Request(url, None, headers)
return urllib2.urlopen(req)
class PyTubeException(Exception):
pass
if __name__ == '__main__':
# parse command line options
parser = OptionParser(usage='usage: %prog, [-o <file.flv> -a <user_agent> -s -h] url')
parser.add_option('-o', '--output', dest='output', help='Output file to download flash file to. If this is not specified file will not be downloaded.')
parser.add_option('-s', '--sites', action='store_true', default=False, dest='sites', help='Display sites that pytube supports, then quit.')
parser.add_option('-a', '--agent', dest='user_agent', default=USER_AGENT, help='Set user-agent for downloads.')
options, args = parser.parse_args()
if options.sites:
print '\n'.join(domain for (domain, reg) in VIDEO_DATA)
else:
if args:
flash_url = scrape(args[0], user_agent=options.user_agent, output=options.output)
if flash_url:
print flash_url
else:
print 'Need to pass the url of the video you want to download'
parser.print_help()
| [
"Jython 2.2.1 is (AFAIK) equivalent to Cpython 2.2.1 as far as syntax is concerned. The line that causes the problem uses the ternary operator which was introduced later. the solution is to replace it with an if statement.\nif not html:\n html = download(url, user_agent).read() \n\nThat should take care of that... | [
1
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0003734496_jython_python.txt |
Q:
When to use * and ** as a function argument in python function
When can I pass * and ** in the argument of a Python function? i.e.:
def fun_name(arg1, *arg2 , ** arg3):
A:
As you've stated your question, you aren't using them in the arguments (which occur when you are calling a function), you are using them in the parameters which occur when you are creating a function. The * and ** operators serve different purposes in each of those situations.
When you are defining a function, they specify that positional arguments will be placed in a tuple and that keyword arguments will be placed in a dict. Yes I did just say arguments, but they are applied to paramaters in this case.
def example(*args, **kwargs):
print "args: {0}".format(args)
print "kwargs: {0}".format(kwargs)
example(1, 2, 'a', foo='bar', bar='foo')
when run, this outputs:
args: (1, 2, 'a')
kwargs: {'foo': 'bar', 'bar': 'foo'}
Do you see what I mean when I say that we applied it to the paramaters in the function definition? the arguments are 1, 2, 'a', foo='bar', bar='foo'. the paramaters are *args, **kwargs.
Now here's an example applying them to arguments.
def example2(a, b, foo=None, bar=None):
print "a: {0}, b:{1}, foo:{2}, bar: {3}".format(a, b, foo, bar)
args = (1, 2)
kwargs = {'foo': 'bar', 'bar': 'foo'}
example2(*args, **kwargs)
This outputs:
a: 1, b:2, foo:bar, bar: foo
You can see that when we apply them to arguments (that is when we are calling the function), * has the effect of expanding a list or tuple to fill the positional arguments of a function and ** has the effect of expanding a dictionary to fill the keyword arguments of a function. You just need to make sure that there are enough and not too much arguments in total after the expansions have taken place.
in the last example, the arguments are *args, **kwargs and the parameters are a, b, foo=None, bar=None
A:
When can I pass * and ** in the argument of a Python function? i.e.:
Short answer: when you require variable number of argument to be passed to your function.
That said, I honestly think that this a very broad question. You will be much better off reading more about these concepts, trying them off and then asking an specific questions here.
@Wooble's answer will help you; but what will help you even more is to understand what *args and **kwargs do. Then you can use them as befits the situations you encounter.
You can learn more about the variable and keyword arguments concepts for example at:
http://www.network-theory.co.uk/docs/pytut/KeywordArguments.html
http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
A:
Any time you want your function to accept non-named positional arguments (*), or additional named arguments (**).
It's certainly possible to include *args, **kwargs in every function definition, although this might not be a great idea if passing more arguments won't actually have any effect.
| When to use * and ** as a function argument in python function | When can I pass * and ** in the argument of a Python function? i.e.:
def fun_name(arg1, *arg2 , ** arg3):
| [
"As you've stated your question, you aren't using them in the arguments (which occur when you are calling a function), you are using them in the parameters which occur when you are creating a function. The * and ** operators serve different purposes in each of those situations.\nWhen you are defining a function, th... | [
11,
2,
1
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003734720_python_syntax.txt |
Q:
How to deploy a Python/SQLAlchemy application?
SQLAlchemy allowed me to create a powerful database utility. Now I don't know how to deploy it. Let me explain how is it built with an example:
# objects.py
class Item(object):
def __init__(self, name):
self.name = name
# schema.py
from sqlalchemy import *
from objects import Item
engine=create_engine('sqlite:///mydb.db')
metadata = MetaData(engine)
item_table = Table(
'items', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(100))
)
item_mapper = mapper(Item, item_table)
metadata.create_all()
# application.py
from schema import engine, Item
from sqlalchemy import *
Session = sessionmaker(bind=engine)
class Browser(object):
def __init__(self):
self.s = Session()
def get_by_name(self, name):
return self.s.query(Item).filter_by(name=name)
As you can see, what I want to make available is the last interface (Browser) where I simplify the queries for the end user.
If you simply request every user to open a Python shell and from application import Browser it seems that the advantages of connection pooling are not realized, because every user creates a different Session class (as opposed to creating a different session instance).
So, should I write a server that the users connect to? Or, how would you deploy this hypothetical application?
Thank you.
A:
Connection pooling happens within the same python instance, so when your users connect from remote to the database, you have to write a small server anyways, if you want to use it. You can also connect directly to a database server, resulting in (at least) one connection per user. Depends on what you want to achieve.
| How to deploy a Python/SQLAlchemy application? | SQLAlchemy allowed me to create a powerful database utility. Now I don't know how to deploy it. Let me explain how is it built with an example:
# objects.py
class Item(object):
def __init__(self, name):
self.name = name
# schema.py
from sqlalchemy import *
from objects import Item
engine=create_engine('sqlite:///mydb.db')
metadata = MetaData(engine)
item_table = Table(
'items', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(100))
)
item_mapper = mapper(Item, item_table)
metadata.create_all()
# application.py
from schema import engine, Item
from sqlalchemy import *
Session = sessionmaker(bind=engine)
class Browser(object):
def __init__(self):
self.s = Session()
def get_by_name(self, name):
return self.s.query(Item).filter_by(name=name)
As you can see, what I want to make available is the last interface (Browser) where I simplify the queries for the end user.
If you simply request every user to open a Python shell and from application import Browser it seems that the advantages of connection pooling are not realized, because every user creates a different Session class (as opposed to creating a different session instance).
So, should I write a server that the users connect to? Or, how would you deploy this hypothetical application?
Thank you.
| [
"Connection pooling happens within the same python instance, so when your users connect from remote to the database, you have to write a small server anyways, if you want to use it. You can also connect directly to a database server, resulting in (at least) one connection per user. Depends on what you want to achie... | [
0
] | [] | [] | [
"deployment",
"python",
"sqlalchemy"
] | stackoverflow_0003525783_deployment_python_sqlalchemy.txt |
Q:
Help with Python urllib2 and openers - How to make only 1 remote file read
I am trying to download content from a content provider that charges me every time I access a document. The code I have written correctly downloads the content and saves them in a local file but apparently it requests the file twice and I am being double charged. I'm not sure where the file is being requested twice, here is my code:
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)
# use the opener to fetch a URL
file_stream = opener.open(url)
# Open our local file for writing
local_file = open(directory + doc_name, "w+")
#Write to our local file
local_file.write(file_stream.read())
I need to figure out how to read the content while only requesting the document once. Any help would be greatly appreciated.
A:
Could it be that it requests the file twice, but only downloads it once? The first request would be a normal GET (without an "Authorization" header), followed by a response of HTTP 401 (Authorization Required), followed by the same request with the Authorization header.
If thats the case, you shold talk to your content provider, since you accessed it only once.
| Help with Python urllib2 and openers - How to make only 1 remote file read | I am trying to download content from a content provider that charges me every time I access a document. The code I have written correctly downloads the content and saves them in a local file but apparently it requests the file twice and I am being double charged. I'm not sure where the file is being requested twice, here is my code:
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)
# use the opener to fetch a URL
file_stream = opener.open(url)
# Open our local file for writing
local_file = open(directory + doc_name, "w+")
#Write to our local file
local_file.write(file_stream.read())
I need to figure out how to read the content while only requesting the document once. Any help would be greatly appreciated.
| [
"Could it be that it requests the file twice, but only downloads it once? The first request would be a normal GET (without an \"Authorization\" header), followed by a response of HTTP 401 (Authorization Required), followed by the same request with the Authorization header. \nIf thats the case, you shold talk to you... | [
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003722017_python_urllib2.txt |
Q:
How to Format dict string outputs nicely
I wonder if there is an easy way to format Strings of dict-outputs such as this:
{
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
..., where a simple str(dict) just would give you a quite unreadable ...
{'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}
For as much as I know about Python I would have to write a lot of code with many special cases and string.replace() calls, where this problem itself does not look so much like a 1000-lines-problem.
Please suggest the easiest way to format any dict according to this shape.
A:
Depending on what you're doing with the output, one option is to use JSON for the display.
import json
x = {'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}
print json.dumps(x, indent=2)
Output:
{
"planet": {
"has": {
"plants": "yes",
"animals": "yes",
"cryptonite": "no"
},
"name": "Earth"
}
}
The caveat to this approach is that some things are not serializable by JSON. Some extra code would be required if the dict contained non-serializable items like classes or functions.
A:
Use pprint
import pprint
x = {
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(x)
This outputs
{ 'planet': { 'has': { 'animals': 'yes',
'cryptonite': 'no',
'plants': 'yes'},
'name': 'Earth'}}
Play around with pprint formatting and you can get the desired result.
http://docs.python.org/library/pprint.html
A:
def format(d, tab=0):
s = ['{\n']
for k,v in d.items():
if isinstance(v, dict):
v = format(v, tab+1)
else:
v = repr(v)
s.append('%s%r: %s,\n' % (' '*tab, k, v))
s.append('%s}' % (' '*tab))
return ''.join(s)
print format({'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}})
Output:
{
'planet': {
'has': {
'plants': 'yes',
'animals': 'yes',
'cryptonite': 'no',
},
'name': 'Earth',
},
}
Note that I'm sorta assuming all keys are strings, or at least pretty objects here
| How to Format dict string outputs nicely | I wonder if there is an easy way to format Strings of dict-outputs such as this:
{
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
..., where a simple str(dict) just would give you a quite unreadable ...
{'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}
For as much as I know about Python I would have to write a lot of code with many special cases and string.replace() calls, where this problem itself does not look so much like a 1000-lines-problem.
Please suggest the easiest way to format any dict according to this shape.
| [
"Depending on what you're doing with the output, one option is to use JSON for the display.\nimport json\nx = {'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}\n\nprint json.dumps(x, indent=2)\n\nOutput:\n{\n \"planet\": {\n \"has\": {\n \"plants\": \"yes\", \n ... | [
116,
42,
7
] | [] | [] | [
"formatting",
"python",
"string"
] | stackoverflow_0003733554_formatting_python_string.txt |
Q:
Convert the input from telnet to a list in twisted
input from telnet
GET /learn/tutorials/351079-weekend-project-secure-your-system-with-port-knocking?name=MyName&married=not+single♂=yes HTTP/1.1
Host: merch1.localhost
User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
how can i get this input into a list.....?
i want like
a = ['GET /en/html/dummy.php?name=MyName&married=not+single&male=yes HTTP/1.1',
'Host: www.explainth.at',
'User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11',
'Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language: en-gb,en;q=0.5',
'Accept-Encoding: gzip,deflate',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7','Keep-Alive: 300']
this is an http request received from telnet.
i'm using EchoProtocol(basic.LineReceiver).
A:
Assuming you're getting those lines of text from a text file-like object f (maybe sys.stdin, whatever), list(f) or f.readlines() are almost what you want except that there are line-end markers at the end of each line. f.read().split('\n') may be closer to what you want (the same split call works if you have the text as a string s coming from some other source, s.split('\n') is the list you want).
A:
If you've read any of the LineReceiver documentation, then you should have seen that all received lines are passed to the lineReceived callback method of that class. So the answer to your question is a class that looks something like this:
from twisted.protocols.basic import LineReceiver
class LineCollector(LineReceiver):
def connectionMade(self):
self.lines = []
def lineReceived(self, line):
self.lines.append(line)
This gives you just what you asked for - your input in a list, one line per entry. However, it's far from clear why you want this. If you actually want to generate an HTTP response, this is the wrong way to go about doing so.
| Convert the input from telnet to a list in twisted | input from telnet
GET /learn/tutorials/351079-weekend-project-secure-your-system-with-port-knocking?name=MyName&married=not+single♂=yes HTTP/1.1
Host: merch1.localhost
User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
how can i get this input into a list.....?
i want like
a = ['GET /en/html/dummy.php?name=MyName&married=not+single&male=yes HTTP/1.1',
'Host: www.explainth.at',
'User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11',
'Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language: en-gb,en;q=0.5',
'Accept-Encoding: gzip,deflate',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7','Keep-Alive: 300']
this is an http request received from telnet.
i'm using EchoProtocol(basic.LineReceiver).
| [
"Assuming you're getting those lines of text from a text file-like object f (maybe sys.stdin, whatever), list(f) or f.readlines() are almost what you want except that there are line-end markers at the end of each line. f.read().split('\\n') may be closer to what you want (the same split call works if you have the ... | [
1,
0
] | [] | [] | [
"http",
"python",
"twisted"
] | stackoverflow_0003732345_http_python_twisted.txt |
Q:
Django - alert when memcached is down
Is there some ready-made addon that alerts admins about memcached instance being inaccessible from a Django application? I don't mean here monitoring memcached daemon itself, but something that checks if my Django app benefits from caching.
My basic idea is to check if cache.get that follow cache.set actually returns something, and if not - then send email to admins, but only one per hour, to not flood the inbox.
But maybe there is something more advanced out there ?
A:
You should monitor your infrastructure. You can use a huge variety of tools for this, look on server fault for more discussions on monitoring.
You should probably monitor your cache hit rate and trend it in your monitoring system; if it falls below a figure (say 90%) then you can alert that the cache has stopped working or something.
Memcached itself will have some way of monitoring hit rate, but that will be overall rather than for a specific part of your application. You probably want to monitor the hit rate for a specific cache instance in your code so you can be sure it's continuing to be effective.
A:
munin reports how memcached is used and can show hits vs misses and other usage data.
You can also set alerts to receive an email if some threshold went off.
| Django - alert when memcached is down | Is there some ready-made addon that alerts admins about memcached instance being inaccessible from a Django application? I don't mean here monitoring memcached daemon itself, but something that checks if my Django app benefits from caching.
My basic idea is to check if cache.get that follow cache.set actually returns something, and if not - then send email to admins, but only one per hour, to not flood the inbox.
But maybe there is something more advanced out there ?
| [
"You should monitor your infrastructure. You can use a huge variety of tools for this, look on server fault for more discussions on monitoring.\nYou should probably monitor your cache hit rate and trend it in your monitoring system; if it falls below a figure (say 90%) then you can alert that the cache has stopped ... | [
5,
2
] | [] | [] | [
"django",
"memcached",
"python",
"python_memcached"
] | stackoverflow_0003735183_django_memcached_python_python_memcached.txt |
Q:
Determine whether a key is present in a dictionary
Possible Duplicate:
'has_key()' or 'in'?
I have a Python dictionary like :
mydict = {'name':'abc','city':'xyz','country','def'}
I want to check if a key is in dictionary or not.
I am eager to know that which is more preferable from the following two cases and why?
1> if mydict.has_key('name'):
2> if 'name' in mydict:
A:
if 'name' in mydict:
is the preferred, pythonic version. Use of has_key() is discouraged, and this method has been removed in Python 3.
A:
In the same vein as martineau's response, the best solution is often not to check. For example, the code
if x in d:
foo = d[x]
else:
foo = bar
is normally written
foo = d.get(x, bar)
which is shorter and more directly speaks to what you mean.
Another common case is something like
if x not in d:
d[x] = []
d[x].append(foo)
which can be rewritten
d.setdefault(x, []).append(foo)
or rewritten even better by using a collections.defaultdict(list) for d and writing
d[x].append(foo)
A:
In terms of bytecode, in saves a LOAD_ATTR and replaces a CALL_FUNCTION with a COMPARE_OP.
>>> dis.dis(indict)
2 0 LOAD_GLOBAL 0 (name)
3 LOAD_GLOBAL 1 (d)
6 COMPARE_OP 6 (in)
9 POP_TOP
>>> dis.dis(haskey)
2 0 LOAD_GLOBAL 0 (d)
3 LOAD_ATTR 1 (haskey)
6 LOAD_GLOBAL 2 (name)
9 CALL_FUNCTION 1
12 POP_TOP
My feelings are that in is much more readable and is to be preferred in every case that I can think of.
In terms of performance, the timing reflects the opcode
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
10000000 loops, best of 3: 0.11 usec per loop
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
1000000 loops, best of 3: 0.205 usec per loop
in is almost twice as fast.
A:
My answer is "neither one".
I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.
This is usually done with enclosing the code in a try...except clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).
Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".
As a trivial example consider:
if 'name' in dct:
value = dct['name'] * 3
else:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
vs
try:
value = dct['name'] * 3
except KeyError:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).
Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict: is better for the reasons stated in the other answers.
If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).
| Determine whether a key is present in a dictionary |
Possible Duplicate:
'has_key()' or 'in'?
I have a Python dictionary like :
mydict = {'name':'abc','city':'xyz','country','def'}
I want to check if a key is in dictionary or not.
I am eager to know that which is more preferable from the following two cases and why?
1> if mydict.has_key('name'):
2> if 'name' in mydict:
| [
"if 'name' in mydict:\n\nis the preferred, pythonic version. Use of has_key() is discouraged, and this method has been removed in Python 3.\n",
"In the same vein as martineau's response, the best solution is often not to check. For example, the code\nif x in d:\n foo = d[x]\nelse:\n foo = bar\n\nis normally... | [
78,
38,
13,
10
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003733992_dictionary_python.txt |
Q:
Python unicode problems on Windows XP
Having the following django view code that generates a CSV response from a database view:
def _get_csv_stats(request, **filterargs):
result = GlobalStats.objects.select_related().filter(**filterargs).values_list('user__username',
'user__first_name','user__last_name',
'center__name', 'action_name',
'action_date').annotate(num = Count('id')).order_by("action_date")
response = HttpResponse(mimetype = 'text/csv')
response.write( codecs.BOM_UTF8 )
response['Content-Disposition'] = 'attachment; filename=statistcs.csv'
writer = UnicodeWriter(response)
for value in result:
writer.writerow([unicode(v) for v in value])
return response
Some of the columns contain utf8 text. When I download the file and open it using Linux or Mac OS X I can see the text properly. But downloading and opening the file using windows XP strange characters appear in the place of the non-ASCII text. Converting the file from csv to xls using Open Office on linux and opening the file on windows xp will result with a readable file (no strange characters).
I can't see what I'm missing here as I don't work with win XP. Has anyone experienced anything similar?
The UnicodeWriter class I'm using is descibed here at the bottom.
A:
Whether the text is displayed properly depends on whether the font that is is being drawn in supports all Unicode characters. This is not a problem with your django.
A:
First: I don't know django, so maybe this is far off.
Check whether your writer actually outputs UTF-8, if you write an UTF-8 BOM into the file. Unicode and UTF-8 are not the same. Also, afaikt, does Windows Notepad understand a UTF-8 BOM, so you getting "strange" characters can mean two things:
a) the rest of the file is not really UTF-8-encoded, try v.encode('utf-8') for that
b) the characters your trying to display are not supported by the font
| Python unicode problems on Windows XP | Having the following django view code that generates a CSV response from a database view:
def _get_csv_stats(request, **filterargs):
result = GlobalStats.objects.select_related().filter(**filterargs).values_list('user__username',
'user__first_name','user__last_name',
'center__name', 'action_name',
'action_date').annotate(num = Count('id')).order_by("action_date")
response = HttpResponse(mimetype = 'text/csv')
response.write( codecs.BOM_UTF8 )
response['Content-Disposition'] = 'attachment; filename=statistcs.csv'
writer = UnicodeWriter(response)
for value in result:
writer.writerow([unicode(v) for v in value])
return response
Some of the columns contain utf8 text. When I download the file and open it using Linux or Mac OS X I can see the text properly. But downloading and opening the file using windows XP strange characters appear in the place of the non-ASCII text. Converting the file from csv to xls using Open Office on linux and opening the file on windows xp will result with a readable file (no strange characters).
I can't see what I'm missing here as I don't work with win XP. Has anyone experienced anything similar?
The UnicodeWriter class I'm using is descibed here at the bottom.
| [
"Whether the text is displayed properly depends on whether the font that is is being drawn in supports all Unicode characters. This is not a problem with your django.\n",
"First: I don't know django, so maybe this is far off.\nCheck whether your writer actually outputs UTF-8, if you write an UTF-8 BOM into the fi... | [
0,
0
] | [] | [] | [
"django",
"python",
"unicode",
"windows"
] | stackoverflow_0003187295_django_python_unicode_windows.txt |
Q:
Python lxml and stdin
I have a xml file, book.xml (http://msdn.microsoft.com/en-us/library/ms762271(VS.85).aspx)
I would like to cat books.xml and get all book ids and genres for the book id.
Similar to
cat books.xml | python reader.py
Any tips or help would be appreciated. Thanks.
A:
To read an XML file from stdin, just use etree.parse. This function accepts a file object, which can be sys.stdin.
import sys
from lxml import etree
tree = etree.parse(sys.stdin)
print ( [(b.get('id'), b.findtext('genre')) for b in tree.iterfind('book')] )
| Python lxml and stdin | I have a xml file, book.xml (http://msdn.microsoft.com/en-us/library/ms762271(VS.85).aspx)
I would like to cat books.xml and get all book ids and genres for the book id.
Similar to
cat books.xml | python reader.py
Any tips or help would be appreciated. Thanks.
| [
"To read an XML file from stdin, just use etree.parse. This function accepts a file object, which can be sys.stdin.\nimport sys\nfrom lxml import etree\n\ntree = etree.parse(sys.stdin)\n\nprint ( [(b.get('id'), b.findtext('genre')) for b in tree.iterfind('book')] )\n\n"
] | [
12
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0003735364_lxml_python_xml.txt |
Q:
How to display a PostScript file in a Python GUI application
I would like to build a cross-platform GUI application in Python that displays PostScript files I generate, among some other stuff. What is the best way to accomplish this? Ideally I would be able to do things like zoom and pan the displayed graphic.
Do any/some/all of the GUI toolkits have something I can drop in to do this, and if so what are they called and how do they work? If necessary, I can convert the postscript file to PDF or a raster format behind the scenes, but I'd rather not do the latter.
A:
I asked pretty much the same question a little time ago. Here it is. Hope it helps.
Note: Poppler is highly undocumented. If you use Gtk for your GUI there are a few working examples. In Qt things are a little harder, and I haven't figured out a way myself yet.
A:
In a word Ghostscript. It's been a while since I used it, but it's cross-platform and you can use it to generate image files which your app could then display, pan, and zoom. I used it to develop and test some pretty involved commercial Postscript code for my own products and under contract for others. It's open source, which came in handy for a couple of use cases I had. Nowdays I believe it does PDF, too.
| How to display a PostScript file in a Python GUI application | I would like to build a cross-platform GUI application in Python that displays PostScript files I generate, among some other stuff. What is the best way to accomplish this? Ideally I would be able to do things like zoom and pan the displayed graphic.
Do any/some/all of the GUI toolkits have something I can drop in to do this, and if so what are they called and how do they work? If necessary, I can convert the postscript file to PDF or a raster format behind the scenes, but I'd rather not do the latter.
| [
"I asked pretty much the same question a little time ago. Here it is. Hope it helps.\nNote: Poppler is highly undocumented. If you use Gtk for your GUI there are a few working examples. In Qt things are a little harder, and I haven't figured out a way myself yet.\n",
"In a word Ghostscript. It's been a while sinc... | [
1,
1
] | [] | [] | [
"postscript",
"python",
"user_interface"
] | stackoverflow_0002534474_postscript_python_user_interface.txt |
Q:
mixing super and classic calls in Python
firstly, let me quote a bit an essay from "Expert Python Programming" book:
In the following example, a C class that calls its base classes using the __init__ method will
make B class be called twice!
class A(object):
def __init__(self):
print "A"
super(A, self).__init__()
class B(object):
def __init__(self):
print "B"
super(B, self).__init__()
class C(A,B):
def __init__(self):
print "C"
A.__init__(self)
B.__init__(self)
print "MRO:", [x.__name__ for x in C.__mro__] #prints MRO: ['C', 'A', 'B', 'object']
C() #prints C A B B
and finally, here is an explanation of what's going on here:
This happens due to the A.__init__(self) call, which is made with the C instance,
thus making super(A, self).__init__() call B's constructor. In other words,
super should be used into the whole class hierarchy. The problem is that sometimes
a part of this hierarchy is located in third-party code.
i have no idea why "super(A, self).__init__() calls B's constructor". Please explain this moment. Thanks a lot.
A:
To understand this behaviour, you have to understand that super calls not the base class, but searches the next matching method along the order in the __mro__. So, the call super(A, self).__init__() looks at the __mro__ == ['C', 'A', 'B', 'object'], sees B as the next class with a matching method and calls the method (constructor) of B.
If you change C to
class C(A,B):
def __init__(self):
print "C1"
A.__init__(self)
print "C2"
B.__init__(self)
print "C3"
you get
MRO: ['C', 'A', 'B', 'object']
C1
A
B
C2
B
C3
which shows how the constructor of A calls B.
A:
The documentation for super says that:
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
When you execute A.__init__(self) from within C the super(A, self) will return <super: <class 'A'>, <C object>>. As the instance is C (<C object>) all the classes in C's inheritance hierarchy are picked up. And the __init__ call is issued on all of them. Consequently you see 'B' getting called twice.
To verify this add another class 'Z' and let 'C' inherit from 'Z' as well. See what happens.
class Z(object):
def __init__(self):
print "Z"
super(Z, self).__init__()
class C(A, B, Z):
def __init__(self):
print "C"
A.__init__(self)
B.__init__(self)
Z.__init__(self)
In this case, A will call B and Z. B will call Z as well.
| mixing super and classic calls in Python | firstly, let me quote a bit an essay from "Expert Python Programming" book:
In the following example, a C class that calls its base classes using the __init__ method will
make B class be called twice!
class A(object):
def __init__(self):
print "A"
super(A, self).__init__()
class B(object):
def __init__(self):
print "B"
super(B, self).__init__()
class C(A,B):
def __init__(self):
print "C"
A.__init__(self)
B.__init__(self)
print "MRO:", [x.__name__ for x in C.__mro__] #prints MRO: ['C', 'A', 'B', 'object']
C() #prints C A B B
and finally, here is an explanation of what's going on here:
This happens due to the A.__init__(self) call, which is made with the C instance,
thus making super(A, self).__init__() call B's constructor. In other words,
super should be used into the whole class hierarchy. The problem is that sometimes
a part of this hierarchy is located in third-party code.
i have no idea why "super(A, self).__init__() calls B's constructor". Please explain this moment. Thanks a lot.
| [
"To understand this behaviour, you have to understand that super calls not the base class, but searches the next matching method along the order in the __mro__. So, the call super(A, self).__init__() looks at the __mro__ == ['C', 'A', 'B', 'object'], sees B as the next class with a matching method and calls the met... | [
10,
4
] | [] | [] | [
"python"
] | stackoverflow_0003735569_python.txt |
Q:
Split with single colon but not double colon using regex
I have a string like this
"yJdz:jkj8h:jkhd::hjkjh"
I want to split it using colon as a separator, but not a double colon. Desired result:
("yJdz", "jkj8h", "jkhd::hjkjh")
I'm trying with:
re.split(":{1}", "yJdz:jkj8h:jkhd::hjkjh")
but I got a wrong result.
In the meanwhile I'm escaping "::", with string.replace("::", "$$")
A:
You could split on (?<!:):(?!:). This uses two negative lookarounds (a lookbehind and a lookahead) which assert that a valid match only has one colon, without a colon before or after it.
To explain the pattern:
(?<!:) # assert that the previous character is not a colon
: # match a literal : character
(?!:) # assert that the next character is not a colon
Both lookarounds are needed, because if there was only the lookbehind, then the regular expression engine would match the first colon in :: (because the previous character isn't a colon), and if there was only the lookahead, the second colon would match (because the next character isn't a colon).
A:
You can do this with lookahead and lookbehind, if you want:
>>> s = "yJdz:jkj8h:jkhd::hjkjh"
>>> l = re.split("(?<!:):(?!:)", s)
>>> print l
['yJdz', 'jkj8h', 'jkhd::hjkjh']
This regex essentially says "match a : that is not followed by a : or preceded by a :"
| Split with single colon but not double colon using regex | I have a string like this
"yJdz:jkj8h:jkhd::hjkjh"
I want to split it using colon as a separator, but not a double colon. Desired result:
("yJdz", "jkj8h", "jkhd::hjkjh")
I'm trying with:
re.split(":{1}", "yJdz:jkj8h:jkhd::hjkjh")
but I got a wrong result.
In the meanwhile I'm escaping "::", with string.replace("::", "$$")
| [
"You could split on (?<!:):(?!:). This uses two negative lookarounds (a lookbehind and a lookahead) which assert that a valid match only has one colon, without a colon before or after it.\nTo explain the pattern:\n(?<!:) # assert that the previous character is not a colon\n: # match a literal : character\n(?... | [
31,
13
] | [] | [] | [
"python",
"regex",
"split"
] | stackoverflow_0003735841_python_regex_split.txt |
Q:
SQL in Python 3.0?
How to use any SQL database eg. mysql, pgsql or other except the ones Python has built-in support for?
def example():
con= Mysql("root", blablabla)
con->query("SELECT * bla bla bla")
....
A:
What DB and what extension are you using? For sqlite3 (and any other extension compatible with DB-API 2.0) you can use something like this:
conn = sqlite3.connect('/tmp/example')
c = conn.cursor()
# Create table
c.execute('''create table stocks(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
c.execute("""insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)""")
# Save (commit) the changes
conn.commit()
# We can also close the cursor if we are done with it
c.close()
BTW, there is no ->in Python
A:
There is a list of Python 3.x compatible packages here: http://pypi.python.org/pypi?:action=browse&c=533&show=all
All I could find was oursql and py-postgresql
| SQL in Python 3.0? | How to use any SQL database eg. mysql, pgsql or other except the ones Python has built-in support for?
def example():
con= Mysql("root", blablabla)
con->query("SELECT * bla bla bla")
....
| [
"What DB and what extension are you using? For sqlite3 (and any other extension compatible with DB-API 2.0) you can use something like this:\nconn = sqlite3.connect('/tmp/example')\nc = conn.cursor()\n\n# Create table\nc.execute('''create table stocks(date text, trans text, symbol text, qty real, price real)''')\n\... | [
3,
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0003735948_python_sql.txt |
Q:
How do I test a WSGI application from a script?
I'm debugging a really weird problem with a mod_wsgi-deployed application resulting in Django/Apache (not yet known which) giving status 500 errors to some users instead of the correct 404. I want to exclude Apache from the debugging environment to determine which part of the setup is at fault and send my requests manually to the WSGI handler.
I suspect it's as easy as setting the environment and running python wsgi_handler.py, but is this correct? What should the enviroment contain additionally? Any pointers to existing documentation?
A:
it's as easy as setting the environment and running python wsgi_handler.py,
Correct.
What should the enviroment contain additionally? Any pointers to existing documentation?
Did you read this? http://docs.python.org/library/wsgiref.html
You can easily run a web server from your desktop for testing. It's a very few lines of code.
http://docs.python.org/library/wsgiref.html#wsgiref.simple_server.make_server
| How do I test a WSGI application from a script? | I'm debugging a really weird problem with a mod_wsgi-deployed application resulting in Django/Apache (not yet known which) giving status 500 errors to some users instead of the correct 404. I want to exclude Apache from the debugging environment to determine which part of the setup is at fault and send my requests manually to the WSGI handler.
I suspect it's as easy as setting the environment and running python wsgi_handler.py, but is this correct? What should the enviroment contain additionally? Any pointers to existing documentation?
| [
"\nit's as easy as setting the environment and running python wsgi_handler.py, \n\nCorrect.\n\nWhat should the enviroment contain additionally? Any pointers to existing documentation?\n\nDid you read this? http://docs.python.org/library/wsgiref.html\nYou can easily run a web server from your desktop for testing. I... | [
4
] | [] | [] | [
"django",
"python",
"testing",
"wsgi"
] | stackoverflow_0003735637_django_python_testing_wsgi.txt |
Q:
How can I remove the axes in an Axes3D class?
I am using mplot3d like this:
fig = plt.figure(figsize=(14,10))
ax = Axes3D(fig,azim=azimuth,elev=elevation)
ax.grid(on=False)
# Additional axes
xspan = np.linspace(0,80+20)
yspan = np.linspace(0,60+20)
zspan = np.linspace(0,60+20)
ax.plot3D(xspan,np.zeros(xspan.shape[0]),np.zeros(xspan.shape[0]),'k--')
ax.plot3D(np.zeros(yspan.shape[0]),yspan,np.zeros(yspan.shape[0]),'k--')
ax.plot3D(np.zeros(zspan.shape[0]),np.zeros(zspan.shape[0]),zspan,'k--')
ax.text(xspan[-1]+10, .5, .5, "x", color='red')
ax.text(.5, yspan[-1]+10, .5, "y", color='red')
ax.text(.5, .5, zspan[-1]+10, "z", color='red')
NZindices = np.nonzero(t2)[0]
#print "Nonzero values of T^2", len(NZindices), "out of", X.shape[0]
ONZ_X, ONZ_Y, ONZ_Z, ONZ_p = [],[],[],[]
INZ_X, INZ_Y, INZ_Z, INZ_p = [],[],[],[]
# Separate indices I/O
for ind in NZindices:
if ind <= HALF_INDICES:
INZ_X.append( X[ind] )
INZ_Y.append( Y[ind] )
INZ_Z.append( Z[ind] )
INZ_p.append( t2[ind] )
else:
ONZ_X.append( X[ind] )
ONZ_Y.append( Y[ind] )
ONZ_Z.append( Z[ind] )
ONZ_p.append( t2[ind] )
cax = ax.scatter(ONZ_X, ONZ_Y, ONZ_Z, c=ONZ_p, marker='o', s=20 )
cax = ax.scatter(INZ_X, INZ_Y, INZ_Z, c=INZ_p, marker='<', s=20 )
fig.colorbar( cax, shrink=0.7 )
success = float(len(NZindices))/X.shape[0]*100
fig.savefig(fname)
#plt.show()
plt.clf()
plt.close()
I want to remove the original (x,y,z) axes that come by default in Axes3D. Any ideas? Thanks!
A:
If I understand your question correctly, all you need to do is call ax.axis("off") or equivalently, ax.set_axis_off().
Just to make sure we're on the same page, your example code might produce something like this (if it could be executed as you posted it...):
While you want something like this:
Here's the code to generate the example below, for future reference:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = Axes3D(fig)
# Draw x, y, and z axis markers in the same way you were in
# the code snippet in your question...
xspan, yspan, zspan = 3 * [np.linspace(0,60,20)]
zero = np.zeros_like(xspan)
ax.plot3D(xspan, zero, zero,'k--')
ax.plot3D(zero, yspan, zero,'k--')
ax.plot3D(zero, zero, zspan,'k--')
ax.text(xspan.max() + 10, .5, .5, "x", color='red')
ax.text(.5, yspan.max() + 10, .5, "y", color='red')
ax.text(.5, .5, zspan.max() + 10, "z", color='red')
# Generate and plot some random data...
ndata = 10
x = np.random.uniform(xspan.min(), xspan.max(), ndata)
y = np.random.uniform(yspan.min(), yspan.max(), ndata)
z = np.random.uniform(zspan.min(), zspan.max(), ndata)
c = np.random.random(ndata)
ax.scatter(x, y, z, c=c, marker='o', s=20)
# This line is the only difference between the two plots above!
ax.axis("off")
plt.show()
| How can I remove the axes in an Axes3D class? | I am using mplot3d like this:
fig = plt.figure(figsize=(14,10))
ax = Axes3D(fig,azim=azimuth,elev=elevation)
ax.grid(on=False)
# Additional axes
xspan = np.linspace(0,80+20)
yspan = np.linspace(0,60+20)
zspan = np.linspace(0,60+20)
ax.plot3D(xspan,np.zeros(xspan.shape[0]),np.zeros(xspan.shape[0]),'k--')
ax.plot3D(np.zeros(yspan.shape[0]),yspan,np.zeros(yspan.shape[0]),'k--')
ax.plot3D(np.zeros(zspan.shape[0]),np.zeros(zspan.shape[0]),zspan,'k--')
ax.text(xspan[-1]+10, .5, .5, "x", color='red')
ax.text(.5, yspan[-1]+10, .5, "y", color='red')
ax.text(.5, .5, zspan[-1]+10, "z", color='red')
NZindices = np.nonzero(t2)[0]
#print "Nonzero values of T^2", len(NZindices), "out of", X.shape[0]
ONZ_X, ONZ_Y, ONZ_Z, ONZ_p = [],[],[],[]
INZ_X, INZ_Y, INZ_Z, INZ_p = [],[],[],[]
# Separate indices I/O
for ind in NZindices:
if ind <= HALF_INDICES:
INZ_X.append( X[ind] )
INZ_Y.append( Y[ind] )
INZ_Z.append( Z[ind] )
INZ_p.append( t2[ind] )
else:
ONZ_X.append( X[ind] )
ONZ_Y.append( Y[ind] )
ONZ_Z.append( Z[ind] )
ONZ_p.append( t2[ind] )
cax = ax.scatter(ONZ_X, ONZ_Y, ONZ_Z, c=ONZ_p, marker='o', s=20 )
cax = ax.scatter(INZ_X, INZ_Y, INZ_Z, c=INZ_p, marker='<', s=20 )
fig.colorbar( cax, shrink=0.7 )
success = float(len(NZindices))/X.shape[0]*100
fig.savefig(fname)
#plt.show()
plt.clf()
plt.close()
I want to remove the original (x,y,z) axes that come by default in Axes3D. Any ideas? Thanks!
| [
"If I understand your question correctly, all you need to do is call ax.axis(\"off\") or equivalently, ax.set_axis_off().\nJust to make sure we're on the same page, your example code might produce something like this (if it could be executed as you posted it...):\n\nWhile you want something like this:\n\nHere's the... | [
10
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003732787_matplotlib_python.txt |
Q:
Need regular expression expert: round bracket within stringliteral
I'm searching for strings within strings using Regex. The pattern is a string literal that ends in (, e.g.
# pattern
" before the bracket ("
# string
this text is before the bracket (and this text is inside) and this text is after the bracket
I know the pattern will work if I escape the character with a backslash, i.e.:
# pattern
" before the bracket \\("
But the pattern strings are coming from another search and I can not control what characters will be or where. Is there a way of escaping an entire string literal so that anything between markers is treated as a string? For example:
# pattern
\" before the ("
The only other option I have is to do a substitute adding escapes for every protected character.
re.escape is exactly what I need. I'm using regexp in Access VBA which doens't have that method. I only have replace, execute or test methods.
Is there a way to escape everything within a string in VBA?
Thanks
A:
You didn't specify the language, but it looks like Python, so if you have a string in Python whose special regex characters you need to escape, use re.escape():
>>> import re
>>> re.escape("Wow. This (really) is *cool*")
'Wow\\.\\ This\\ \\(really\\)\\ is\\ \\*cool\\*'
Note that spaces are escaped, too (probably to ensure that they still work in a re.VERBOSE regex).
A:
Maybe write your own VBA escape function:
Function EscapeRegEx(text As String) As String
Dim regEx As RegExp
Set regEx = New RegExp
regEx.Global = True
regEx.Pattern = "(\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\)|\{|\})"
EscapeRegEx = regEx.Replace(text, "\$1")
End Function
A:
I'm pretty sure that with the limitations of the RegExp abilities in VBA/VBScript, you are going to have to replace the special characters in your pattern before using it. There doesn't seem to be anything built into it like there is in Python.
| Need regular expression expert: round bracket within stringliteral | I'm searching for strings within strings using Regex. The pattern is a string literal that ends in (, e.g.
# pattern
" before the bracket ("
# string
this text is before the bracket (and this text is inside) and this text is after the bracket
I know the pattern will work if I escape the character with a backslash, i.e.:
# pattern
" before the bracket \\("
But the pattern strings are coming from another search and I can not control what characters will be or where. Is there a way of escaping an entire string literal so that anything between markers is treated as a string? For example:
# pattern
\" before the ("
The only other option I have is to do a substitute adding escapes for every protected character.
re.escape is exactly what I need. I'm using regexp in Access VBA which doens't have that method. I only have replace, execute or test methods.
Is there a way to escape everything within a string in VBA?
Thanks
| [
"You didn't specify the language, but it looks like Python, so if you have a string in Python whose special regex characters you need to escape, use re.escape():\n>>> import re\n>>> re.escape(\"Wow. This (really) is *cool*\")\n'Wow\\\\.\\\\ This\\\\ \\\\(really\\\\)\\\\ is\\\\ \\\\*cool\\\\*'\n\nNote that spaces ar... | [
2,
1,
0
] | [
"The following regex will capture everything from the beginning of the string to the first (. The first captured group $1 will contain the portion before (.\n^([^(]+)\\(\n\nDepending on your language, you might have to escape it as:\n\"^([^(]+)\\\\(\"\n\n"
] | [
-1
] | [
"python",
"regex",
"vba"
] | stackoverflow_0003723038_python_regex_vba.txt |
Q:
Add advanced features to a tkinter Text widget
I am working on a simple messaging system, and need to add the following to a Tkinter text widget:
Spell Check
Option To Change Font ( on selected text )
Option to change font color ( on selected text )
Option to Change Font Size ( on selected text )
I understand that the tkinter Text widget has the ability to use multiple fonts and colors through the tagging mechanism, but I don't understand how to make use of those capabilities.
How can I implement those features using the features of the Text widget? Specifically, how can I change the font family, color and size of words, and how could I use that to implement something like spellcheck, where misspelled words are underlined or colored differently than the rest of the text.
A:
The Tkinter text widget is remarkably powerful, but you do have to do some advanced features yourself. It doesn't have built-in spell check or built-in buttons for bolding text, etc, but they are quite easy to implement. All the capabilities are there in the widget, you just need to know how to do it.
The following example gives you a button to toggle the bold state of the highlighted text -- select a range of characters then click the button to add and then remove the bold attribute. It should be pretty easy for you to extend this example for fonts and colors.
Spell check is also pretty easy. the following example uses the words in /usr/share/dict/words (which almost certainly doesn't exist on Windows 7, so you'll need to supply a suitable list of words) It's rather simplistic in that it only spell-checks when you press the space key, but that's only to keep the code size of the example to a minimal level. In the real world you'll want to be a bit more smart about when you do the spell checking.
import Tkinter as tk
import tkFont
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
## Toolbar
self.toolbar = tk.Frame()
self.bold = tk.Button(name="toolbar", text="bold",
borderwidth=1, command=self.OnBold,)
self.bold.pack(in_=self.toolbar, side="left")
## Main part of the GUI
# I'll use a frame to contain the widget and
# scrollbar; it looks a little nicer that way...
text_frame = tk.Frame(borderwidth=1, relief="sunken")
self.text = tk.Text(wrap="word", background="white",
borderwidth=0, highlightthickness=0)
self.vsb = tk.Scrollbar(orient="vertical", borderwidth=1,
command=self.text.yview)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(in_=text_frame,side="right", fill="y", expand=False)
self.text.pack(in_=text_frame, side="left", fill="both", expand=True)
self.toolbar.pack(side="top", fill="x")
text_frame.pack(side="bottom", fill="both", expand=True)
# clone the text widget font and use it as a basis for some
# tags
bold_font = tkFont.Font(self.text, self.text.cget("font"))
bold_font.configure(weight="bold")
self.text.tag_configure("bold", font=bold_font)
self.text.tag_configure("misspelled", foreground="red", underline=True)
# set up a binding to do simple spell check. This merely
# checks the previous word when you type a space. For production
# use you'll need to be a bit more intelligent about when
# to do it.
self.text.bind("<space>", self.Spellcheck)
# initialize the spell checking dictionary. YMMV.
self._words=open("/usr/share/dict/words").read().split("\n")
def Spellcheck(self, event):
'''Spellcheck the word preceeding the insertion point'''
index = self.text.search(r'\s', "insert", backwards=True, regexp=True)
if index == "":
index ="1.0"
else:
index = self.text.index("%s+1c" % index)
word = self.text.get(index, "insert")
if word in self._words:
self.text.tag_remove("misspelled", index, "%s+%dc" % (index, len(word)))
else:
self.text.tag_add("misspelled", index, "%s+%dc" % (index, len(word)))
def OnBold(self):
'''Toggle the bold state of the selected text'''
# toggle the bold state based on the first character
# in the selected range. If bold, unbold it. If not
# bold, bold it.
current_tags = self.text.tag_names("sel.first")
if "bold" in current_tags:
# first char is bold, so unbold the range
self.text.tag_remove("bold", "sel.first", "sel.last")
else:
# first char is normal, so bold the whole selection
self.text.tag_add("bold", "sel.first", "sel.last")
if __name__ == "__main__":
app=App()
app.mainloop()
A:
1) Tk does'nt have an integrated spellchecker. You may be interested by PyEnchant.
2) 3) 4) is not that difficult (please forget my previous suggestion to use wxPython). You can pass a tag_config as 3rd arg of the insert method of the text widget. It defines the config of this selection.
See the following code which is adapted from the Scrolledtext example and effbot which the best reference about Tk.
"""
Some text
hello
"""
from Tkinter import *
from Tkconstants import RIGHT, LEFT, Y, BOTH
from tkFont import Font
from ScrolledText import ScrolledText
def example():
import __main__
from Tkconstants import END
stext = ScrolledText(bg='white', height=10)
stext.insert(END, __main__.__doc__)
f = Font(family="times", size=30, weight="bold")
stext.tag_config("font", font=f)
stext.insert(END, "Hello", "font")
stext.pack(fill=BOTH, side=LEFT, expand=True)
stext.focus_set()
stext.mainloop()
if __name__ == "__main__":
example()
| Add advanced features to a tkinter Text widget | I am working on a simple messaging system, and need to add the following to a Tkinter text widget:
Spell Check
Option To Change Font ( on selected text )
Option to change font color ( on selected text )
Option to Change Font Size ( on selected text )
I understand that the tkinter Text widget has the ability to use multiple fonts and colors through the tagging mechanism, but I don't understand how to make use of those capabilities.
How can I implement those features using the features of the Text widget? Specifically, how can I change the font family, color and size of words, and how could I use that to implement something like spellcheck, where misspelled words are underlined or colored differently than the rest of the text.
| [
"The Tkinter text widget is remarkably powerful, but you do have to do some advanced features yourself. It doesn't have built-in spell check or built-in buttons for bolding text, etc, but they are quite easy to implement. All the capabilities are there in the widget, you just need to know how to do it.\nThe followi... | [
37,
5
] | [] | [] | [
"message",
"python",
"text",
"tkinter",
"windows"
] | stackoverflow_0003732605_message_python_text_tkinter_windows.txt |
Q:
How do I read an image file using Python?
How do I read an image file and decode it using Python?
A:
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpgfile.size, jpgfile.format)
| How do I read an image file using Python? | How do I read an image file and decode it using Python?
| [
"The word \"read\" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it. \nfrom PIL import Image\njpgfile = Image.open(\"picture.jpg\")\n\nprint(jpgfile.bits, jpgfile.size, jpgfile.format)\n\n"
] | [
53
] | [] | [] | [
"file",
"image",
"python"
] | stackoverflow_0003735553_file_image_python.txt |
Q:
Distinguishable characters?
I have a bunch of items in my database. Each is assigned a unique ID. I want to shorten this ID and display it on the page, so that if I user needs to contact us (over the phone) regarding a particular item, he can give us the shortened ID, rather than a really big number. Similar to the SKU, on sites like NCIX. Thus, I was thinking about encoding it in base 36. The problem with that, however, is letters like 1lI all look kind of the same. So, I was thinking about eliminating the look-alikes. Is this a good idea, or should I just use a really legible font?
A:
Yes, you should eliminate sources of confusion. Because if a mistake can be made, someone will make it. Very easy to confuse 0 with O and I with l or 1 - hence should not use them both. Well that's easy - since you won't use 3 chars (i, L and o), just get the number in base 36-3 = 33 and convert
SKU.replace('I','X').replace('L','Y').replace('O','Z')
Inversely when given such code and before doing int(SKU, 33), you will have to return XYZ back to the confusing characters. Before that though, if - as expected - you are given by mistake L or I, replace with 1 and if given O, replace with 0. E.g. use SKU.translate() with
string.maketrans('LIOXYZ','110IL0')
A:
I'm assuming the original ID is numeric. We've had good results from z-base-32 with a similar scenario. We've been using it since April 2009.
I particularly liked the encoding's goals of minimizing transcription errors, through removing confusing letters from the alphabet, and brevity, as shorter identifiers are easier to use.
The encoding orders the alphabet so that the more commonly occurring characters are those that are easier to read, write, speak and remember. Lower case is used as it's easier to read.
I asked this similar question before we decided to use z-base-32.
A:
Use a legible font.
A:
We had a similar situation in a regular app many years ago, at a company I worked for. There was an ID, base 36 (0-9a-z) that often had to be communicated over the phone. That was an application running on a Unix server and viewed on serial terminals (not relevant, just part of the story :).
Our solution was that whenever the user was on that field and pressed F2, a small window popped-up having the radio code for the field: “a9vg5” would display “alpha niner victor golf five”, which the user would just read aloud.
When the application was developed, I had the inclination to display the ID as base 64 encoded, with capitals plus dot and slash, and use different radio-code words for the capitals, but the designated analyst disagreed. You could look-up different words in Wikipedia or be creative.
PS a clarification: although it's not clear the way I wrote it, the analyst disagreed with a good reason, since one has to think both sides of the communication; the user just reads, but the other side on the phone has to remember or look up that e.g. delta==d and Dalton==D.
| Distinguishable characters? | I have a bunch of items in my database. Each is assigned a unique ID. I want to shorten this ID and display it on the page, so that if I user needs to contact us (over the phone) regarding a particular item, he can give us the shortened ID, rather than a really big number. Similar to the SKU, on sites like NCIX. Thus, I was thinking about encoding it in base 36. The problem with that, however, is letters like 1lI all look kind of the same. So, I was thinking about eliminating the look-alikes. Is this a good idea, or should I just use a really legible font?
| [
"Yes, you should eliminate sources of confusion. Because if a mistake can be made, someone will make it. Very easy to confuse 0 with O and I with l or 1 - hence should not use them both. Well that's easy - since you won't use 3 chars (i, L and o), just get the number in base 36-3 = 33 and convert\nSKU.replace('I','... | [
6,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003082812_python.txt |
Q:
Handle user-raised deprecation warning by pylint
Is there a way to tell pylint that it must show warning message when it see user-defined deprecation warning?
I've tried warnings.warn, DeprecationWarning - but pylint ignores them.
A:
Since warnings.warn &c are intended to happen at runtime, Pylint by default doesn't see them as anything strange. To change that I think you need to follow the (advanced and scarce) docs for writing your own checker, with which you can emit warnings on any characteristics of the sources (either the raw ones or the AST-compiled level thereof).
| Handle user-raised deprecation warning by pylint | Is there a way to tell pylint that it must show warning message when it see user-defined deprecation warning?
I've tried warnings.warn, DeprecationWarning - but pylint ignores them.
| [
"Since warnings.warn &c are intended to happen at runtime, Pylint by default doesn't see them as anything strange. To change that I think you need to follow the (advanced and scarce) docs for writing your own checker, with which you can emit warnings on any characteristics of the sources (either the raw ones or th... | [
2
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0003736203_pylint_python.txt |
Q:
How to determine if CherryPy is caching responses?
Is it possible that CherryPy, in its default configuration, is caching the responses to one or more of my request handlers? And, if so, how do I turn that off?
A:
Per the docs, there is indeed a cache (for GET), and you can disable it by having in your configuration
tools.caching.on = False
A:
CherryPy has a caching Tool, but it's never on by default. Most HTTP responses are cacheable by default, though, so look for an intermediate cache between your client and server. Look at the browser first.
If you're not sure whether or not your content is being cached, compare the Date response header to the current time.
| How to determine if CherryPy is caching responses? | Is it possible that CherryPy, in its default configuration, is caching the responses to one or more of my request handlers? And, if so, how do I turn that off?
| [
"Per the docs, there is indeed a cache (for GET), and you can disable it by having in your configuration\ntools.caching.on = False\n\n",
"CherryPy has a caching Tool, but it's never on by default. Most HTTP responses are cacheable by default, though, so look for an intermediate cache between your client and serve... | [
6,
4
] | [] | [] | [
"cherrypy",
"http",
"python"
] | stackoverflow_0003736606_cherrypy_http_python.txt |
Q:
Access an injected object's containing object?
Given an object A, which contains a callable object B, is there a way to determine "A" from inside B.__call__()?
This is for use in test injection, where A.B is originally a method.
The code is something like this:
# Class to be tested.
class Outer(object):
def __init__(self, arg):
self.arg = arg
def func(self, *args, **kwargs):
print ('Outer self: %r' % (self,))
# Framework-provided:
class Injected(object):
def __init__(self):
self._replay = False
self._calls = []
def replay(self):
self._replay = True
self._calls.reverse()
def __call__(self, *args, **kwargs):
if not self._replay:
expected = (args[0], args[1:], kwargs)
self._calls.append(expected)
else:
expected_s, expected_a, expected_k = self._calls.pop()
ok = True
# verify args, similar for expected_k == kwargs
ok = reduce(lambda x, comp: x and comp[0](comp[1]),
zip(expected_a, args),
ok)
# what to do for expected_s == self?
# ok = ok and expected_s(this) ### <= need "this". ###
if not ok:
raise Exception('Expectations not matched.')
# Inject:
setattr(Outer, 'func', Injected())
# Set expectations:
# - One object, initialised with "3", must pass "here" as 2nd arg.
# - One object, initialised with "4", must pass "whatever" as 1st arg.
Outer.func(lambda x: x.arg == 3, lambda x: True, lambda x: x=='here')
Outer.func(lambda x: x.arg == 4, lambda x: x=='whatever', lambda x: True)
Outer.func.replay()
# Invoke other code, which ends up doing:
o = Outer(3)
p = Outer(5)
o.func('something', 'here')
p.func('whatever', 'next') # <- This should fail, 5 != 4
The question is: Is there a way (black magic is fine) within Injected.__call__() to access what "self" would have been in non-overwritten Outer.func(), to use as "this" (line marked with "###")?
Naturally, the code is a bit more complex (the calls can be configured to be in arbitrary order, return values can be set, etc.), but this is the minimal example I could come up with that demonstrates both the problem and most of the constraints.
I cannot inject a function with a default argument instead of Outer.func - that breaks recording (if a function were injected, it'd be an unbound method and require an instance of "Outer" as its first argument, rather than a comparator/validator).
Theoretically, I could mock out "Outer" completely for its caller. However, setting up the expectations there would probably be more code, and not reusable elsewhere - any similar case/project would also have to reimplement "Outer" (or its equivalent) as a mock.
A:
Given an object A, which contains a
callable object B, is there a way to
determine "A" from inside
B.call()?
Not in the general case, i.e., with the unbounded generality you require in this text -- unless B keeps a reference to A in some way, Python most surely doesn't keep it on B's behalf.
For your intended use case, it's even worse: it wouldn't help even if B itself did keep a reference to A (as a method object would to its class), since you're trampling all over B without recourse with that setattr, which is equivalent to an assignment. There is no trace left in class Outer that, back in happier times, it had a func attribute with certain characteristics: that attribute is no more, obliterated by your setattr.
This isn't really dependency injection (a design pattern requiring cooperation from the injected-into object), it's monkey patching, one of my pet peeves, and its destructive, non-recoverable nature (that you're currently struggling with) is part of why I peeve about it.
A:
Perhaps you want the Python descriptor protocol?
| Access an injected object's containing object? | Given an object A, which contains a callable object B, is there a way to determine "A" from inside B.__call__()?
This is for use in test injection, where A.B is originally a method.
The code is something like this:
# Class to be tested.
class Outer(object):
def __init__(self, arg):
self.arg = arg
def func(self, *args, **kwargs):
print ('Outer self: %r' % (self,))
# Framework-provided:
class Injected(object):
def __init__(self):
self._replay = False
self._calls = []
def replay(self):
self._replay = True
self._calls.reverse()
def __call__(self, *args, **kwargs):
if not self._replay:
expected = (args[0], args[1:], kwargs)
self._calls.append(expected)
else:
expected_s, expected_a, expected_k = self._calls.pop()
ok = True
# verify args, similar for expected_k == kwargs
ok = reduce(lambda x, comp: x and comp[0](comp[1]),
zip(expected_a, args),
ok)
# what to do for expected_s == self?
# ok = ok and expected_s(this) ### <= need "this". ###
if not ok:
raise Exception('Expectations not matched.')
# Inject:
setattr(Outer, 'func', Injected())
# Set expectations:
# - One object, initialised with "3", must pass "here" as 2nd arg.
# - One object, initialised with "4", must pass "whatever" as 1st arg.
Outer.func(lambda x: x.arg == 3, lambda x: True, lambda x: x=='here')
Outer.func(lambda x: x.arg == 4, lambda x: x=='whatever', lambda x: True)
Outer.func.replay()
# Invoke other code, which ends up doing:
o = Outer(3)
p = Outer(5)
o.func('something', 'here')
p.func('whatever', 'next') # <- This should fail, 5 != 4
The question is: Is there a way (black magic is fine) within Injected.__call__() to access what "self" would have been in non-overwritten Outer.func(), to use as "this" (line marked with "###")?
Naturally, the code is a bit more complex (the calls can be configured to be in arbitrary order, return values can be set, etc.), but this is the minimal example I could come up with that demonstrates both the problem and most of the constraints.
I cannot inject a function with a default argument instead of Outer.func - that breaks recording (if a function were injected, it'd be an unbound method and require an instance of "Outer" as its first argument, rather than a comparator/validator).
Theoretically, I could mock out "Outer" completely for its caller. However, setting up the expectations there would probably be more code, and not reusable elsewhere - any similar case/project would also have to reimplement "Outer" (or its equivalent) as a mock.
| [
"\nGiven an object A, which contains a\n callable object B, is there a way to\n determine \"A\" from inside\n B.call()?\n\nNot in the general case, i.e., with the unbounded generality you require in this text -- unless B keeps a reference to A in some way, Python most surely doesn't keep it on B's behalf.\nFor y... | [
2,
0
] | [] | [] | [
"code_injection",
"python"
] | stackoverflow_0003736612_code_injection_python.txt |
Q:
Where is the raise object in Python?
When you want to print a bunch of variables in Python, you have quite a few options, such as:
for i in range(len(iterable)):
print iterable[i].name
OR
map(lambda i: sys.stdout.write(i.name), iterable)
The reason I use sys.stdout.write instead of print in the second example is that lambdas won't accept print, but sys.stdout.write serves the same purpose.
You can also print conditionally with the ternary operator:
map(lambda n: None if n % 2 else sys.stdout.write(str(n)), range(1, 100))
So it would be really handy if I could check an entire sequence for a condition that would warrant an exception in such a way:
map(lambda o: raise InvalidObjectError, o.name if not o.isValid else o(), iterable)
But that doesn't work.
Is there such an object for raise in Python, and if so, where is it?
A:
There is no Python "object" (built-in or in the standard library) for raise, you have to build one yourself (typical short snippet that goes in one's util.py...!):
def do_raise(exc): raise exc
typically to be called as do_raise(InvalidObjectError(o.name)).
A:
I don't think it's possible to use raise in a lambda, like you're attempting to do. raise is a statement/expression, not an object. As @Alex Martelli has stated, you'd likely need to define a function to do the check for you. Now, the function could be declared locally, within the same context.
As far as the exception types, which is what your question seems to be aimed at: Exception types are not defined automatically. For simple exception types, where you either want just a text message, or none at all, typically exception types are defined simply at your module/file scope as:
class InvalidObjectError(Exception): pass
A:
Do. Not. Do. This.
This is a dreadful idea.
map(lambda o: raise InvalidObjectError, o.name if not o.isValid else o(), iterable)
Do this.
class SomeValidatingClass( object ):
def isValid( self ):
try:
self.validate()
except InvalidObjectError:
return False
return True
def validate( self ):
"""raises InvalidObjectErorr if there's a problem."""
[ x.validate() for x in iterable ]
No map. No lambda. Same behavior.
A:
For your first example I use form like this:
print '\n'.join(obj.name for obj in iterable)
Also I would use:
firstnotvalid = next(obj.name for obj in iterable if not obj.is_valid())
And instead of:
>>> import sys
>>> map(lambda n: None if n % 2 else sys.stdout.write(str(n)), range(1, 100))
2468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]
I would do:
>>> print (', '.join(str(number) for number in range(1,100) if not number % 2))
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98
Ignoring that there is step parameter for range, as I think the function is simplification of other more complicated functions.
| Where is the raise object in Python? | When you want to print a bunch of variables in Python, you have quite a few options, such as:
for i in range(len(iterable)):
print iterable[i].name
OR
map(lambda i: sys.stdout.write(i.name), iterable)
The reason I use sys.stdout.write instead of print in the second example is that lambdas won't accept print, but sys.stdout.write serves the same purpose.
You can also print conditionally with the ternary operator:
map(lambda n: None if n % 2 else sys.stdout.write(str(n)), range(1, 100))
So it would be really handy if I could check an entire sequence for a condition that would warrant an exception in such a way:
map(lambda o: raise InvalidObjectError, o.name if not o.isValid else o(), iterable)
But that doesn't work.
Is there such an object for raise in Python, and if so, where is it?
| [
"There is no Python \"object\" (built-in or in the standard library) for raise, you have to build one yourself (typical short snippet that goes in one's util.py...!):\ndef do_raise(exc): raise exc\n\ntypically to be called as do_raise(InvalidObjectError(o.name)).\n",
"I don't think it's possible to use raise in a... | [
4,
2,
1,
0
] | [] | [] | [
"python",
"raise"
] | stackoverflow_0003732358_python_raise.txt |
Q:
How to pause python execution in eclipse and return to an interactive prompt
I am using Eclipse as a Python IDE. Is there anyway for me to Debug my program and break to an interactive prompt. I am interested in exploring the existing data and running/testing commands.
I believe there has to be a way, but I am so used to compiling languages that I have not been able to find where the options are.
Any ideas?
A:
You can easily do that by using PDB (Python Debugger) inside a python shell.
Look at http://docs.python.org/library/pdb.html for more info.
Anyway I believe Eclipse will let you inspect you data when setting a breakpoint.
| How to pause python execution in eclipse and return to an interactive prompt | I am using Eclipse as a Python IDE. Is there anyway for me to Debug my program and break to an interactive prompt. I am interested in exploring the existing data and running/testing commands.
I believe there has to be a way, but I am so used to compiling languages that I have not been able to find where the options are.
Any ideas?
| [
"You can easily do that by using PDB (Python Debugger) inside a python shell.\nLook at http://docs.python.org/library/pdb.html for more info.\nAnyway I believe Eclipse will let you inspect you data when setting a breakpoint.\n"
] | [
2
] | [] | [] | [
"database",
"eclipse",
"interactive",
"ipython",
"python"
] | stackoverflow_0003737565_database_eclipse_interactive_ipython_python.txt |
Q:
Memory consumption in Cherrypy
I am using Cherrypy in a RESTful web service and server returns XML as a result (lxml is being used to create XML). Some of those XMLs are quite large. I have noticed that memory is not being released after such request (that return large XML) has been processed.
So, I have isolated a problem and created this one very short dummy example:
import cherrypy
from lxml import etree
class Server:
@cherrypy.expose
def index(self):
foo = etree.Element('foo')
for i in range(200000):
bar = etree.SubElement(foo, 'bar')
bar1 = etree.SubElement(bar, 'bar1')
bar1.text = "this is bar1 text ({0})".format(i)
bar2 = etree.SubElement(bar, 'bar2')
bar2.text = "this is bar2 text ({0})".format(i)
bar3 = etree.SubElement(bar, 'bar3')
bar3.text = "this is bar3 text ({0})".format(i)
bar4 = etree.SubElement(bar, 'bar4')
bar4.text = "this is bar4 text ({0})".format(i)
bar5 = etree.SubElement(bar, 'bar5')
bar5.text = "this is bar5 text ({0})".format(i)
return etree.tostring(foo, pretty_print=True)
if __name__ == '__main__':
cherrypy.quickstart(Server())
After request has been made to: http://localhost:8080/index, memory consumption goes from 830MB to 1.2GB. Then, after request has been processed it goes down to 1.1GB and stays there until the server is shut down. After server shut down, memory consumption goes down to 830MB.
In my project, data (of course) comes from the database, and parameters are being used to specify what data should be retrieved. If the same request (with same parameters) is made, memory stays at 1.1GB, i.e. no additional memory is being used. But, if different parameters are being passed, server keeps consuming more and more memory. Only way to free the memory is to restart the server.
Do you have any ideas on why this is happening and how to solve it? Thanks.
A:
This is a generic Python problem, not really a CherryPy one per se. effbot has a great answer to this question at http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm
And there's a similar SO question with a great answer at How can I explicitly free memory in Python?
| Memory consumption in Cherrypy | I am using Cherrypy in a RESTful web service and server returns XML as a result (lxml is being used to create XML). Some of those XMLs are quite large. I have noticed that memory is not being released after such request (that return large XML) has been processed.
So, I have isolated a problem and created this one very short dummy example:
import cherrypy
from lxml import etree
class Server:
@cherrypy.expose
def index(self):
foo = etree.Element('foo')
for i in range(200000):
bar = etree.SubElement(foo, 'bar')
bar1 = etree.SubElement(bar, 'bar1')
bar1.text = "this is bar1 text ({0})".format(i)
bar2 = etree.SubElement(bar, 'bar2')
bar2.text = "this is bar2 text ({0})".format(i)
bar3 = etree.SubElement(bar, 'bar3')
bar3.text = "this is bar3 text ({0})".format(i)
bar4 = etree.SubElement(bar, 'bar4')
bar4.text = "this is bar4 text ({0})".format(i)
bar5 = etree.SubElement(bar, 'bar5')
bar5.text = "this is bar5 text ({0})".format(i)
return etree.tostring(foo, pretty_print=True)
if __name__ == '__main__':
cherrypy.quickstart(Server())
After request has been made to: http://localhost:8080/index, memory consumption goes from 830MB to 1.2GB. Then, after request has been processed it goes down to 1.1GB and stays there until the server is shut down. After server shut down, memory consumption goes down to 830MB.
In my project, data (of course) comes from the database, and parameters are being used to specify what data should be retrieved. If the same request (with same parameters) is made, memory stays at 1.1GB, i.e. no additional memory is being used. But, if different parameters are being passed, server keeps consuming more and more memory. Only way to free the memory is to restart the server.
Do you have any ideas on why this is happening and how to solve it? Thanks.
| [
"This is a generic Python problem, not really a CherryPy one per se. effbot has a great answer to this question at http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm\nAnd there's a similar SO question with a great answer at How can I explicitly free memory in Python?\n"
] | [
1
] | [] | [] | [
"cherrypy",
"consumption",
"lxml",
"memory",
"python"
] | stackoverflow_0003737268_cherrypy_consumption_lxml_memory_python.txt |
Q:
python threads - how do "condition.wait" and "condition.notifyAll" work
I have the following "consumer" code:
....
while 1:
time.sleep(self.sleeptime)
cond.acquire() #acquire the lock
print currentThread(), "lock acquired"
while itemq.isEmpty():
cond.wait()
itemq.consume()
print currentThread(),"Consumed One Item"
cond.release()
And the following producer's code:
....
while 1 :
cond.acquire() #acquire the lock
print currentThread(), "lock acquired"
print currentThread(),"Produced One Item"
itemq.produce()
cond.notifyAll()
cond.release()
time.sleep(self.sleeptime)
I'm running the program with 1 producer and 2 consumers.
I don't know what result to expect. The producer calls "notifyAll()", so I expect both consumers to wake up from their "wait". I see that indeed both consumer acquire the lock, but only the first one who acquired the lock actually get to consume the item. Could somebody please tell me how the "wait" command works? If both threads get the "notifyAll", how is it that only one gets to consume?
Thanks,
Li
A:
I think the docs are very clear:
The wait() method releases the lock,
and then blocks until it is awakened
by a notify() or notifyAll() call for
the same condition variable in another
thread. Once awakened, it re-acquires
the lock and returns. It is also
possible to specify a timeout.
and:
Note: the notify() and notifyAll()
methods don’t release the lock; this
means that the thread or threads
awakened will not return from their
wait() call immediately, but only when
the thread that called notify() or
notifyAll() finally relinquishes
ownership of the lock.ownership of the lock.
Only one thread can have the lock at any time, of course: that's the core purpose of having a lock in the first place, after all!
So, IOW, notifyAll puts all waiting threads in ready-to-run state, and intrinsically all waiting to acquire the lock again so they can proceed: once the notifier releases the lock, one of the threads waiting to acquire that lock does acquire it (the others, if any, keep waiting for the lock to be released again, of course, so that only one thread has the lock at any given time).
A:
The key is in the loop around the wait:
while itemq.isEmpty():
cond.wait()
cond.wait() is implemented something like this (example only):
def wait():
cond.release()
wait for notify
cond.aquire()
So only one consumer exits the 'wait' function at a time thanks to the lock. The first consumer to exit the wait function detects that itemq.isEmpty() == false and goes on to consume the item. They then re-enter the wait function and release the lock.
The second consumer exits, detects that itemq.isEmpty() == true again, and re-enters wait() right away.
| python threads - how do "condition.wait" and "condition.notifyAll" work | I have the following "consumer" code:
....
while 1:
time.sleep(self.sleeptime)
cond.acquire() #acquire the lock
print currentThread(), "lock acquired"
while itemq.isEmpty():
cond.wait()
itemq.consume()
print currentThread(),"Consumed One Item"
cond.release()
And the following producer's code:
....
while 1 :
cond.acquire() #acquire the lock
print currentThread(), "lock acquired"
print currentThread(),"Produced One Item"
itemq.produce()
cond.notifyAll()
cond.release()
time.sleep(self.sleeptime)
I'm running the program with 1 producer and 2 consumers.
I don't know what result to expect. The producer calls "notifyAll()", so I expect both consumers to wake up from their "wait". I see that indeed both consumer acquire the lock, but only the first one who acquired the lock actually get to consume the item. Could somebody please tell me how the "wait" command works? If both threads get the "notifyAll", how is it that only one gets to consume?
Thanks,
Li
| [
"I think the docs are very clear:\n\nThe wait() method releases the lock,\n and then blocks until it is awakened\n by a notify() or notifyAll() call for\n the same condition variable in another\n thread. Once awakened, it re-acquires\n the lock and returns. It is also\n possible to specify a timeout.\n\nand:\... | [
4,
1
] | [] | [] | [
"conditional_statements",
"multithreading",
"python",
"wait"
] | stackoverflow_0003737755_conditional_statements_multithreading_python_wait.txt |
Q:
How do you convert a stringed dictionary to a Python dictionary?
I have the following string which is a Python dictionary stringified:
some_string = '{123: False, 456: True, 789: False}'
How do I get the Python dictionary out of the above string?
A:
Use ast.literal_eval:
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
Example:
>>> some_string = '{123: False, 456: True, 789: False}'
>>> import ast
>>> ast.literal_eval(some_string)
{456: True, 123: False, 789: False}
A:
Well, you can do
d = eval(some_string)
But if the string contains user input, it's a bad idea because some random malicious function could be in the expression. See Safety of Python 'eval' For List Deserialization
So a safer alternative might be:
import ast
d = ast.literal_eval(some_string)
From http://docs.python.org/library/ast.html#ast.literal_eval :
The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
A:
The only safe way to do it is with ast.literal_eval (it's safe because, differently from built-in eval, """The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.""".
| How do you convert a stringed dictionary to a Python dictionary? | I have the following string which is a Python dictionary stringified:
some_string = '{123: False, 456: True, 789: False}'
How do I get the Python dictionary out of the above string?
| [
"Use ast.literal_eval:\n\nSafely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.\nThis can be used for safely evaluating strings containing Pyt... | [
12,
10,
3
] | [] | [] | [
"python"
] | stackoverflow_0003737900_python.txt |
Q:
How to quit the running python program to python prompt?
I wrote a implementation of conway's game of life. I set up two modes, one is auto and the other is manual, which I mean the way to ouput the result of the game. For the auto mode, I cannot stop the running progran without ctrl + q or ctrl + c (which prints out the error message). So is there any way which can allow me to stop the running program and return to the python >>> prompt by pressing some key defined by myself, say, ctrl + k. Thank you.
A:
You can't use arbitrary keypresses, but to handle the normal interrupt (e.g. control-C) without errors all you need is to catch the KeyboardInterrupt exception it causes, i.e., just wrap all of your looping code with
try:
functionthatloopsalot()
except KeyboardInterrupt:
"""user wants control back"""
To "get control back" to the interactive prompt, the script must be running with -i (for "interactive"), or more advanced interactive Python shells like ipython must be used.
A:
Provided that you are able to intercept the event raised by the key press and call a specific function than you could do this:
def prompt():
import code
code.interact(local=locals())
or if you use IPython:
def prompt():
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell(local_ns=locals())
This will open a python or IPython shell in which you are able to access the current environment.
Cheers Andrea
A:
Are you running it from an iteractive prompt and want to just get back to the prompt. Or, are you running it from a shell and want to get to a python prompt in but with the current state of the programs execution?
For the later it you could the keyboard interupt exception in your code and break out to the python debugger (pdb).
import pdb
try:
mainProgramLoop()
except (KeyboardInterrupt, SystemExit):
pdb.set_trace()
| How to quit the running python program to python prompt? | I wrote a implementation of conway's game of life. I set up two modes, one is auto and the other is manual, which I mean the way to ouput the result of the game. For the auto mode, I cannot stop the running progran without ctrl + q or ctrl + c (which prints out the error message). So is there any way which can allow me to stop the running program and return to the python >>> prompt by pressing some key defined by myself, say, ctrl + k. Thank you.
| [
"You can't use arbitrary keypresses, but to handle the normal interrupt (e.g. control-C) without errors all you need is to catch the KeyboardInterrupt exception it causes, i.e., just wrap all of your looping code with\ntry:\n functionthatloopsalot()\nexcept KeyboardInterrupt:\n \"\"\"user wants control back\"... | [
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003737922_python.txt |
Q:
What are the possible pitfalls in porting Psyco to 64-bit?
The Psyco docs say:
Just for reference, Psyco does not
work on any 64-bit systems at all.
This fact is worth being noted again,
now that the latest Mac OS/X 10.6
"Snow Leopart" comes with a default
Python that is 64-bit on 64-bit
machines. The only way to use Psyco on
OS/X 10.6 is by recompiling a custom
Python in 32-bit mode.
In general, porting programs from 32 to 64 bits is only really an issue when the code assumes a certain size for a pointer type and other similarly small(ish) issues. Considering that Psyco isn't a whole lot of code (~32K lines of C + ~8K lines of Python), how hard could it be? Has anyone tried this and hit a wall? I haven't really had a chance to take a good look at the Psyco sources yet, so I'd really appreciate knowing if I'm wasting my time looking into this...
A:
Christian Tismer, one of the Psyco developers also seems to disagree with the "how hard could it be" - assumption (quoted from here):
Needs to come to x86-64? Why that!
Seriously, I would love to do that,
but this would be much harder than
anybody would expect. Due to the way
psyco is written, it would be really
half a rewrite to releave it from its
32-bitterness. The 32 bit assumption
is implicitly everywhere. It would be
straight forward, if the memory model
was all 64 bit. But no intel platform
is that simple. so long, and thanks
for all the fish -- chris
and
hum. It would cost at least 3 or 4 months of full-time work do do that, if not more. I doubt that I can get sponsorship for that.
If you want more details (firm inside knowledge of Psyco probably needed) I guess you can always try to ask on one of the psyco mailing lists ...
A:
Since psyco is a compiler, it would need to be aware of the underlying assembly language to generate useful code. That would mean it would need to know about the 8 new registers, new opcodes for 64 bit code, etc.
Furthermore, to interop with the existing code, it would need to use the same calling conventions as 64 bit code. The AMD-64 calling convention is similar to the old fast-call conventions in that some parameters are passed in registers (in the 64 bit case rcx,rdx,r8,r9 for pointers and Xmm0-Xmm3 for floating point) and the rest are pushed onto spill space on the stack. Unlike x86, this extra space is usually allocated once for all of the possible calls. The IA64 conventions and assembly language are different yet.
So in short, I think this is probably not as simple as it sounds.
A:
Psyco assumes that sizeof(int) == sizeof(void*) a bit all over the place. That's much harder than just writing down 64bit calling conventions and assembler. On the sidenote, pypy has 64bit jit support these days.
Cheers,
fijal
A:
+1 for "... how hard could it be?".
Take a look here: http://codespeak.net/svn/psyco/dist/c/i386/iprocessor.c
All that ASM would have to be ported, and there are assumptions all over the place about the underlying processor.
I think it's fair to say that if it were trivial to port (or not too difficult), it would already have been done.
| What are the possible pitfalls in porting Psyco to 64-bit? | The Psyco docs say:
Just for reference, Psyco does not
work on any 64-bit systems at all.
This fact is worth being noted again,
now that the latest Mac OS/X 10.6
"Snow Leopart" comes with a default
Python that is 64-bit on 64-bit
machines. The only way to use Psyco on
OS/X 10.6 is by recompiling a custom
Python in 32-bit mode.
In general, porting programs from 32 to 64 bits is only really an issue when the code assumes a certain size for a pointer type and other similarly small(ish) issues. Considering that Psyco isn't a whole lot of code (~32K lines of C + ~8K lines of Python), how hard could it be? Has anyone tried this and hit a wall? I haven't really had a chance to take a good look at the Psyco sources yet, so I'd really appreciate knowing if I'm wasting my time looking into this...
| [
"Christian Tismer, one of the Psyco developers also seems to disagree with the \"how hard could it be\" - assumption (quoted from here):\n\nNeeds to come to x86-64? Why that!\n Seriously, I would love to do that,\n but this would be much harder than\n anybody would expect. Due to the way\n psyco is written, it ... | [
4,
3,
3,
1
] | [] | [] | [
"64_bit",
"c",
"porting",
"psyco",
"python"
] | stackoverflow_0002374233_64_bit_c_porting_psyco_python.txt |
Q:
How to write find-all function (with regex) in awk or sed
I have bash function which run python (which return all finded regex from stdin)
function find-all() {
python -c "import re
import sys
print '\n'.join(re.findall('$1', sys.stdin.read()))"
}
When I use this regex find-all 'href="([^"]*)"' < index.html it should return first group from the regex (value of href attribute from file index.html)
How can I write this in sed or awk?
A:
I suggest you use grep -o.
-o, --only-matching
Show only the part of a matching line that matches PATTERN.
E.g.:
$ cat > foo
test test test
test
bar
baz test
$ grep -o test foo
test
test
test
test
test
Update
If you were extracting href attributes from html files, using a command like:
$ grep -o -E 'href="([^"]*)"' /usr/share/vlc/http/index.html
href="style.css"
href="iehacks.css"
href="old/"
You could extract the values by using cut and sed like this:
$ grep -o -E 'href="([^"]*)"' /usr/share/vlc/http/index.html| cut -f2 -d'=' | sed -e 's/"//g'
style.css
iehacks.css
old/
But you'd be better off using html/xml parsers for reliability.
A:
Here's a gawk implementation (not tested with other awks): find_all.sh
awk -v "patt=$1" '
function find_all(str, patt) {
while (match(str, patt, a) > 0) {
for (i=0; i in a; i++) print a[i]
str = substr(str, RSTART+RLENGTH)
}
}
$0 ~ patt {find_all($0, patt)}
' -
Then:
echo 'asdf href="href1" asdf asdf href="href2" asdfasdf
asdfasdfasdfasdf href="href3" asdfasdfasdf' |
find_all.sh 'href="([^"]+)"'
outputs:
href="href1"
href1
href="href2"
href2
href="href3"
href3
Change i=0 to i=1 if you only want to print the captured groups. With i=0 you'll get output even if you have no parentheses in your pattern.
| How to write find-all function (with regex) in awk or sed | I have bash function which run python (which return all finded regex from stdin)
function find-all() {
python -c "import re
import sys
print '\n'.join(re.findall('$1', sys.stdin.read()))"
}
When I use this regex find-all 'href="([^"]*)"' < index.html it should return first group from the regex (value of href attribute from file index.html)
How can I write this in sed or awk?
| [
"I suggest you use grep -o.\n-o, --only-matching\n Show only the part of a matching line that matches PATTERN.\n\nE.g.:\n$ cat > foo\ntest test test\ntest\nbar\nbaz test\n$ grep -o test foo\ntest\ntest\ntest\ntest\ntest\n\n\nUpdate\nIf you were extracting href attributes from html files, using a command like:... | [
3,
2
] | [] | [] | [
"awk",
"bash",
"python",
"sed"
] | stackoverflow_0003707625_awk_bash_python_sed.txt |
Q:
Draw text image without crop need by PIL
I would like to draw a text by using PIL. But my problem is I need to crop the text image again after run the program. The thing i need is only text, no border. Any one can suggest?
Thank you.
This is my code:
import Image, ImageDraw, ImageFont
def draw (text, size, color) :
fontPath = '/home/FreeSansBold.ttf'
font = ImageFont.truetype(fontPath, size)
size2 = font.getsize(text)
im = Image.new('RGBA', size2, (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
draw.text((0, 0), text, font=font, fill=color)
im.save(text +'.png')
drawA = draw('A', 200, 'green')
drawC = draw('C', 200, 'blue')
drawG = draw('G', 200, 'yellow')
drawT = draw('T', 200, 'red')
A:
Could you clarify what you mean by no border? Are you wanting text tight against edge of the image? If so this should work:
import Image, ImageDraw, ImageFont
def draw (text, size, color) :
fontPath = '/home/FreeSansBold.ttf'
font = ImageFont.truetype(fontPath, size)
size2 = font.getsize(text)
im = Image.new('RGBA', size2, (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
draw.text((0, 0), text, font=font, fill=color)
pixels = im.load()
width, height = im.size
max_x = max_y = 0
min_y = height
min_x = width
# find the corners that bound the letter by looking for
# non-transparent pixels
transparent = (0, 0, 0, 0)
for x in xrange(width):
for y in xrange(height):
p = pixels[x,y]
if p != transparent:
min_x = min(x, min_x)
min_y = min(y, min_y)
max_x = max(x, max_x)
max_y = max(y, max_y)
cropped = im.crop((min_x, min_y, max_x, max_y))
cropped.save(text +'.png')
drawA = draw('A', 200, 'green')
drawC = draw('C', 200, 'blue')
drawG = draw('G', 200, 'yellow')
drawT = draw('T', 200, 'red')
It produces an image like this (I filled in the transparent pixels with red to show the bounds of the image better: http://img43.imageshack.us/img43/3066/awithbg.png
| Draw text image without crop need by PIL | I would like to draw a text by using PIL. But my problem is I need to crop the text image again after run the program. The thing i need is only text, no border. Any one can suggest?
Thank you.
This is my code:
import Image, ImageDraw, ImageFont
def draw (text, size, color) :
fontPath = '/home/FreeSansBold.ttf'
font = ImageFont.truetype(fontPath, size)
size2 = font.getsize(text)
im = Image.new('RGBA', size2, (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
draw.text((0, 0), text, font=font, fill=color)
im.save(text +'.png')
drawA = draw('A', 200, 'green')
drawC = draw('C', 200, 'blue')
drawG = draw('G', 200, 'yellow')
drawT = draw('T', 200, 'red')
| [
"Could you clarify what you mean by no border? Are you wanting text tight against edge of the image? If so this should work:\n\nimport Image, ImageDraw, ImageFont\n\ndef draw (text, size, color) :\n fontPath = '/home/FreeSansBold.ttf'\n font = ImageFont.truetype(fontPath, size)\n size2 = font.getsize(tex... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003706142_python.txt |
Q:
Python namespace in between builtins and global?
As I understand it python has the following outermost namespaces:
Builtin - This namespace is global across the entire interpreter and all scripts running within an interpreter instance.
Globals - This namespace is global across a module, ie across a single file.
I am looking for a namespace in between these two, where I can share a few variables declared within the main script to modules called by it.
For example, script.py:
import Log from Log
import foo from foo
log = Log()
foo()
foo.py:
def foo():
log.Log('test') # I want this to refer to the callers log object
I want to be able to call script.py multiple times and in each case, expose the module level log object to the foo method.
Any ideas if this is possible?
It won't be too painful to pass down the log object, but I am working with a large chunk of code that has been ported from Javascript. I also understand that this places constraints on the caller of foo to expose its log object.
Thanks,
Paul
A:
There is no namespace "between" builtins and globals -- but you can easily create your own namespaces and insert them with a name in sys.modules, so any other module can "import" them (ideally not using the from ... import syntax, which carries a load of problems, and definitely not using tghe import ... from syntax you've invented, which just gives a syntax error). For example, in script.py:
import sys
import types
sys.modules['yay'] = types.ModuleType('yay')
import Log
import foo
yay.log = Log.Log()
foo.foo()
and in foo.py
import yay
def foo():
yay.log.Log('test')
Do not fear qualified names -- they're goodness! Or as the last line of the Zen of Python (AKA import this) puts it:
Namespaces are one honking great idea -- let's do more of those!
You can make and use "more of those" most simply -- just qualify your names (situating them in the proper namespace they belong in!) rather than insisting on barenames where they're just not a good fit. There's a bazillion things that are quite easy with qualified names and anywhere between seriously problematic and well-nigh unfeasible for those who're stuck on barenames!-)
A:
There is no such scope. You will need to either add to the builtins scope, or pass the relevant object.
A:
Actually, I did figure out what I was looking for.
This hack is actually used PLY and that is where is stumbled across.
The library code can raise a runtime exception, which then gives access to the callers stack.
| Python namespace in between builtins and global? | As I understand it python has the following outermost namespaces:
Builtin - This namespace is global across the entire interpreter and all scripts running within an interpreter instance.
Globals - This namespace is global across a module, ie across a single file.
I am looking for a namespace in between these two, where I can share a few variables declared within the main script to modules called by it.
For example, script.py:
import Log from Log
import foo from foo
log = Log()
foo()
foo.py:
def foo():
log.Log('test') # I want this to refer to the callers log object
I want to be able to call script.py multiple times and in each case, expose the module level log object to the foo method.
Any ideas if this is possible?
It won't be too painful to pass down the log object, but I am working with a large chunk of code that has been ported from Javascript. I also understand that this places constraints on the caller of foo to expose its log object.
Thanks,
Paul
| [
"There is no namespace \"between\" builtins and globals -- but you can easily create your own namespaces and insert them with a name in sys.modules, so any other module can \"import\" them (ideally not using the from ... import syntax, which carries a load of problems, and definitely not using tghe import ... from ... | [
4,
0,
0
] | [] | [] | [
"global_variables",
"module",
"namespaces",
"python"
] | stackoverflow_0003010657_global_variables_module_namespaces_python.txt |
Q:
How to insert arrays into a database?
In my previous question a lot of users wanted me to give some more data to toy with. So I got working on exporting all my data and processing it with Python, but then I realized: where do I leave all this data?
Well I decided the best thing would be to stick them in a database, so at least I don't have to parse the raw files every time. But since I know nothing about databases this is turning out to be quite confusing. I tried some tutorials to create a sqlite database, add a table and field and try to insert my numpy.arrays, but it can't get it to work.
Typically my results per dog look like this:
So I have 35 different dogs and each dog has 24 measurement. Each measurement itself has an unknown amount of contacts. Each measurement consists out of a 3D array (248 frames of the whole plate [255x63]) and a 2D array (the maximal values for each sensor of the plate [255x63]). Storing one value in a database wasn't a problem, but getting my 2D arrays in there didn't seem to work.
So my question is how should I order this in a database and insert my arrays into it?
A:
You'll probably want to start out with a dogs table containing all the flat (non array) data for each dog, things which each dog has one of, like a name, a sex, and an age:
CREATE TABLE `dogs` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(64),
`age` INT UNSIGNED,
`sex` ENUM('Male','Female')
);
From there, each dog "has many" measurements, so you need a dog_mesaurements table to store the 24 measurements:
CREATE TABLE `dog_measurements` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`dog_id` INT UNSIGNED NOT NULL,
`paw` ENUM ('Front Left','Front Right','Rear Left','Rear Right'),
`taken_at` DATETIME NOT NULL
);
Then whenever you take a measurement, you INSERT INTO dog_measurements (dog_id,taken_at) VALUES (*?*, NOW()); where * ? * is the dog's ID from the dogs table.
You'll then want tables to store the actual frames for each measurement, something like:
CREATE TABLE `dog_measurement_data` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`dog_measurement_id` INT UNSIGNED NOT NULL,
`frame` INT UNSIGNED,
`sensor_row` INT UNSIGNED,
`sensor_col` INT UNSIGNED,
`value` NUMBER
);
That way, for each of the 250 frames, you loop through each of the 63 sensors, and store the value for that sensor with the frame number into the database:
INSERT INTO `dog_measurement_data` (`dog_measurement_id`,`frame`,`sensor_row`,`sensor_col`,`value`) VALUES
(*measurement_id?*, *frame_number?*, *sensor_row?*, *sensor_col?*, *value?*)
Obviously replace measurement_id?, frame_number?, sensor_number?, value? with real values :-)
So basically, each dog_measurement_data is a single sensor value for a given frame. That way, to get all the sensor values for all a given frame, you would:
SELECT `sensor_row`,sensor_col`,`value` FROM `dog_measurement_data`
WHERE `dog_measurement_id`=*some measurement id* AND `frame`=*some frame number*
ORDER BY `sensor_row`,`sensor_col`
And this will give you all the rows and cols for that frame.
A:
Django has a library for encapsulating all the database work into Python classes, so you don't have to mess with raw SQL until you have to do something really clever. Even though Django is a framework for web applications, you can use the database ORM by itself.
Josh's models would look like this in Python using Django:
from django.db import models
class Dog(models.Model):
# Might want to look at storing birthday instead of age.
# If you track age, you probably need another field telling
# you when in the year age goes up by 1... and at that point,
# you're really storing a birthday.
name = models.CharField(max_length=64)
age = models.IntegerField()
genders = [
('M', 'Male'),
('F', 'Female'),
]
gender = models.CharField(max_length=1, choices=genders)
class Measurement(models.Model):
dog = models.ForeignKey(Dog, related_name="measurements")
paws = [
('FL', 'Front Left'),
('FR', 'Front Right'),
('RL', 'Rear Left'),
('RR', 'Rear Right'),
]
paw = models.CharField(max_length=2, choices=paws)
taken_at = models.DateTimeField(default=date, auto_now_add=True)
class Measurement_Point(models.Model):
measurement = models.ForeignKey(Measurement, related_name="data_points")
frame = models.IntegerField()
sensor_row = models.PositiveIntegerField()
sensor_col = models.PositiveIntegerField()
value = models.FloatField()
class Meta:
ordering = ['frame', 'sensor_row', 'sensor_col']
The id fields are created automatically.
Then you can do things like:
dog = Dog()
dog.name = "Pochi"
dog.age = 3
dog.gender = 'M'
# dog.gender will return 'M', and dog.get_gender_display() will return 'Male'
dog.save()
# Or, written another way:
dog = Dog.objects.create(name="Fido", age=3, sex='M')
To take a measurement:
measurement = dog.measurements.create(paw='FL')
for frame in range(248):
for row in range(255):
for col in range(63):
measurement.data_points.create(frame=frame, sensor_row=row,
sensor_col=col, value=myData[frame][row][col])
Finally, to get a frame:
# For the sake of argument, assuming the dogs have unique names.
# If not, you'll need some more fields in the Dog model to disambiguate.
dog = Dog.objects.get(name="Pochi", sex='M')
# For example, grab the latest measurement...
measurement = dog.measurements.all().order_by('-taken_at')[0]
# `theFrameNumber` has to be set somewhere...
theFrame = measurement.filter(frame=theFrameNumber).values_list('value')
Note: this will return a list of tuples (e.g. [(1.5,), (1.8,), ... ]), since values_list() can retrieve multiple fields at once. I'm not familiar with NumPy, but I'd imagine it's got a function similar to Matlab's reshape function for remapping vectors to matrices.
A:
I think you are not able to figure out how to put 2D data in database.
If you think of relation between 2 columns, you can think of it as 2D data with 1st column as X axis data and 2nd column as Y axis data. Similarly for 3D data.
Finally your db should look like this:
Table: Dogs
Columns: DogId, DogName -- contains data for each dog
Table: Measurements
Columns: DogId, MeasurementId, 3D_DataId, 2D_DataId -- contains measurements of each dog
Table: 3D_data
Columns: 3D_DataId, 3D_X, 3D_Y, 3D_Z -- contains all 3D data of a measurement
Table: 2D_data
Columns: 2D_DataId, 2D_X, 2D_Y -- contains all 2D data of a measurement
Also you may want to store your 3D data and 2D data in an order. In that case, you will have to add a column to store that order in table of 3D data and 2D data
A:
The only thing I would add to Josh's answer is that if you don't need to query individual frames or sensors, just store the arrays as BLOBs in the dog_measurement_data table. I have done this before with large binary set of sensor data and it worked out well. You basically query the 2d and 3d arrays with each measurement and manipulate them in code instead of the database.
A:
I've benefited a lot from the sqlalchemy package; it is an Object Relational Mapper. What this means is that you can create a very clear and distinct separation between your objects and your data:
SQL databases behave less like object
collections the more size and
performance start to matter; object
collections behave less like tables
and rows the more abstraction starts
to matter. SQLAlchemy aims to
accommodate both of these principles.
You can create a objects representing your different nouns (Dog, Measurement, Plate, etc). Then you create a table via sqlalchemy constructs which will contain all the data that you want to associate with, say, a Dog object. Finally you create a mapper between the Dog object and the dog_table.
This is difficult to understand without an example, and I will not reproduce one here. Instead, please start by reading this case study and then study this tutorial.
Once you can think of your Dogs and Measurements as you do in the real world (that is, the objects themselves) you can start factoring out the data that makes them up.
Finally, try not to marry your data with an specific format (as you do currently by using numpy arrays). Instead, you can think of the simple numbers and then transform them on demand to the specific format your current application demands (along the lines of a Model-View-Controller paradigm).
Good luck!
A:
From your description, I would highly recommend looking into PyTables. It's not a relational database in the traditional sense, it has most of the features you're likely to be using (e.g. querying) while allowing easy storage of large, multidimensional datasets and their attributes. As an added bonus, it's tightly integrated with numpy.
| How to insert arrays into a database? | In my previous question a lot of users wanted me to give some more data to toy with. So I got working on exporting all my data and processing it with Python, but then I realized: where do I leave all this data?
Well I decided the best thing would be to stick them in a database, so at least I don't have to parse the raw files every time. But since I know nothing about databases this is turning out to be quite confusing. I tried some tutorials to create a sqlite database, add a table and field and try to insert my numpy.arrays, but it can't get it to work.
Typically my results per dog look like this:
So I have 35 different dogs and each dog has 24 measurement. Each measurement itself has an unknown amount of contacts. Each measurement consists out of a 3D array (248 frames of the whole plate [255x63]) and a 2D array (the maximal values for each sensor of the plate [255x63]). Storing one value in a database wasn't a problem, but getting my 2D arrays in there didn't seem to work.
So my question is how should I order this in a database and insert my arrays into it?
| [
"You'll probably want to start out with a dogs table containing all the flat (non array) data for each dog, things which each dog has one of, like a name, a sex, and an age:\nCREATE TABLE `dogs` (\n `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n `name` VARCHAR(64),\n `age` INT UNSIGNED,\n `sex` ENUM('... | [
9,
7,
2,
2,
1,
0
] | [] | [] | [
"database_design",
"numpy",
"python"
] | stackoverflow_0003738269_database_design_numpy_python.txt |
Q:
Generating parser in Python language from JavaCC source?
I do mean the ??? in the title because I'm not exactly sure. Let me explain the situation.
I'm not a computer science student & I never did any compilers course. Till now I used to think that compiler writers or students who did compilers course are outstanding because they had to write Parser component of the compiler in whatever language they are writing the compiler. It's not an easy job right?
I'm dealing with Information Retrieval problem. My desired programming language is Python.
Parser Nature:
http://ir.iit.edu/~dagr/frDocs/fr940104.0.txt is the sample corpus. This file contains around 50 documents with some XML style markup. (You can see it in above link). I need to note down other some other values like <DOCNO> FR940104-2-00001 </DOCNO> & <PARENT> FR940104-2-00001 </PARENT> and I only need to index the <TEXT> </TEXT> portion of document which contains some varying tags which I need to strip down and a lot of <!-- --> comments that are to be neglected and some &hyph; &space; & character entities. I don't know why corpus has things like this when its know that it's neither meant to be rendered by browser nor a proper XML document.
I thought of using any Python XML parser and extract desired text. But after little searching I found JavaCC parser source code (Parser.jj) for the same corpus I'm using here. A quick look up on JavaCC followed by Compiler-compiler revealed that after all compiler writers aren't as great as I thought. They use Compiler-compiler to generate parser code in desired language. Wiki says input to compiler-compiler is input is a grammar (usually in BNF). This is where I'm lost.
Is Parser.jj the grammar (Input to compiler-compiler called JavaCC)? It's definitely not BNF. What is this grammar called? Why is this grammar has Java language? Isn't there any universal grammar language?
I want python parser for parsing the corpus. Is there any way I can translate Parser.jj to get python equivalent? If yes, what is it? If no, what are my other options?
By any chance does any one know what is this corpus? Where is its original source? I would like to see some description for it. It is distributed on internet with name frDocs.tar.gz
A:
Why do you call this "XML-style" markup? - this looks like pretty standard/basic XML to me.
Try elementTree or lxml. Instead of writing a parser, use one of the stable, well-hardened libraries that are already out there.
A:
You can't build a parser - let alone a whole compiler - from a(n E)BNF grammar - it's just the grammar, i.e. syntax (and some syntax, like Python's indentation-based block rules, can't be modeled in it at all), not the semantics. Either you use seperate tools for these aspects, or use a more advances framework (like Boost::Spirit in C++ or Parsec in Haskell) that unifies both.
JavaCC (like yacc) is responsible for generating a parser, i.e. the subprogram that makes sense of the tokens read from the source code. For this, they mix a (E)BNF-like notation with code written in the language the resulting parser will be in (for e.g. building a parse tree) - in this case, Java. Of course it would be possible to make up another language - but since the existing languages can handle those tasks relatively well, it would be rather pointless. And since other parts of the compiler might be written by hand in the same language, it makes sense to leave the "I got ze tokens, what do I do wit them?" part to the person who will write these other parts ;)
I never heard of "PythonCC", and google didn't either (well, theres a "pythoncc" project on google code, but it's describtion just says "pythoncc is a program that tries to generate optimized machine Code for Python scripts." and there was no commit since march). Do you mean any of these python parsing libraries/tools? But I don't think there's a way to automatically convert the javaCC code to a Python equivalent - but the whole thing looks rather simple, so if you dive in and learn a bit about parsing via javaCC and [python library/tool of your choice], you might be able to translate it...
| Generating parser in Python language from JavaCC source? | I do mean the ??? in the title because I'm not exactly sure. Let me explain the situation.
I'm not a computer science student & I never did any compilers course. Till now I used to think that compiler writers or students who did compilers course are outstanding because they had to write Parser component of the compiler in whatever language they are writing the compiler. It's not an easy job right?
I'm dealing with Information Retrieval problem. My desired programming language is Python.
Parser Nature:
http://ir.iit.edu/~dagr/frDocs/fr940104.0.txt is the sample corpus. This file contains around 50 documents with some XML style markup. (You can see it in above link). I need to note down other some other values like <DOCNO> FR940104-2-00001 </DOCNO> & <PARENT> FR940104-2-00001 </PARENT> and I only need to index the <TEXT> </TEXT> portion of document which contains some varying tags which I need to strip down and a lot of <!-- --> comments that are to be neglected and some &hyph; &space; & character entities. I don't know why corpus has things like this when its know that it's neither meant to be rendered by browser nor a proper XML document.
I thought of using any Python XML parser and extract desired text. But after little searching I found JavaCC parser source code (Parser.jj) for the same corpus I'm using here. A quick look up on JavaCC followed by Compiler-compiler revealed that after all compiler writers aren't as great as I thought. They use Compiler-compiler to generate parser code in desired language. Wiki says input to compiler-compiler is input is a grammar (usually in BNF). This is where I'm lost.
Is Parser.jj the grammar (Input to compiler-compiler called JavaCC)? It's definitely not BNF. What is this grammar called? Why is this grammar has Java language? Isn't there any universal grammar language?
I want python parser for parsing the corpus. Is there any way I can translate Parser.jj to get python equivalent? If yes, what is it? If no, what are my other options?
By any chance does any one know what is this corpus? Where is its original source? I would like to see some description for it. It is distributed on internet with name frDocs.tar.gz
| [
"Why do you call this \"XML-style\" markup? - this looks like pretty standard/basic XML to me.\nTry elementTree or lxml. Instead of writing a parser, use one of the stable, well-hardened libraries that are already out there.\n",
"You can't build a parser - let alone a whole compiler - from a(n E)BNF grammar - it'... | [
2,
1
] | [] | [] | [
"javacc",
"parsing",
"python"
] | stackoverflow_0003738239_javacc_parsing_python.txt |
Q:
Django, unable to import validators in form class, getting "name 'validatorname' is not defined"
I am trying to use validators in my form fields but am getting an error:
from django import forms
from django.db import models
from django.core.exceptions import ValidationError
class Register(forms.Form):
username = forms.CharField(max_length=100,label="Username",validators=[validate_email])
>>>> name 'validate_email' is not defined
I have tried this with a number of different validator types, only to be hit with the same message for each. I have looked over the documentation and really can't see what I am missing as to how to import the validators into the class, any advice is appreciated
A:
You seem to be missing an import. Try adding
from django.core.validators import validate_email
to your imports
| Django, unable to import validators in form class, getting "name 'validatorname' is not defined" | I am trying to use validators in my form fields but am getting an error:
from django import forms
from django.db import models
from django.core.exceptions import ValidationError
class Register(forms.Form):
username = forms.CharField(max_length=100,label="Username",validators=[validate_email])
>>>> name 'validate_email' is not defined
I have tried this with a number of different validator types, only to be hit with the same message for each. I have looked over the documentation and really can't see what I am missing as to how to import the validators into the class, any advice is appreciated
| [
"You seem to be missing an import. Try adding\nfrom django.core.validators import validate_email\n\nto your imports\n"
] | [
5
] | [] | [] | [
"django",
"forms",
"python",
"validation"
] | stackoverflow_0003739411_django_forms_python_validation.txt |
Q:
Django trying to set up a project and find out which Django I have
I'm on a Mac OS X Snow Leopard with Python 2.6.5, I'm trying to get django working but I keep getting this error. Do I need to add it to the path? I'm not sure where django is installed is there any way that I can find it?
solidariti:~/home/solidariti
→ python
Python 2.6.5 (r265:79063, Aug 8 2010, 21:45:26)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named django
>>> django.VERSION
A:
This shows that there's definitely no Django in your Python include path.
You can try searching for the directory using regular file searching tools.
A:
Yeah, you need to add Django to your python path. I'm not sure where you have Django installed, but for what it's worth, I set things up so I don't have to remember. I use virtualenv and pip. Create a new virtualenv, workon that virtualenv, and then
pip install django
pip and virtualenv are great for juggling python requirements. Django projects often have pip requirements files too, so if some day you want to use some random Django project, you can get the dependencies set up nice and quickly.
| Django trying to set up a project and find out which Django I have | I'm on a Mac OS X Snow Leopard with Python 2.6.5, I'm trying to get django working but I keep getting this error. Do I need to add it to the path? I'm not sure where django is installed is there any way that I can find it?
solidariti:~/home/solidariti
→ python
Python 2.6.5 (r265:79063, Aug 8 2010, 21:45:26)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named django
>>> django.VERSION
| [
"This shows that there's definitely no Django in your Python include path.\nYou can try searching for the directory using regular file searching tools.\n",
"Yeah, you need to add Django to your python path. I'm not sure where you have Django installed, but for what it's worth, I set things up so I don't have to r... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003739266_django_python.txt |
Q:
How to fix a circular dependency for imports
I have three files:
testimports module:
#import moduleTwo
import moduleOne
hiString = "Hi!"
moduleOne.sayHi()
moduleOne:
import moduleTwo
class sayHi():
moduleTwo.printHi()
moduleTwo:
import testimports
def printHi():
print(testimports.hiString)
If I run testimports, I get:
Traceback (most recent call last):
File "..file path snipped../testimports/src/testimports.py", line 2, in <module>
import moduleOne
File "..file path snipped../testimports/src/moduleOne.py", line 1, in <module>
import moduleTwo
File "..file path snipped../testimports/src/moduleTwo.py", line 1, in <module>
import testimports
File "..file path snipped../testimports/src/testimports.py", line 6, in <module>
moduleOne.sayHi()
AttributeError: 'module' object has no attribute 'sayHi'
If, however, I uncomment the import moduleTwo line in testimports, the program gets to this point before it stops working:
Traceback (most recent call last):
File "..file path snipped../testimports/src/testimports.py", line 1, in <module>
import moduleTwo
File "..file path snipped../testimports/src/moduleTwo.py", line 1, in <module>
import testimports
File "..file path snipped../testimports/src/testimports.py", line 2, in <module>
import moduleOne
File "..file path snipped../testimports/src/moduleOne.py", line 3, in <module>
class sayHi():
File "..file path snipped../testimports/src/moduleOne.py", line 4, in sayHi
moduleTwo.printHi()
AttributeError: 'module' object has no attribute 'printHi'
How would I go about resolving this circular dependency problem?
A:
verisimilidude is along the right direction. I would expand a little to give more details.
In both cases, this is what happens:
testimports is executed as __main__
testimports imports moduleOne. Now moduleOne is read from file and added to the list of imported modules sys.modules.
The execution of importing of moduleOne starts by importing moduleTwo. Now moduleTwo is read from file and added to the list of imported modules sys.modules. Note at this stage the rest of moduleOne hasn't been executed yet so sayHi is not defined.
Now moduleTwo starts execution by importing testimports. This is the first time testimports is imported and it has nothing to do with it being the same as __main__. It is now inserted into sys.modules.
Here is where things get interesting. The newly imported testimports imports moduleOne. But moduleOne is already in sys.modules, so it is not read again. Then the execution progresses to the line moduleOne.sayHi(). But the importing of moduleOne hasn't finished and sayHi is not yet defined. Hence we get the error.
A similar loop happens if moduleTwo is uncommented. In essence, __main__ imports moduleTwo which imports testimports which passes the import of moduleTwo which is already imported and imports moduleOne; which in turn imports moduleTwo and then tries to call moduleTwo.printHi which isn't defined yet because moduleTwo hasn't finished execution all this time.
Anatoly Rr's solution breaks all this by making the module testimports not call any other module functionality when imported. So when it is imported by moduleTwo it doesn't call moduleOne.sayHi. Only when started as __main__ will it execute that so that execution is delayed after all the imports.
The moral of the story? Avoid circular dependencies in Python if possible.
A:
Rewriting testimports.py may help:
import moduleOne
hiString = "Hi!"
def main ():
moduleOne.sayHi()
if __name__ == "__main__":
main ()
A:
Your problem is that when Python imports something it executes all statements at the base level. hiString is assigned to again and the call is made again when Module3 imports your original testimports.py as a module. Anatoly Rr's solution works because the call is now inside a def. The def is not called because the __name__ indicates to the Python runtime that the module is being imported. When it is being called from the command line it's module name would be __main__.
| How to fix a circular dependency for imports | I have three files:
testimports module:
#import moduleTwo
import moduleOne
hiString = "Hi!"
moduleOne.sayHi()
moduleOne:
import moduleTwo
class sayHi():
moduleTwo.printHi()
moduleTwo:
import testimports
def printHi():
print(testimports.hiString)
If I run testimports, I get:
Traceback (most recent call last):
File "..file path snipped../testimports/src/testimports.py", line 2, in <module>
import moduleOne
File "..file path snipped../testimports/src/moduleOne.py", line 1, in <module>
import moduleTwo
File "..file path snipped../testimports/src/moduleTwo.py", line 1, in <module>
import testimports
File "..file path snipped../testimports/src/testimports.py", line 6, in <module>
moduleOne.sayHi()
AttributeError: 'module' object has no attribute 'sayHi'
If, however, I uncomment the import moduleTwo line in testimports, the program gets to this point before it stops working:
Traceback (most recent call last):
File "..file path snipped../testimports/src/testimports.py", line 1, in <module>
import moduleTwo
File "..file path snipped../testimports/src/moduleTwo.py", line 1, in <module>
import testimports
File "..file path snipped../testimports/src/testimports.py", line 2, in <module>
import moduleOne
File "..file path snipped../testimports/src/moduleOne.py", line 3, in <module>
class sayHi():
File "..file path snipped../testimports/src/moduleOne.py", line 4, in sayHi
moduleTwo.printHi()
AttributeError: 'module' object has no attribute 'printHi'
How would I go about resolving this circular dependency problem?
| [
"verisimilidude is along the right direction. I would expand a little to give more details.\nIn both cases, this is what happens:\n\ntestimports is executed as __main__\ntestimports imports moduleOne. Now moduleOne is read from file and added to the list of imported modules sys.modules.\nThe execution of importing ... | [
9,
2,
2
] | [] | [] | [
"circular_dependency",
"import",
"python",
"python_3.x"
] | stackoverflow_0003739654_circular_dependency_import_python_python_3.x.txt |
Q:
is there a compatible TCL environment variable for cygwin and python idle
Idle stopped working after installing cygwin and after some troubleshooting (on windows if its not obvious), it looks like the issue is with a TCL library. They both use an environment variable to locate tcl. when I installed cygwin, it overwrote the variable to a different (and incompatible to python) version. Now I figure I can just change the variable, but it seems kind of a hassle to switch between them all of the time. Does anyone have a good solution to this? (besides not using cygwin or something...)
A:
If you could change the variable, you know already which it is, and to which value it is set. Would you kindly share this information, maybe someone can make an educated guess?
| is there a compatible TCL environment variable for cygwin and python idle | Idle stopped working after installing cygwin and after some troubleshooting (on windows if its not obvious), it looks like the issue is with a TCL library. They both use an environment variable to locate tcl. when I installed cygwin, it overwrote the variable to a different (and incompatible to python) version. Now I figure I can just change the variable, but it seems kind of a hassle to switch between them all of the time. Does anyone have a good solution to this? (besides not using cygwin or something...)
| [
"If you could change the variable, you know already which it is, and to which value it is set. Would you kindly share this information, maybe someone can make an educated guess?\n"
] | [
0
] | [] | [] | [
"cygwin",
"python",
"tcl"
] | stackoverflow_0003739837_cygwin_python_tcl.txt |
Q:
Converting a hex-string representation to actual bytes in Python
i need to load the third column of this text file as a hex string
http://www.netmite.com/android/mydroid/1.6/external/skia/emoji/gmojiraw.txt
>>> open('gmojiraw.txt').read().split('\n')[0].split('\t')[2]
'\\xF3\\xBE\\x80\\x80'
how do i open the file so that i can get the third column as hex string:
'\xF3\xBE\x80\x80'
i also tried binary mode and hex mode, with no success.
A:
You can:
Remove the \x-es
Use .decode('hex') on the resulting string
Code:
>>> '\\xF3\\xBE\\x80\\x80'.replace('\\x', '').decode('hex')
'\xf3\xbe\x80\x80'
Note the appropriate interpretation of backslashes. When the string representation is '\xf3' it means it's a single-byte string with the byte value 0xF3. When it's '\\xf3', which is your input, it means a string consisting of 4 characters: \, x, f and 3
A:
Quick'n'dirty reply
your_string.decode('string_escape')
>>> a='\\xF3\\xBE\\x80\\x80'
>>> a.decode('string_escape')
'\xf3\xbe\x80\x80'
>>> len(_)
4
Bonus info
>>> u='\uDBB8\uDC03'
>>> u.decode('unicode_escape')
Some trivia
What's interesting, is that I have Python 2.6.4 on Karmic Koala Ubuntu (sys.maxunicode==1114111) and Python 2.6.5 on Gentoo (sys.maxunicode==65535); on Ubuntu, the unicode_escape-decode result is \uDBB8\uDC03 and on Gentoo it's u'\U000fe003', both correctly of length 2. Unless it's something fixed between 2.6.4 and 2.6.5, I'm impressed the 2-byte-per-unicode-character Gentoo version reports the correct character.
A:
If you are using Python2.6+ here is a safe way to use eval
>>> from ast import literal_eval
>>> item='\\xF3\\xBE\\x80\\x80'
>>> literal_eval("'%s'"%item)
'\xf3\xbe\x80\x80'
A:
After stripping out the "\x" as Eli's answer, you can just do:
int("F3BE8080",16)
A:
If you trust the source, you can use eval('"%s"' % data)
| Converting a hex-string representation to actual bytes in Python | i need to load the third column of this text file as a hex string
http://www.netmite.com/android/mydroid/1.6/external/skia/emoji/gmojiraw.txt
>>> open('gmojiraw.txt').read().split('\n')[0].split('\t')[2]
'\\xF3\\xBE\\x80\\x80'
how do i open the file so that i can get the third column as hex string:
'\xF3\xBE\x80\x80'
i also tried binary mode and hex mode, with no success.
| [
"You can:\n\nRemove the \\x-es\nUse .decode('hex') on the resulting string\n\nCode:\n>>> '\\\\xF3\\\\xBE\\\\x80\\\\x80'.replace('\\\\x', '').decode('hex')\n'\\xf3\\xbe\\x80\\x80'\n\nNote the appropriate interpretation of backslashes. When the string representation is '\\xf3' it means it's a single-byte string with ... | [
7,
7,
5,
1,
0
] | [] | [] | [
"hex",
"python",
"representation"
] | stackoverflow_0003519125_hex_python_representation.txt |
Q:
Trying to find all the combinations of values inside N lists
I am trying to compare all combinations of the values in N lists. Each list is identical holding values 1 through 9 in order. I am having a very hard time figuring out how to code this because I cannot create N nested loops beforehand. N is user defined and won't be known until run time. The place I always get stuck on is trying to iterate through every possible combination of values in an arbitrary number of lists using a fixed number of loops.
Any suggestions? I've been trying for an hour now to figure this out. I'm sure it is something simple I am missing.
A:
import itertools
for combo in itertools.product(xrange(1, 10), repeat=N):
...
| Trying to find all the combinations of values inside N lists | I am trying to compare all combinations of the values in N lists. Each list is identical holding values 1 through 9 in order. I am having a very hard time figuring out how to code this because I cannot create N nested loops beforehand. N is user defined and won't be known until run time. The place I always get stuck on is trying to iterate through every possible combination of values in an arbitrary number of lists using a fixed number of loops.
Any suggestions? I've been trying for an hour now to figure this out. I'm sure it is something simple I am missing.
| [
"import itertools\nfor combo in itertools.product(xrange(1, 10), repeat=N):\n ...\n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0003740178_python.txt |
Q:
i got this error: "ImportError: cannot import name python" How do I fix it?
File "G:\Python25\Lib\site-packages\PyAMF-0.6b2-py2.5-win32.egg\pyamf\util\__init__.py", line 15, in <module>
ImportError: cannot import name python
How do I fix it?
If you need any info to know how to fix this problem, I can explain, just ask.
Thanks
Code:
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import webapp
from TottysGateway import TottysGateway
import logging
def main():
services_root = 'services'
#services = ['users.login']
#gateway = TottysGateway(services, services_root, logger=logging, debug=True)
#app = webapp.WSGIApplication([('/', gateway)], debug=True)
#run_wsgi_app(app)
if __name__ == "__main__":
main()
Code:
from pyamf.remoting.gateway.google import WebAppGateway
import logging
class TottysGateway(WebAppGateway):
def __init__(self, services_available, root_path, not_found_service, logger, debug):
# override the contructor and then call the super
self.services_available = services_available
self.root_path = root_path
self.not_found_service = not_found_service
WebAppGateway.__init__(self, {}, logger=logging, debug=True)
def getServiceRequest(self, request, target):
# override the original getServiceRequest method
try:
# try looking for the service in the services list
return WebAppGateway.getServiceRequest(self, request, target)
except:
pass
try:
# don't know what it does but is an error for now
service_func = self.router(target)
except:
if(target in self.services_available):
# only if is an available service import it's module
# so it doesn't access services that should be hidden
try:
module_path = self.root_path + '.' + target
paths = target.rsplit('.')
func_name = paths[len(paths) - 1]
import_as = '_'.join(paths) + '_' + func_name
import_string = "from "+module_path+" import "+func_name+' as service_func'
exec import_string
except:
service_func = False
if(not service_func):
# if is not found load the default not found service
module_path = self.rootPath + '.' + self.not_found_service
import_string = "from "+module_path+" import "+func_name+' as service_func'
# add the service loaded above
assign_string = "self.addService(service_func, target)"
exec assign_string
return WebAppGateway.getServiceRequest(self, request, target)
A:
You need to post your full traceback. What you show here isn't all that useful. I ended up digging up line 15 of pyamf/util/init.py. The code you should have posted is
from pyamf import python
This should not fail unless your local environment is messed up.
Can you 'import pyamf.util' and 'import pyamf.python' in a interactive Python shell? What about if you start Python while in /tmp (on the assumption that you might have a file named 'pyamf.py' in the current directory. Which is a bad thing.)
= (older comment below) =
Fix your question. I can't even tell where line 15 of util/__init__.py is supposed to be. Since I can't figure that out, I can't answer your question. Instead, I'll point out ways to improve your question and code.
First, use the markup language correctly, so that all the code is in a code block. Make sure you've titled the code, so we know it's from util/__init__.py and not some random file.
In your error message, include the full traceback, and not the last two lines.
Stop using parens in things like "if(not service_func):" and use a space instead, so its " if not service_func:". This is discussed in PEP 8.
Read the Python documentation and learn how to use the language. Something like "func_name = paths[len(paths) - 1]" should be "func_name = paths[-1]"
Learn about the import function and don't use "exec" for this case. Nor do you need the "exec assign_string" -- just do the "self.addService(service_func, target)"
| i got this error: "ImportError: cannot import name python" How do I fix it? | File "G:\Python25\Lib\site-packages\PyAMF-0.6b2-py2.5-win32.egg\pyamf\util\__init__.py", line 15, in <module>
ImportError: cannot import name python
How do I fix it?
If you need any info to know how to fix this problem, I can explain, just ask.
Thanks
Code:
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import webapp
from TottysGateway import TottysGateway
import logging
def main():
services_root = 'services'
#services = ['users.login']
#gateway = TottysGateway(services, services_root, logger=logging, debug=True)
#app = webapp.WSGIApplication([('/', gateway)], debug=True)
#run_wsgi_app(app)
if __name__ == "__main__":
main()
Code:
from pyamf.remoting.gateway.google import WebAppGateway
import logging
class TottysGateway(WebAppGateway):
def __init__(self, services_available, root_path, not_found_service, logger, debug):
# override the contructor and then call the super
self.services_available = services_available
self.root_path = root_path
self.not_found_service = not_found_service
WebAppGateway.__init__(self, {}, logger=logging, debug=True)
def getServiceRequest(self, request, target):
# override the original getServiceRequest method
try:
# try looking for the service in the services list
return WebAppGateway.getServiceRequest(self, request, target)
except:
pass
try:
# don't know what it does but is an error for now
service_func = self.router(target)
except:
if(target in self.services_available):
# only if is an available service import it's module
# so it doesn't access services that should be hidden
try:
module_path = self.root_path + '.' + target
paths = target.rsplit('.')
func_name = paths[len(paths) - 1]
import_as = '_'.join(paths) + '_' + func_name
import_string = "from "+module_path+" import "+func_name+' as service_func'
exec import_string
except:
service_func = False
if(not service_func):
# if is not found load the default not found service
module_path = self.rootPath + '.' + self.not_found_service
import_string = "from "+module_path+" import "+func_name+' as service_func'
# add the service loaded above
assign_string = "self.addService(service_func, target)"
exec assign_string
return WebAppGateway.getServiceRequest(self, request, target)
| [
"You need to post your full traceback. What you show here isn't all that useful. I ended up digging up line 15 of pyamf/util/init.py. The code you should have posted is\nfrom pyamf import python\n\nThis should not fail unless your local environment is messed up.\nCan you 'import pyamf.util' and 'import pyamf.python... | [
1
] | [] | [] | [
"pyamf",
"python"
] | stackoverflow_0003738110_pyamf_python.txt |
Q:
extending scripting integration to an existing lib
I found swig can generate script wrapper for various scripting languages.
I've a 3rd party static library, a header file and a lib.
How can I use swig so that I can call functions from that library from a scripting language, say python?
Thanks
A:
Try reading the swig documentation. It walks through examples of how to do exactly this.
| extending scripting integration to an existing lib | I found swig can generate script wrapper for various scripting languages.
I've a 3rd party static library, a header file and a lib.
How can I use swig so that I can call functions from that library from a scripting language, say python?
Thanks
| [
"Try reading the swig documentation. It walks through examples of how to do exactly this.\n"
] | [
0
] | [] | [] | [
"python",
"scripting",
"swig"
] | stackoverflow_0003733380_python_scripting_swig.txt |
Q:
How can I call a inner function from the Python shell?
I have some code (that I can't easily modify), of the following form:
def foo(x):
do_other_stuff_that_I_do_not_want_to_do()
def bar():
"do something"
str(x)
bar()
I would like to call bar(), directly, from the Python shell. I don't mind using co_globals, or other internal bits. I have the feeling that this may be impossible; is it?
A:
It is impossible to get at the inner function object with the code as you've stated it -- said object is only created (by the def statement) when the outer function runs (i.e., when it gets called).
As an aside, note that outer functions like foo are often coded to return the inner function as their result (e.g. by changing bar() to return bar) as the last line, exactly to work as "function factories" (often, as "closure factories") rather than keep the very existence of an internal function as a kind of private, secret implementation detail; but your coding picks the latter route instead.
Edit...:
It is possible to get at the code object for the inner function, however:
>>> def outer():
... def inner(): return 'boo'
... print inner()
...
>>> eval(outer.func_code.co_consts[1])
'boo'
>>>
However, in general, to make a code object into a callable function requires considerable work (in this special case an eval suffices because the inner function has no arguments nor any nonlocal variables, but of course that's not anywhere even close to the general case... in which you do have to supply such niceties as bindings for nonlocals!-)
| How can I call a inner function from the Python shell? | I have some code (that I can't easily modify), of the following form:
def foo(x):
do_other_stuff_that_I_do_not_want_to_do()
def bar():
"do something"
str(x)
bar()
I would like to call bar(), directly, from the Python shell. I don't mind using co_globals, or other internal bits. I have the feeling that this may be impossible; is it?
| [
"It is impossible to get at the inner function object with the code as you've stated it -- said object is only created (by the def statement) when the outer function runs (i.e., when it gets called).\nAs an aside, note that outer functions like foo are often coded to return the inner function as their result (e.g. ... | [
4
] | [] | [] | [
"nested",
"private_methods",
"python"
] | stackoverflow_0003740467_nested_private_methods_python.txt |
Q:
List sorted by categories in Tkinter?
I'm building a graphical program that will need to show files on both the user's computer and on a remote server. I'm using Tkinter, and I'm definitely a novice with this toolkit. I want to have the files displayed in a box similar to what you would get from a "Details" view in Windows, so that each file has several categories of info(think name, type, size, permissions, etc.) about it and so that the list can be sorted by category, ascending or descending.
What objects in Tkinter (if any) could I use to accomplish this? Is there a tutorial or an existing project that implements something similar with Tkinter?
I'm not sure if my description makes sense, so here's a screenshot of what I want:
A:
TreeView widget should help you
http://www.tkdocs.com/tutorial/tree.html
http://docs.python.org/dev/library/tkinter.ttk.html#ttk-treeview
http://m-eken.com/2010/03/02/treeview-in-python-tkinter/
Yeah , So already has one on this topic
Tk treeview column sort
You should be able to get started from these pointers
| List sorted by categories in Tkinter? | I'm building a graphical program that will need to show files on both the user's computer and on a remote server. I'm using Tkinter, and I'm definitely a novice with this toolkit. I want to have the files displayed in a box similar to what you would get from a "Details" view in Windows, so that each file has several categories of info(think name, type, size, permissions, etc.) about it and so that the list can be sorted by category, ascending or descending.
What objects in Tkinter (if any) could I use to accomplish this? Is there a tutorial or an existing project that implements something similar with Tkinter?
I'm not sure if my description makes sense, so here's a screenshot of what I want:
| [
"TreeView widget should help you\n\nhttp://www.tkdocs.com/tutorial/tree.html\nhttp://docs.python.org/dev/library/tkinter.ttk.html#ttk-treeview\nhttp://m-eken.com/2010/03/02/treeview-in-python-tkinter/\n\nYeah , So already has one on this topic\n\nTk treeview column sort\n\nYou should be able to get started from the... | [
1
] | [] | [] | [
"detailsview",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0003740590_detailsview_python_tkinter_user_interface.txt |
Q:
Python. Showing text from a file in fragments of 20 lines every time ENTER is pressed
This is the code i have at the moment
print "Please input the filename:"
n = raw_input()
f = open(n,"r")
x = 0
for line in f.readlines():
print line
x+=1
if x % 20 == 0:
break
q = raw_input()
if q == "":
x+= 20
continue
Things the program should do:
1) Ask for a filename
2) Read the file
3) Print the first 20 lines of the file
4) Stop working after the first 20 lines and wait for an Enter keypress
5) If Enter is pressed show the next 20 lines of the file (20->40 and so on)
Current problem: The loop doesn't restart, it only shows the first 20 lines and then stops working.
A:
Basically, you want to pause every 20 lines. Currently, you're breaking out of your loop after the first 20 lines.
for line in f:
print line
x += 1
if x % 20 == 0:
raw_input("Hit enter")
should suffice.
A:
filename = raw_input("Please enter the file name: ")
with open(filename) as f:
lines = f.readlines()
for i in xrange(0, len(lines), 20):
print lines[i:i+20]
raw_input("Press Enter for more")
This reads the whole file into memory so you might not want to use slices if it's a huge file. But if it's a huge file, you're unlikely to want to step through it twenty lines at a time ;)
The major change is that we are opening the file using a with statement. This is much nicer than using open/close and guarantees that the file will always be closed.
in the code that you posted, when you executed break, you were exiting your look. break leaves the loop so you only want to use it for that purpose. just calling a blocking operation likeraw_input` suffices if you just need to pause execution for some reason (like waiting on the user).
also, the continue is entirely unnecessary. At the end of the body of a loop, it has no choice but to continue
What were you thinking with the linesif q == "": x += 20? first off, it should just be if not q: x += 20 (empty string (like empty lists/dicts/tuples) evaluates to False) and second, this would skip the next 20 lines. Is this a requirement that you haven't shared?
| Python. Showing text from a file in fragments of 20 lines every time ENTER is pressed | This is the code i have at the moment
print "Please input the filename:"
n = raw_input()
f = open(n,"r")
x = 0
for line in f.readlines():
print line
x+=1
if x % 20 == 0:
break
q = raw_input()
if q == "":
x+= 20
continue
Things the program should do:
1) Ask for a filename
2) Read the file
3) Print the first 20 lines of the file
4) Stop working after the first 20 lines and wait for an Enter keypress
5) If Enter is pressed show the next 20 lines of the file (20->40 and so on)
Current problem: The loop doesn't restart, it only shows the first 20 lines and then stops working.
| [
"Basically, you want to pause every 20 lines. Currently, you're breaking out of your loop after the first 20 lines.\nfor line in f:\n print line\n x += 1\n if x % 20 == 0:\n raw_input(\"Hit enter\")\n\nshould suffice.\n",
"filename = raw_input(\"Please enter the file name: \")\nwith open(filename)... | [
1,
0
] | [] | [] | [
"input",
"loops",
"python"
] | stackoverflow_0003740915_input_loops_python.txt |
Q:
Total number of live sessions on GAE
Is there a way to count total number of active sessions (e.g. in 10 minutes) on Google App Engine (Python)?
I want to show something on frontpage like, This site currently haz 200 people online
A:
Considering the distributed nature of GAE, I don't think you can do this directly.
You can store visits in the database (with timestamp) and query this (use a cookie to check if a user is already counted, avoid writing on each request!).
Alternatively, you can use some external service that uses included javascript or image that counts this for you, much like how analytics works.
| Total number of live sessions on GAE | Is there a way to count total number of active sessions (e.g. in 10 minutes) on Google App Engine (Python)?
I want to show something on frontpage like, This site currently haz 200 people online
| [
"Considering the distributed nature of GAE, I don't think you can do this directly. \nYou can store visits in the database (with timestamp) and query this (use a cookie to check if a user is already counted, avoid writing on each request!).\nAlternatively, you can use some external service that uses included javasc... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003740932_google_app_engine_python.txt |
Q:
Raw input and printing simultaneously
So I have a threaded Python program that takes input from a user and prints data simultaneously. The problem is that when the program is sitting at raw_input(), it won't print anything and will print it all after the user presses enter.
Is there any way to have user input and print at the same time?
A:
You have two options, basically: threading and asynchronous IO.
You can have one thread fill a Queue with entered data and have the other thread print its contents. Be warned that threading is hard (impossible?) to do right.
Asynchronous IO means you have a main dispatcher that invokes callbacks when data is available (i.e. the user has entered data). There are frameworks that abstract most of this for you, such as asyncore and Twisted.
Most GUI toolkits will also implement an asynchronous dispatching system through their mainloop, ie.. Tkinter, wxWidgets and pygtk. This will also solve the interface problems you have when mixing reading from and writing to the same (terminal) screen.
| Raw input and printing simultaneously | So I have a threaded Python program that takes input from a user and prints data simultaneously. The problem is that when the program is sitting at raw_input(), it won't print anything and will print it all after the user presses enter.
Is there any way to have user input and print at the same time?
| [
"You have two options, basically: threading and asynchronous IO. \nYou can have one thread fill a Queue with entered data and have the other thread print its contents. Be warned that threading is hard (impossible?) to do right.\nAsynchronous IO means you have a main dispatcher that invokes callbacks when data is av... | [
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003740960_multithreading_python.txt |
Q:
WxPython - Resize WxFrame when adding new content?
Pretty much exactly as it sounds. I have buttons in a Wx.Frame that are created on the fly and I'd like the parent frame to increase in height as I add new buttons. The height is already being acquire from the total number of buttons multiplied by an integer equal the each button's height, but I don't know how to get the frame to change size based on that when new buttons are added.
As a side question the current method I have for updating the buttons creates a nasty flicker and I was wondering if anyone had any ideas for fixing that.
import wx
import mmap
import re
class pt:
with open('note.txt', "r+") as note:
buf = mmap.mmap(note.fileno(), 0)
TL = 0
readline = buf.readline
while readline():
TL += 1
readlist = note.readlines()
note.closed
class MainWindow(wx.Frame):
def __init__(self, parent, title):
w, h = wx.GetDisplaySize()
self.x = w * 0
self.y = h - bdepth
self.container = wx.Frame.__init__(self, parent, title = title, pos = (self.x, self.y), size = (224, bdepth), style = wx.STAY_ON_TOP)
self.__DoButtons()
self.Show(True)
def __DoButtons(self):
for i, line in enumerate(pt.readlist):
strip = line.rstrip('\n')
todo = strip.lstrip('!')
self.check = re.match('!', strip)
self.priority = re.search('(\!$)', strip)
if self.check is None and self.priority is None:
bullet = wx.Image('bullet.bmp', wx.BITMAP_TYPE_BMP)
solid = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(solid)
solidpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetPen(solidpen)
dc.DrawRectangle(0, 0, 200, 64)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawBitmap(wx.BitmapFromImage(bullet, 32), 10, 28)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
hover = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(hover)
hoverpen = wx.Pen(wx.Colour(100,100,100),wx.SOLID)
dc.SetPen(hoverpen)
dc.DrawRectangle(0, 0, 200, 64)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawBitmap(wx.BitmapFromImage(bullet, 32), 10, 28)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
bmp = solid
elif self.priority is None:
checkmark = wx.Image('check.bmp', wx.BITMAP_TYPE_BMP)
checked = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(checked)
checkedpen = wx.Pen(wx.Colour(50,50,50),wx.SOLID)
dc.SetPen(checkedpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(200, 255, 0))
dc.DrawBitmap(wx.BitmapFromImage(checkmark, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
bmp = checked
else:
exclaim = wx.Image('exclaim.bmp', wx.BITMAP_TYPE_BMP)
important = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(important)
importantpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetPen(importantpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 180, 0))
dc.DrawBitmap(wx.BitmapFromImage(exclaim, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
importanthover = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(importanthover)
importanthoverpen = wx.Pen(wx.Colour(100,100,100),wx.SOLID)
dc.SetPen(importanthoverpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 180, 0))
dc.DrawBitmap(wx.BitmapFromImage(exclaim, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
bmp = important
b = wx.BitmapButton(self, i + 800, bmp, (10, i * 64), (bmp.GetWidth(), bmp.GetHeight()), style = wx.NO_BORDER)
if self.check is None and self.priority is None:
b.SetBitmapHover(hover)
elif self.priority is None:
b.SetBitmapHover(checked)
else:
b.SetBitmapHover(importanthover)
self.input = wx.TextCtrl(self, -1, "", (16, pt.TL * 64 + 4), (184, 24))
self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter, self.input)
def OnClick(self, event):
button = event.GetEventObject()
button.None
print('cheese')
def OnEnter(self, event):
value = self.input.GetValue()
pt.readlist.append('\n' + value)
self.__DoButtons()
with open('note.txt', "r+") as note:
for item in pt.readlist:
note.write("%s" % item)
note.closed
bdepth = pt.TL * 64 + 32
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.SetTopWindow(frame)
app.MainLoop()
A:
Don't double-prefix your methods unless you know what you're doing. This is not directly related to your question, but it'll result in bugs you won't understand later.
See this stackoverflow question and the python documentation what/why.
A:
AFAIK there no way automatically resize the frame, but you can manually reset the size of your frame with SetSize()
e.g.
w, h = self.GetClientSize()
self.SetSize((w, h + height_of_your_new_button))
To the get the desired result though with minimum hassle you'll need to use sizers, I don't think theres ever a good reason to use absolute positioning. I would also recommend using a panel, which provides tab traversal between widgets and cross platform consistency of layout.
Zetcode Sizer Tutorial
wxPython Sizer Tutorial
| WxPython - Resize WxFrame when adding new content? | Pretty much exactly as it sounds. I have buttons in a Wx.Frame that are created on the fly and I'd like the parent frame to increase in height as I add new buttons. The height is already being acquire from the total number of buttons multiplied by an integer equal the each button's height, but I don't know how to get the frame to change size based on that when new buttons are added.
As a side question the current method I have for updating the buttons creates a nasty flicker and I was wondering if anyone had any ideas for fixing that.
import wx
import mmap
import re
class pt:
with open('note.txt', "r+") as note:
buf = mmap.mmap(note.fileno(), 0)
TL = 0
readline = buf.readline
while readline():
TL += 1
readlist = note.readlines()
note.closed
class MainWindow(wx.Frame):
def __init__(self, parent, title):
w, h = wx.GetDisplaySize()
self.x = w * 0
self.y = h - bdepth
self.container = wx.Frame.__init__(self, parent, title = title, pos = (self.x, self.y), size = (224, bdepth), style = wx.STAY_ON_TOP)
self.__DoButtons()
self.Show(True)
def __DoButtons(self):
for i, line in enumerate(pt.readlist):
strip = line.rstrip('\n')
todo = strip.lstrip('!')
self.check = re.match('!', strip)
self.priority = re.search('(\!$)', strip)
if self.check is None and self.priority is None:
bullet = wx.Image('bullet.bmp', wx.BITMAP_TYPE_BMP)
solid = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(solid)
solidpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetPen(solidpen)
dc.DrawRectangle(0, 0, 200, 64)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawBitmap(wx.BitmapFromImage(bullet, 32), 10, 28)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
hover = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(hover)
hoverpen = wx.Pen(wx.Colour(100,100,100),wx.SOLID)
dc.SetPen(hoverpen)
dc.DrawRectangle(0, 0, 200, 64)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawBitmap(wx.BitmapFromImage(bullet, 32), 10, 28)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
bmp = solid
elif self.priority is None:
checkmark = wx.Image('check.bmp', wx.BITMAP_TYPE_BMP)
checked = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(checked)
checkedpen = wx.Pen(wx.Colour(50,50,50),wx.SOLID)
dc.SetPen(checkedpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(200, 255, 0))
dc.DrawBitmap(wx.BitmapFromImage(checkmark, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
bmp = checked
else:
exclaim = wx.Image('exclaim.bmp', wx.BITMAP_TYPE_BMP)
important = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(important)
importantpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetPen(importantpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 180, 0))
dc.DrawBitmap(wx.BitmapFromImage(exclaim, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
importanthover = wx.EmptyBitmap(200,64,-1)
dc = wx.MemoryDC()
dc.SelectObject(importanthover)
importanthoverpen = wx.Pen(wx.Colour(100,100,100),wx.SOLID)
dc.SetPen(importanthoverpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 180, 0))
dc.DrawBitmap(wx.BitmapFromImage(exclaim, 32), 6, 24)
dc.DrawText(todo, 30, 24)
dc.SelectObject(wx.NullBitmap)
bmp = important
b = wx.BitmapButton(self, i + 800, bmp, (10, i * 64), (bmp.GetWidth(), bmp.GetHeight()), style = wx.NO_BORDER)
if self.check is None and self.priority is None:
b.SetBitmapHover(hover)
elif self.priority is None:
b.SetBitmapHover(checked)
else:
b.SetBitmapHover(importanthover)
self.input = wx.TextCtrl(self, -1, "", (16, pt.TL * 64 + 4), (184, 24))
self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter, self.input)
def OnClick(self, event):
button = event.GetEventObject()
button.None
print('cheese')
def OnEnter(self, event):
value = self.input.GetValue()
pt.readlist.append('\n' + value)
self.__DoButtons()
with open('note.txt', "r+") as note:
for item in pt.readlist:
note.write("%s" % item)
note.closed
bdepth = pt.TL * 64 + 32
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.SetTopWindow(frame)
app.MainLoop()
| [
"Don't double-prefix your methods unless you know what you're doing. This is not directly related to your question, but it'll result in bugs you won't understand later.\nSee this stackoverflow question and the python documentation what/why.\n",
"AFAIK there no way automatically resize the frame, but you can manua... | [
1,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003740640_python_wxpython.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.