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:
Why is printing to stdout so slow? Can it be sped up?
I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost all the time spent is waiting for the terminal to process the results.
Can writing to stdout be sped up somehow?
I wrote a script ('print_timer.py' at the bottom of this question) to compare timing when writing 100k lines to stdout, to file, and with stdout redirected to /dev/null. Here is the timing result:
$ python print_timer.py
this is a test
this is a test
<snipped 99997 lines>
this is a test
-----
timing summary (100k lines each)
-----
print :11.950 s
write to file (+ fsync) : 0.122 s
print with stdout = /dev/null : 0.050 s
Wow. To make sure python isn't doing something behind the scenes like recognizing that I reassigned stdout to /dev/null or something, I did the redirection outside the script...
$ python print_timer.py > /dev/null
-----
timing summary (100k lines each)
-----
print : 0.053 s
write to file (+fsync) : 0.108 s
print with stdout = /dev/null : 0.045 s
So it isn't a python trick, it is just the terminal. I always knew dumping output to /dev/null sped things up, but never figured it was that significant!
It amazes me how slow the tty is. How can it be that writing to physical disk is WAY faster than writing to the "screen" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null?
This link talks about how the terminal will block I/O so it can "parse [the input], update its frame buffer, communicate with the X server in order to scroll the window and so on"... but I don't fully get it. What can be taking so long?
I expect there is no way out (short of a faster tty implementation?) but figure I'd ask anyway.
UPDATE: after reading some comments I wondered how much impact my screen size actually has on the print time, and it does have some significance. The really slow numbers above are with my Gnome terminal blown up to 1920x1200. If I reduce it very small I get...
-----
timing summary (100k lines each)
-----
print : 2.920 s
write to file (+fsync) : 0.121 s
print with stdout = /dev/null : 0.048 s
That is certainly better (~4x), but doesn't change my question. It only adds to my question as I don't understand why the terminal screen rendering should slow down an application writing to stdout. Why does my program need to wait for screen rendering to continue?
Are all terminal/tty apps not created equal? I have yet to experiment. It really seems to me like a terminal should be able to buffer all incoming data, parse/render it invisibly, and only render the most recent chunk that is visible in the current screen configuration at a sensible frame rate. So if I can write+fsync to disk in ~0.1 seconds, a terminal should be able to complete the same operation in something of that order (with maybe a few screen updates while it did it).
I'm still kind of hoping there is a tty setting that can be changed from the application side to make this behaviour better for programmer. If this is strictly a terminal application issue, then this maybe doesn't even belong on StackOverflow?
What am I missing?
Here is the python program used to generate the timing:
import time, sys, tty
import os
lineCount = 100000
line = "this is a test"
summary = ""
cmd = "print"
startTime_s = time.time()
for x in range(lineCount):
print line
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)
#Add a newline to match line outputs above...
line += "\n"
cmd = "write to file (+fsync)"
fp = file("out.txt", "w")
startTime_s = time.time()
for x in range(lineCount):
fp.write(line)
os.fsync(fp.fileno())
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)
cmd = "print with stdout = /dev/null"
sys.stdout = file(os.devnull, "w")
startTime_s = time.time()
for x in range(lineCount):
fp.write(line)
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)
print >> sys.stderr, "-----"
print >> sys.stderr, "timing summary (100k lines each)"
print >> sys.stderr, "-----"
print >> sys.stderr, summary
A:
How can it be that writing to physical disk is WAY faster than writing to the "screen" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null?
Congratulations, you have just discovered the importance of I/O buffering. :-)
The disk appears to be faster, because it is highly buffered: all Python's write() calls are returning before anything is actually written to physical disk. (The OS does this later, combining many thousands of individual writes into a big, efficient chunks.)
The terminal, on the other hand, does little or no buffering: each individual print / write(line) waits for the full write (i.e. display to output device) to complete.
To make the comparison fair, you must make the file test use the same output buffering as the terminal, which you can do by modifying your example to:
fp = file("out.txt", "w", 1) # line-buffered, like stdout
[...]
for x in range(lineCount):
fp.write(line)
os.fsync(fp.fileno()) # wait for the write to actually complete
I ran your file writing test on my machine, and with buffering, it also 0.05s here for 100,000 lines.
However, with the above modifications to write unbuffered, it takes 40 seconds to write only 1,000 lines to disk. I gave up waiting for 100,000 lines to write, but extrapolating from the previous, it would take over an hour.
That puts the terminal's 11 seconds into perspective, doesn't it?
So to answer your original question, writing to a terminal is actually blazingly fast, all things considered, and there's not a lot of room to make it much faster (but individual terminals do vary in how much work they do; see Russ's comment to this answer).
(You could add more write buffering, like with disk I/O, but then you wouldn't see what was written to your terminal until after the buffer gets flushed. It's a trade-off: interactivity versus bulk efficiency.)
A:
Thanks for all the comments! I've ended up answering it myself with your help. It feels dirty answering your own question, though.
Question 1: Why is printing to stdout slow?
Answer: Printing to stdout is not inherently slow. It is the terminal you work with that is slow. And it has pretty much zero to do with I/O buffering on the application side (eg: python file buffering). See below.
Question 2: Can it be sped up?
Answer: Yes it can, but seemingly not from the program side (the side doing the 'printing' to stdout). To speed it up, use a faster different terminal emulator.
Explanation...
I tried a self-described 'lightweight' terminal program called wterm and got significantly better results. Below is the output of my test script (at the bottom of the question) when running in wterm at 1920x1200 in on the same system where the basic print option took 12s using gnome-terminal:
-----
timing summary (100k lines each)
-----
print : 0.261 s
write to file (+fsync) : 0.110 s
print with stdout = /dev/null : 0.050 s
0.26s is MUCH better than 12s! I don't know whether wterm is more intelligent about how it renders to screen along the lines of how I was suggesting (render the 'visible' tail at a reasonable frame rate), or whether it just "does less" than gnome-terminal. For the purposes of my question I've got the answer, though. gnome-terminal is slow.
So - If you have a long running script that you feel is slow and it spews massive amounts of text to stdout... try a different terminal and see if it is any better!
Note that I pretty much randomly pulled wterm from the ubuntu/debian repositories. This link might be the same terminal, but I'm not sure. I did not test any other terminal emulators.
Update: Because I had to scratch the itch, I tested a whole pile of other terminal emulators with the same script and full screen (1920x1200). My manually collected stats are here:
wterm 0.3s
aterm 0.3s
rxvt 0.3s
mrxvt 0.4s
konsole 0.6s
yakuake 0.7s
lxterminal 7s
xterm 9s
gnome-terminal 12s
xfce4-terminal 12s
vala-terminal 18s
xvt 48s
The recorded times are manually collected, but they were pretty consistent. I recorded the best(ish) value. YMMV, obviously.
As a bonus, it was an interesting tour of some of the various terminal emulators available out there! I'm amazed my first 'alternate' test turned out to be the best of the bunch.
A:
Your redirection probably does nothing as programs can determine whether their output FD points to a tty.
It's likely that stdout is line buffered when pointing to a terminal (the same as C's stdout stream behaviour).
As an amusing experiment, try piping the output to cat.
I've tried my own amusing experiment, and here are the results.
$ python test.py 2>foo
...
$ cat foo
-----
timing summary (100k lines each)
-----
print : 6.040 s
write to file : 0.122 s
print with stdout = /dev/null : 0.121 s
$ python test.py 2>foo |cat
...
$ cat foo
-----
timing summary (100k lines each)
-----
print : 1.024 s
write to file : 0.131 s
print with stdout = /dev/null : 0.122 s
A:
I can't talk about the technical details because I don't know them, but this doesn't surprise me: the terminal was not designed for printing lots of data like this. Indeed, you even provide a link to a load of GUI stuff that it has to do every time you want to print something! Notice that if you call the script with pythonw instead, it does not take 15 seconds; this is entirely a GUI issue. Redirect stdout to a file to avoid this:
import contextlib, io
@contextlib.contextmanager
def redirect_stdout(stream):
import sys
sys.stdout = stream
yield
sys.stdout = sys.__stdout__
output = io.StringIO
with redirect_stdout(output):
...
A:
Printing to the terminal is going to be slow. Unfortunately short of writing a new terminal implementation I can't really see how you'd speed this up significantly.
A:
In addition to the output probably defaulting to a line-buffered mode, output to a terminal is also causing your data to flow into a terminal and serial line with a maximum throughput, or a pseudo-terminal and a separate process that is handling a display event loop, rendering characters from some font, moving display bits to implement a scrolling display. The latter scenario is probably spread over multiple processes (e.g. telnet server/client, terminal app, X11 display server) so there are context switching and latency issues too.
| Why is printing to stdout so slow? Can it be sped up? | I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost all the time spent is waiting for the terminal to process the results.
Can writing to stdout be sped up somehow?
I wrote a script ('print_timer.py' at the bottom of this question) to compare timing when writing 100k lines to stdout, to file, and with stdout redirected to /dev/null. Here is the timing result:
$ python print_timer.py
this is a test
this is a test
<snipped 99997 lines>
this is a test
-----
timing summary (100k lines each)
-----
print :11.950 s
write to file (+ fsync) : 0.122 s
print with stdout = /dev/null : 0.050 s
Wow. To make sure python isn't doing something behind the scenes like recognizing that I reassigned stdout to /dev/null or something, I did the redirection outside the script...
$ python print_timer.py > /dev/null
-----
timing summary (100k lines each)
-----
print : 0.053 s
write to file (+fsync) : 0.108 s
print with stdout = /dev/null : 0.045 s
So it isn't a python trick, it is just the terminal. I always knew dumping output to /dev/null sped things up, but never figured it was that significant!
It amazes me how slow the tty is. How can it be that writing to physical disk is WAY faster than writing to the "screen" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null?
This link talks about how the terminal will block I/O so it can "parse [the input], update its frame buffer, communicate with the X server in order to scroll the window and so on"... but I don't fully get it. What can be taking so long?
I expect there is no way out (short of a faster tty implementation?) but figure I'd ask anyway.
UPDATE: after reading some comments I wondered how much impact my screen size actually has on the print time, and it does have some significance. The really slow numbers above are with my Gnome terminal blown up to 1920x1200. If I reduce it very small I get...
-----
timing summary (100k lines each)
-----
print : 2.920 s
write to file (+fsync) : 0.121 s
print with stdout = /dev/null : 0.048 s
That is certainly better (~4x), but doesn't change my question. It only adds to my question as I don't understand why the terminal screen rendering should slow down an application writing to stdout. Why does my program need to wait for screen rendering to continue?
Are all terminal/tty apps not created equal? I have yet to experiment. It really seems to me like a terminal should be able to buffer all incoming data, parse/render it invisibly, and only render the most recent chunk that is visible in the current screen configuration at a sensible frame rate. So if I can write+fsync to disk in ~0.1 seconds, a terminal should be able to complete the same operation in something of that order (with maybe a few screen updates while it did it).
I'm still kind of hoping there is a tty setting that can be changed from the application side to make this behaviour better for programmer. If this is strictly a terminal application issue, then this maybe doesn't even belong on StackOverflow?
What am I missing?
Here is the python program used to generate the timing:
import time, sys, tty
import os
lineCount = 100000
line = "this is a test"
summary = ""
cmd = "print"
startTime_s = time.time()
for x in range(lineCount):
print line
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)
#Add a newline to match line outputs above...
line += "\n"
cmd = "write to file (+fsync)"
fp = file("out.txt", "w")
startTime_s = time.time()
for x in range(lineCount):
fp.write(line)
os.fsync(fp.fileno())
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)
cmd = "print with stdout = /dev/null"
sys.stdout = file(os.devnull, "w")
startTime_s = time.time()
for x in range(lineCount):
fp.write(line)
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)
print >> sys.stderr, "-----"
print >> sys.stderr, "timing summary (100k lines each)"
print >> sys.stderr, "-----"
print >> sys.stderr, summary
| [
"\nHow can it be that writing to physical disk is WAY faster than writing to the \"screen\" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null?\n\nCongratulations, you have just discovered the importance of I/O buffering. :-)\nThe disk appears to be faster, becaus... | [
186,
109,
14,
4,
3,
2
] | [] | [] | [
"linux",
"printing",
"python",
"stdout",
"tty"
] | stackoverflow_0003857052_linux_printing_python_stdout_tty.txt |
Q:
Generate a list of length n with m possible elements
I need to generate a ton of lists in Python. Every list is of length 13, and I have 4 possible values that can go into each element. These are [1, -1, i, -i], but it could be whatever.
Thus I should get 4 * 4 * 4 ... * 4 = 4^13 = 67,108,864 lists, or more generally, m^n, given the info in the subject.
I tried the combinations_with_replacement method in Python's itertools, but with the following code I only get 560 results.
c = it.combinations_with_replacement([1,-1,np.complex(0,1), np.complex(0,-1)], 13)
print list(c)
I know that combinations do not care about order, so this result is probably right. However, when I use the permutations method instead, I can only pick the second argument <= the number of elements in the first argument.
Any idea how to accomplish this?
Thanks!
A:
I think you want
y = itertools.product((1, -1, 1j, -1j), repeat=13)
Then, btw, print sum(1 for x in y) prints, 67108864, as you expect.
| Generate a list of length n with m possible elements | I need to generate a ton of lists in Python. Every list is of length 13, and I have 4 possible values that can go into each element. These are [1, -1, i, -i], but it could be whatever.
Thus I should get 4 * 4 * 4 ... * 4 = 4^13 = 67,108,864 lists, or more generally, m^n, given the info in the subject.
I tried the combinations_with_replacement method in Python's itertools, but with the following code I only get 560 results.
c = it.combinations_with_replacement([1,-1,np.complex(0,1), np.complex(0,-1)], 13)
print list(c)
I know that combinations do not care about order, so this result is probably right. However, when I use the permutations method instead, I can only pick the second argument <= the number of elements in the first argument.
Any idea how to accomplish this?
Thanks!
| [
"I think you want\ny = itertools.product((1, -1, 1j, -1j), repeat=13)\n\n\nThen, btw, print sum(1 for x in y) prints, 67108864, as you expect.\n"
] | [
7
] | [] | [] | [
"combinations",
"permutation",
"python",
"python_itertools"
] | stackoverflow_0003860267_combinations_permutation_python_python_itertools.txt |
Q:
Is it ok to return None from __new__?
In general, is it reasonable to return None from a __new__ method if the user of the class knows that sometimes the constructor will evaluate to None?
The documentation doesn't imply it's illegal, and I don't see any immediate problems (since __init__ is not going to be called, None not being an instance of the custom class in question!). But I'm worried about
whether it might have other unforeseen issues
whether it's a good programming practice to have constructors return None
Specific example:
class MyNumber(int):
def __new__(cls, value): # value is a string (usually) parsed from a file
if value == 'N.A.':
return None
return int.__new__(cls, value)
A:
It's not illegal. If nothing weird is done with the result, it will work.
A:
You should avoid this. The documentation doesn't exhaustively list the things you shouldn't do, but it says what __new__ should do: return an instance of the class.
If you don't want to return a new object in some cases, raise an exception.
| Is it ok to return None from __new__? | In general, is it reasonable to return None from a __new__ method if the user of the class knows that sometimes the constructor will evaluate to None?
The documentation doesn't imply it's illegal, and I don't see any immediate problems (since __init__ is not going to be called, None not being an instance of the custom class in question!). But I'm worried about
whether it might have other unforeseen issues
whether it's a good programming practice to have constructors return None
Specific example:
class MyNumber(int):
def __new__(cls, value): # value is a string (usually) parsed from a file
if value == 'N.A.':
return None
return int.__new__(cls, value)
| [
"It's not illegal. If nothing weird is done with the result, it will work.\n",
"You should avoid this. The documentation doesn't exhaustively list the things you shouldn't do, but it says what __new__ should do: return an instance of the class.\nIf you don't want to return a new object in some cases, raise an e... | [
7,
3
] | [] | [] | [
"new_operator",
"python"
] | stackoverflow_0003860469_new_operator_python.txt |
Q:
about python datetime type
What's the equivalent type in types module for datetime? Example:
import datetime
import types
t=datetime.datetime.now()
if type(t)==types.xxxxxx:
do sth
I didn't find the relevent type in types module for the datetime type; could any one help me?
A:
>>> type(t)
<type 'datetime.datetime'>
>>> type(t) is datetime.datetime
True
Is that the information you're looking for? I don't think you'll be able to find the relevant type within the types module since datetime.datetime is not a builtin type.
Edit to add: Another note, since this is evidently what you were looking for (I wasn't entirely sure when I first answered) - type checking is generally not necessary in Python, and can be an indication of poor design. I'd recommend that you review your code and see if there's a way to do whatever it is you need to do without having to use type checking.
Also, the typical (canonical? pythonic) way to do this is with:
>>> isinstance(t, datetime.datetime)
True
See also: Differences between isinstance() and type() in python, but the main reason is that isinstance() supports inheritance whereas type() requires that both objects be of the exact same type (i.e. a derived type will evaluate to false when compared to its base type using the latter).
| about python datetime type | What's the equivalent type in types module for datetime? Example:
import datetime
import types
t=datetime.datetime.now()
if type(t)==types.xxxxxx:
do sth
I didn't find the relevent type in types module for the datetime type; could any one help me?
| [
">>> type(t)\n<type 'datetime.datetime'>\n>>> type(t) is datetime.datetime\nTrue\n\nIs that the information you're looking for? I don't think you'll be able to find the relevant type within the types module since datetime.datetime is not a builtin type.\nEdit to add: Another note, since this is evidently what you w... | [
14
] | [] | [] | [
"datetime",
"python",
"types"
] | stackoverflow_0003860482_datetime_python_types.txt |
Q:
How to parse and print fields from CSV data in python
I'm dealing with an application that exports text as as CSV type data. The text is broken up into fields where there was a hard return. I have been trying to use pythons CSV to restore the text.
This is an example of the text:
{"This is an example", "of what I what I have to deal with. ", "Please pick up th following:", "eggs", "milk", "Thanks for picking groceries up for me"}
What is the best way to read this output this text like so:
This is an example
of what I have to deal with.
Please pick up the following:
eggs
milk
Thanks for picking up the groceries for me
I have tried a number of ways that just haven't been quite right.
Here is what I am doing so far:
import csv
import xlrd
book = xlrd.open_workbook("book1.xls")
sh = book.sheet_by_index(0)
cat = 'Mister Peanuts'
for r in range(sh.nrows)[0:]:
cat_name = sh.cell_value(rowx=r, colx=1)
cat_behavior = sh.cell_value(rowx=r, colx=5)
if sh.cell_value(rowx=r, colx=1) == cat :
csv_reader = csv.reader( ([ cat_behavior ]), delimiter=',')
for row in csv_reader:
for item in row:
item = item.strip()
print(item)
pass
pass
So, the actual cell value that is returned for cat_behavior is the following:
['{"Mister Peanut spent 3.2 hours with {bojangles} fighting', ' "', ' "litter box was cleaned, sanitized and replaced "', ' " Food was replensished - with the best food possible"', ' ', ' "technician - don johnson performed all tasks"}']
I am now trying to take the above and run in through csv.reader to sanitize it and print it to a text file. I am now trying to make the (item) look normal.
A:
import csv
with open('test') as f:
for row in csv.reader(f):
for item in row:
item=item.strip('{} "')
print(item)
The strip method removes the specified characters from the left or right end of the string item.
A:
Please explain what you have got to start with.
x = {"This is an example", ......., "Thanks for picking groceries up for me"}
That looks like a set. Then you pass [x] as the first arg of csv.reader!! That doesn't work:
[Python 2.7]
>>> import csv
>>> x = {"foo", "bar", "baz"}
>>> rdr = csv.reader([x]) # comma is the default delimiter
>>> list(rdr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected string or Unicode object, set found
>>>
You say "application that exports text as as CSV type data" -- what does "exports" mean? If it means "writes to a file", please (if you can't follow the examples dotted all over the web) give us a dump of the file to look at. If it means "method/function returns a python object", please do print(repr(python_object)) and update your question with a copy/paste of the print output.
What documentation about the application output do you have?
Update after comments and question edited:
You say that the cell value "returned" was:
['{"Mister Peanut spent 3.2 hours with {bojangles} fighting', ' "', ' "litter box was cleaned, sanitized and replaced "', ' " Food was replensished - with the best food possible"', ' ', ' "technician - don johnson performed all tasks"}']
This looks like what you printed after passing the ACTUAL data through the CSV mangle, not the raw value extracted by xlrd, which certainly won't be a list; it would be a single unicode object.
In case you didn't read it before: Please explain what you have got to start with.
Do you think it possible to do these:
(1) please do print(repr(cat_behavior)) and update your question with a copy/paste of the print output.
(2) say what documentation you have about the application that creates the Excel file.
A:
You will need to look into csv.writer to export data to csv, rather than csv.reader.
EDIT: The body and title of question conflict. You're right about using csv.reader.You can use print in a for loop to achieve the result you are after.
A:
>>> s
'{"This is an example", "of what I what I have to deal with. ", "Please pick up th following:", "eggs", "milk", "Thanks for picking groceries up for me"}'
>>> print s.replace(",","\n").replace("{","").replace("}","").replace('"',"")
This is an example
of what I what I have to deal with.
Please pick up th following:
eggs
milk
Thanks for picking groceries up for me
>>> open("output.csv","w").write( s.replace(",","\n").replace("{","").replace("}","").replace('"',"") )
| How to parse and print fields from CSV data in python | I'm dealing with an application that exports text as as CSV type data. The text is broken up into fields where there was a hard return. I have been trying to use pythons CSV to restore the text.
This is an example of the text:
{"This is an example", "of what I what I have to deal with. ", "Please pick up th following:", "eggs", "milk", "Thanks for picking groceries up for me"}
What is the best way to read this output this text like so:
This is an example
of what I have to deal with.
Please pick up the following:
eggs
milk
Thanks for picking up the groceries for me
I have tried a number of ways that just haven't been quite right.
Here is what I am doing so far:
import csv
import xlrd
book = xlrd.open_workbook("book1.xls")
sh = book.sheet_by_index(0)
cat = 'Mister Peanuts'
for r in range(sh.nrows)[0:]:
cat_name = sh.cell_value(rowx=r, colx=1)
cat_behavior = sh.cell_value(rowx=r, colx=5)
if sh.cell_value(rowx=r, colx=1) == cat :
csv_reader = csv.reader( ([ cat_behavior ]), delimiter=',')
for row in csv_reader:
for item in row:
item = item.strip()
print(item)
pass
pass
So, the actual cell value that is returned for cat_behavior is the following:
['{"Mister Peanut spent 3.2 hours with {bojangles} fighting', ' "', ' "litter box was cleaned, sanitized and replaced "', ' " Food was replensished - with the best food possible"', ' ', ' "technician - don johnson performed all tasks"}']
I am now trying to take the above and run in through csv.reader to sanitize it and print it to a text file. I am now trying to make the (item) look normal.
| [
"import csv\nwith open('test') as f:\n for row in csv.reader(f):\n for item in row:\n item=item.strip('{} \"')\n print(item)\n\nThe strip method removes the specified characters from the left or right end of the string item.\n",
"Please explain what you have got to start with.\nx =... | [
1,
1,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003860095_csv_python.txt |
Q:
Python: Dictionary of list of lists
def makecounter():
return collections.defaultdict(int)
class RankedIndex(object):
def __init__(self):
self._inverted_index = collections.defaultdict(list)
self._documents = []
self._inverted_index = collections.defaultdict(makecounter)
def index_dir(self, base_path):
num_files_indexed = 0
allfiles = os.listdir(base_path)
self._documents = os.listdir(base_path)
num_files_indexed = len(allfiles)
docnumber = 0
self._inverted_index = collections.defaultdict(list)
docnumlist = []
for file in allfiles:
self.documents = [base_path+file] #list of all text files
f = open(base_path+file, 'r')
lines = f.read()
tokens = self.tokenize(lines)
docnumber = docnumber + 1
for term in tokens:
if term not in sorted(self._inverted_index.keys()):
self._inverted_index[term] = [docnumber]
self._inverted_index[term][docnumber] +=1
else:
if docnumber not in self._inverted_index.get(term):
docnumlist = self._inverted_index.get(term)
docnumlist = docnumlist.append(docnumber)
f.close()
print '\n \n'
print 'Dictionary contents: \n'
for term in sorted(self._inverted_index):
print term, '->', self._inverted_index.get(term)
return num_files_indexed
return 0
I get index error on executing this code: list index out of range.
The above code generates a dictionary index that stores the 'term' as a key and the document numbers in which the term occurs as a list.
For ex: if the term 'cat' occurs in documents 1.txt, 5.txt and 7.txt the dictionary will have:
cat <- [1,5,7]
Now, I have to modify it to add term frequency, so if the word cat occurs twice in document 1, thrice in document 5 and once in document 7:
expected result:
term <-[[docnumber, term freq], [docnumber,term freq]] <--list of lists in a dict!!!
cat <- [[1,2],[5,3],[7,1]]
I played around with the code, but nothing works. I have no clue to modify this datastructure to achieve the above.
Thanks in advance.
A:
First, use a factory. Start with:
def makecounter():
return collections.defaultdict(int)
and later use
self._inverted_index = collections.defaultdict(makecounter)
and as the for term in tokens: loop,
for term in tokens:
self._inverted_index[term][docnumber] +=1
This leaves in each self._inverted_index[term] a dict such as
{1:2,5:3,7:1}
in your example case. Since you want instead in each self._inverted_index[term] a list of lists, then just after the end of the looping add:
self._inverted_index = dict((t,[d,v[d] for d in sorted(v)])
for t in self._inverted_index)
Once made (this way or any other -- I'm just showing a simple way to construct it!), this data structure will then actually be as awkward to use as you needlessly made it difficult to construct, of course (the dict of dict is much more useful and easy to use as well as to construct), but, hey, one's man meat &c-).
A:
Here is a general algorithm you could use, but you will have adapt some of your code to it.
It produce a dict containing a dictionary of word counts for each file.
filedicts = {}
for file in allfiles:
filedicts[file] = {}
for term in terms:
filedict.setdefault(term, 0)
filedict[term] += 1
A:
Perhaps you could just create a simple class for (docname, frequency).
Then your dict could have lists of this new data type. You can do a list of lists, too, but a separate data type would be cleaner.
| Python: Dictionary of list of lists | def makecounter():
return collections.defaultdict(int)
class RankedIndex(object):
def __init__(self):
self._inverted_index = collections.defaultdict(list)
self._documents = []
self._inverted_index = collections.defaultdict(makecounter)
def index_dir(self, base_path):
num_files_indexed = 0
allfiles = os.listdir(base_path)
self._documents = os.listdir(base_path)
num_files_indexed = len(allfiles)
docnumber = 0
self._inverted_index = collections.defaultdict(list)
docnumlist = []
for file in allfiles:
self.documents = [base_path+file] #list of all text files
f = open(base_path+file, 'r')
lines = f.read()
tokens = self.tokenize(lines)
docnumber = docnumber + 1
for term in tokens:
if term not in sorted(self._inverted_index.keys()):
self._inverted_index[term] = [docnumber]
self._inverted_index[term][docnumber] +=1
else:
if docnumber not in self._inverted_index.get(term):
docnumlist = self._inverted_index.get(term)
docnumlist = docnumlist.append(docnumber)
f.close()
print '\n \n'
print 'Dictionary contents: \n'
for term in sorted(self._inverted_index):
print term, '->', self._inverted_index.get(term)
return num_files_indexed
return 0
I get index error on executing this code: list index out of range.
The above code generates a dictionary index that stores the 'term' as a key and the document numbers in which the term occurs as a list.
For ex: if the term 'cat' occurs in documents 1.txt, 5.txt and 7.txt the dictionary will have:
cat <- [1,5,7]
Now, I have to modify it to add term frequency, so if the word cat occurs twice in document 1, thrice in document 5 and once in document 7:
expected result:
term <-[[docnumber, term freq], [docnumber,term freq]] <--list of lists in a dict!!!
cat <- [[1,2],[5,3],[7,1]]
I played around with the code, but nothing works. I have no clue to modify this datastructure to achieve the above.
Thanks in advance.
| [
"First, use a factory. Start with:\ndef makecounter():\n return collections.defaultdict(int)\n\nand later use\nself._inverted_index = collections.defaultdict(makecounter)\n\nand as the for term in tokens: loop,\n for term in tokens: \n self._inverted_index[term][docnumber] +=1\n\nThis lea... | [
6,
1,
0
] | [] | [] | [
"information_retrieval",
"python"
] | stackoverflow_0003860568_information_retrieval_python.txt |
Q:
Decorators applied to class definition with Python
Compared to decorators applied to a function, it's not easy to understand the decorators applied to a class.
@foo
class Bar(object):
def __init__(self, x):
self.x = x
def spam(self):
statements
What's the use case of decorators to a class? How to use it?
A:
It replaces the vast majority of classic good uses for custom metaclasses in a much simpler way.
Think about it this way: nothing that's directly in the class body can refer to the class object, because the class object doesn't exist until well after the body's done running (it's the metaclass's job to create the class object -- usually type's, for all classes without a custom metaclass).
But, the code in the class decorator runs after the class object is created (indeed, with the class object as an argument!) and so can perfectly well refer to that class object (and usually needs to do so).
For example, consider:
def enum(cls):
names = getattr(cls, 'names', None)
if names is None:
raise TypeError('%r must have a class field `names` to be an `enum`!',
cls.__name__)
for i, n in enumerate(names):
setattr(cls, n, i)
return cls
@enum
class Color(object):
names = 'red green blue'.split()
and now you can refer to Color.red, Color.green, &c, rather than to 0, 1, etc. (Of course you normally would add even more functionality to make "an enum", but here I'm just showing the simple way to put such functionality addition in a class decorator, rather than needing a custom metaclass!-)
A:
One use case I can think of is if you want to wrap all the methods of a class with one function decorator. Say you have the following decorator:
def logit(f):
def res(*args, **kwargs):
print "Calling %s" % f.__name__
return f(*args, **kwargs)
return res
And the following class:
>>> class Pointless:
def foo(self): print 'foo'
def bar(self): print 'bar'
def baz(self): print 'baz'
>>> p = Pointless()
>>> p.foo(); p.bar(); p.baz()
foo
bar
baz
You can decorate all the methods:
>>> class Pointless:
@logit
def foo(self): print 'foo'
@logit
def bar(self): print 'bar'
@logit
def baz(self): print 'baz'
>>> p = Pointless()
>>> p.foo(); p.bar(); p.baz()
Calling foo
foo
Calling bar
bar
Calling baz
baz
But that is LAME! Instead you can do this:
>>> def logall(cls):
for a in dir(cls):
if callable(getattr(cls, a)):
setattr(cls, a, logit(getattr(cls, a)))
return cls
>>> @logall
class Pointless:
def foo(self): print 'foo'
def bar(self): print 'bar'
def baz(self): print 'baz'
>>> p = Pointless()
>>> p.foo(); p.bar(); p.baz()
Calling foo
foo
Calling bar
bar
Calling baz
baz
UPDATE: A more generic version of logall:
>>> def wrapall(method):
def dec(cls):
for a in dir(cls):
if callable(getattr(cls, a)):
setattr(cls, a, method(getattr(cls, a)))
return cls
return dec
>>> @wrapall(logit)
class Pointless:
def foo(self): print 'foo'
def bar(self): print 'bar'
def baz(self): print 'baz'
>>> p = Pointless()
>>> p.foo(); p.bar(); p.baz()
Calling foo
foo
Calling bar
bar
Calling baz
baz
>>>
Full disclosure: I've never had to do this and I just made this example up.
| Decorators applied to class definition with Python | Compared to decorators applied to a function, it's not easy to understand the decorators applied to a class.
@foo
class Bar(object):
def __init__(self, x):
self.x = x
def spam(self):
statements
What's the use case of decorators to a class? How to use it?
| [
"It replaces the vast majority of classic good uses for custom metaclasses in a much simpler way.\nThink about it this way: nothing that's directly in the class body can refer to the class object, because the class object doesn't exist until well after the body's done running (it's the metaclass's job to create the... | [
23,
6
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0003860539_decorator_python.txt |
Q:
Any free debug softwares that would allow me to peek into the workings of a compiled pyexe file?
I am trying to learn more about the mechanics of executable files, but I have no background in assembler code. Is there any program I can use for this purpose? I would like to be able to pause a program in real time and read its memory dump at that instant. Is there anything like that for windows 7 32? What about for windows 7 64?
Thanks
A:
I would suggest that you beef up on assembly programming.
Also read about and around windows executable format
http://msdn.microsoft.com/en-us/magazine/cc301805.aspx
http://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx
Others
- http://www.slideshare.net/rety61/a-handson-introduction-to-the-elf-object-file-format
You can also read the following book which uses windows tools too.
http://nostarch.com/ghpython.htm
Tools like pe reader
- http://code.google.com/p/pefile/
A:
Pyfunc has a good answer if you want to know the header and inner workings of PE executables (and the mention of ELF). He is also totally right about the assembly recommendation.
As for your disassembler request, I recommend OllyDBG for on-the-fly debugging, IDA Pro for code analysis and PEExplorer for PE (windows executables) headers analysis. SoftICE is prefered by many people for the debugging stage, though.
While these works for any compiled executable or library, languages running in a virtual mode (cross-platform bitcode or interpreted common language) like Java or .NET Framework are dealt differently. For example, a .NET executable would be easily analysable via a software like Reflector because it would allow to get back to the high level programming language instead of debugging assembly.
A good knowledge of what you are dealing with (language the software was written in, I/O operations, etc) will allow you to better discernate a program subtilities. You can use PEiD to help you with this analyse.
Please bear in mind that disassembly and reverse engineering can be illegal depending in which country you are and on which piece of software you apply it. If unsure, you should always use these kind of software on your own projects or programs your compiled yourself (OpenSource ones would be a good idea to begin with).
| Any free debug softwares that would allow me to peek into the workings of a compiled pyexe file? | I am trying to learn more about the mechanics of executable files, but I have no background in assembler code. Is there any program I can use for this purpose? I would like to be able to pause a program in real time and read its memory dump at that instant. Is there anything like that for windows 7 32? What about for windows 7 64?
Thanks
| [
"I would suggest that you beef up on assembly programming.\nAlso read about and around windows executable format\n\nhttp://msdn.microsoft.com/en-us/magazine/cc301805.aspx\nhttp://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx\n\nOthers\n - http://www.slideshare.net/rety61/a-handson-introduction-to-the-... | [
1,
1
] | [] | [] | [
"debugging",
"executable",
"python"
] | stackoverflow_0003860732_debugging_executable_python.txt |
Q:
Python regex: how to extract inner data from regex
I want to extract data from such regex:
<td>[a-zA-Z]+</td><td>[\d]+.[\d]+</td><td>[\d]+</td><td>[\d]+.[\d]+</td>
I've found related question extract contents of regex
but in my case I shoud iterate somehow.
A:
As paprika mentioned in his/her comment, you need to identify the desired parts of any matched text using ()'s to set off the capture groups. To get the contents from within the td tags, change:
<td>[a-zA-Z]+</td><td>[\d]+.[\d]+</td><td>[\d]+</td><td>[\d]+.[\d]+</td>
to:
<td>([a-zA-Z]+)</td><td>([\d]+.[\d]+)</td><td>([\d]+)</td><td>([\d]+.[\d]+)</td>
^^^^^^^^^ ^^^^^^^^^^^ ^^^^^ ^^^^^^^^^^^
group 1 group 2 group 3 group 4
And then access the groups by number. (Just the first line, the line with the '^'s and the one naming the groups are just there to help you see the capture groups as specified by the parentheses.)
dataPattern = re.compile(r"<td>[a-zA-Z]+</td>... etc.")
match = dataPattern.find(htmlstring)
field1 = match.group(1)
field2 = match.group(2)
and so on. But you should know that using re's to crack HTML source is one of the paths toward madness. There are many potential surprises that will lurk in your input HTML, that are perfectly working HTML, but will easily defeat your re:
"<TD>" instead of "<td>"
spaces between tags, or between data and tags
" " spacing characters
Libraries like BeautifulSoup, lxml, or even pyparsing will make for more robust web scrapers.
A:
As the poster clarified, the <td> tags should be removed from the string.
Note that the string you've shown us is just that: a string. Only if used in the context of regular expression functions is it a regular expression (a regexp object can be compiled from it).
You could remove the <td> tags as simply as this (assuming your string is stored in s):
s.replace('<td>','').replace('</td>','')
Watch out for the gotchas however: this is really of limited use in the context of real HTML, just as others pointed out.
Further, you should be aware that whatever regular expression [string] is left, what you can parse with that is probably not what you want, i.e. it's not going to automatically match anything that it matched before without <td> tags!
| Python regex: how to extract inner data from regex | I want to extract data from such regex:
<td>[a-zA-Z]+</td><td>[\d]+.[\d]+</td><td>[\d]+</td><td>[\d]+.[\d]+</td>
I've found related question extract contents of regex
but in my case I shoud iterate somehow.
| [
"As paprika mentioned in his/her comment, you need to identify the desired parts of any matched text using ()'s to set off the capture groups. To get the contents from within the td tags, change:\n<td>[a-zA-Z]+</td><td>[\\d]+.[\\d]+</td><td>[\\d]+</td><td>[\\d]+.[\\d]+</td> \n\nto:\n<td>([a-zA-Z]+)</td><td>([\\d]+... | [
7,
0
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0003860881_html_python_regex.txt |
Q:
How do I modify a single character in a string, in Python?
How do I modify a single character in a string, in Python? Something like:
a = "hello"
a[2] = "m"
'str' object does not support item assignment.
A:
Strings are immutable in Python. You can use a list of characters instead:
a = list("hello")
When you want to display the result use ''.join(a):
a[2] = 'm'
print ''.join(a)
A:
In python, string are immutable. If you want to change a single character, you'll have to use slicing:
a = "hello"
a = a[:2] + "m" + a[3:]
A:
Try constructing a list from it. When you pass an iterable into a list constructor, it will turn it into a list (this is a bit of an oversimplification, but usually works).
a = list("hello")
a[2] = m
You can then join it back up with ''.join(a).
A:
It's because strings in python are immutable.
| How do I modify a single character in a string, in Python? | How do I modify a single character in a string, in Python? Something like:
a = "hello"
a[2] = "m"
'str' object does not support item assignment.
| [
"Strings are immutable in Python. You can use a list of characters instead:\na = list(\"hello\")\n\nWhen you want to display the result use ''.join(a):\na[2] = 'm'\nprint ''.join(a)\n\n",
"In python, string are immutable. If you want to change a single character, you'll have to use slicing:\na = \"hello\"\na = a[... | [
15,
12,
8,
3
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003861026_python_string.txt |
Q:
Chaining operator functions in Python's filter
I have a list of objects and want to filter them according to some criteria. I can do it with list comprehension:
import datetime, pytz
# let's have a range of 100 hourly datetimes (just an example!):
dates = [ datetime.datetime(2010, 10, 1, 0, 0, 0, 0, pytz.utc) + datetime.timedelta(hours=i) for i in xrange(100) ]
# now I want a list of all dates, where hour in (0, 6, 12, 18)...
[ dt for dt in dates if dt.hour % 6 == 0 ]
Which works correctly.
How can I use the filter function (for much larger datasets, therefore the speed is important)? I can check whether dt.hour is True (not 0):
import operator
filter(operator.attrrgetter('hour'), dates)
but how can I put also the (6).__rmod__ part to it, which will tell me whether the hour attribute is divisible by 6?
A:
One way is to use a custom lambda function. This one is verbose for clarity.
filter(lambda dt: hasattr(dt, 'hour') and dt.hour % 6, dates)
The hasattr check is only necessary if you are expecting non date objects in the dates sequence.
I'd like to add a note that list comprehensions are preferred to map and filter. You could rewrite the above as:
[dt for dt in dates if hasattr(dt, 'hour') and dt.hour % 6]
A:
Unfortunately there's no prefab method for doing rmod, so best is to use a lambda (or a LC).
filter(lambda x: not x.hour % 6, dates)
| Chaining operator functions in Python's filter | I have a list of objects and want to filter them according to some criteria. I can do it with list comprehension:
import datetime, pytz
# let's have a range of 100 hourly datetimes (just an example!):
dates = [ datetime.datetime(2010, 10, 1, 0, 0, 0, 0, pytz.utc) + datetime.timedelta(hours=i) for i in xrange(100) ]
# now I want a list of all dates, where hour in (0, 6, 12, 18)...
[ dt for dt in dates if dt.hour % 6 == 0 ]
Which works correctly.
How can I use the filter function (for much larger datasets, therefore the speed is important)? I can check whether dt.hour is True (not 0):
import operator
filter(operator.attrrgetter('hour'), dates)
but how can I put also the (6).__rmod__ part to it, which will tell me whether the hour attribute is divisible by 6?
| [
"One way is to use a custom lambda function. This one is verbose for clarity.\nfilter(lambda dt: hasattr(dt, 'hour') and dt.hour % 6, dates)\n\nThe hasattr check is only necessary if you are expecting non date objects in the dates sequence. \nI'd like to add a note that list comprehensions are preferred to map and ... | [
4,
1
] | [] | [] | [
"filter",
"operators",
"python"
] | stackoverflow_0003861263_filter_operators_python.txt |
Q:
Read contents of a pdf file
Is there a commandline tool to read a pdf file on linux.Please indicate the appropriate urls for this.
Thanks..
A:
Xpdf and Poppler contain the commandline-utility pdftotext wich converts PDF files to plain text.
A:
Not a command line tool but a pdf reading and generation framework
http://www.reportlab.com/software/opensource/
you should also be able to write a simple reader using
http://pybrary.net/pyPdf/
http://code.activestate.com/recipes/511465-pure-python-pdf-to-text-converter/
you can also look at:
http://www.unixuser.org/~euske/python/pdfminer/index.html
A:
There is PyODConverter. It uses OpenOffice working as a service and can convert between various document formats including PDF and simple text.
| Read contents of a pdf file | Is there a commandline tool to read a pdf file on linux.Please indicate the appropriate urls for this.
Thanks..
| [
"Xpdf and Poppler contain the commandline-utility pdftotext wich converts PDF files to plain text.\n",
"Not a command line tool but a pdf reading and generation framework\n\nhttp://www.reportlab.com/software/opensource/\n\nyou should also be able to write a simple reader using\n\nhttp://pybrary.net/pyPdf/\nhttp:/... | [
5,
0,
0
] | [] | [] | [
"command_line",
"linux",
"pdf",
"python",
"shell"
] | stackoverflow_0003861158_command_line_linux_pdf_python_shell.txt |
Q:
Combining two lists of objects based on an attribute
Every example of list or set usage in Python seems to include trivial cases of integers but I have two lists of objects where the name attribute defines whether two objects instances are "the same" or not (other attributes might have different values).
I can create a list that contains all items from both lists, sorted, with
tmpList = sorted(list1 + list2, key=attrgetter('name'))
but how do I do the same so that list items that have the same value in the name attribute are selected from the second list?
E.g combining these two lists
list1 = [obj('Harry',18), obj('Mary',27), obj('Tim', 7)]
list2 = [obj('Harry', 22), obj('Mary', 27), obj('Frank', 40)]
would result in
list = [obj('Harry',22), obj('Mary', 27), obj('Tim', 7), obj('Frank', 40)]
(I used obj() as a short-hand notation for an object that has two attributes.)
It seems like I can't use the attrgetter() function in most set and list functions like I can with the sorted() function so I can't figure out how I'm supposed to do this. I suspect I could use a lambda function, but I'm not too familiar with functional programming so I don't seem to manage to figure it out.
The naive solution (first pick all items that are unique in both lists and then combine that list with what is left of the second list) seems quite long-winded so there must be a simpler way in Python.
A:
Sounds to me like you might be better off with a dict instead of a list, using the name as the key, and the rest of the object as value. Then you can simply dict1.update(dict2).
>>> dict1 = {"Harry": 18, "Mary": 27, "Tim": 7}
>>> dict2 = {"Harry": 22, "Mary": 27, "Frank": 40}
>>> dict1.update(dict2)
>>> dict1
{'Tim': 7, 'Harry': 22, 'Frank': 40, 'Mary': 27}
A:
Yes. The easy way is a dictionary.
list1 = {"Harry": 18, "Mary": 27, "Tim": 7}
list2 = {"Harry": 22, "Mary": 27, "Frank": 40}
list1.update(list2)
list is now {'Harry':22, 'Mary': 27, 'Tim': 7, 'Frank': 40}
If your data is more than just a number, that's OK. You can put any kind of object as the value for a dictionary.
list1['Harry'] = (1,"weee",54.55)
A:
You can implement de __eq__ attribute in your object. Based on that you can compare your objects with the == operator.
| Combining two lists of objects based on an attribute | Every example of list or set usage in Python seems to include trivial cases of integers but I have two lists of objects where the name attribute defines whether two objects instances are "the same" or not (other attributes might have different values).
I can create a list that contains all items from both lists, sorted, with
tmpList = sorted(list1 + list2, key=attrgetter('name'))
but how do I do the same so that list items that have the same value in the name attribute are selected from the second list?
E.g combining these two lists
list1 = [obj('Harry',18), obj('Mary',27), obj('Tim', 7)]
list2 = [obj('Harry', 22), obj('Mary', 27), obj('Frank', 40)]
would result in
list = [obj('Harry',22), obj('Mary', 27), obj('Tim', 7), obj('Frank', 40)]
(I used obj() as a short-hand notation for an object that has two attributes.)
It seems like I can't use the attrgetter() function in most set and list functions like I can with the sorted() function so I can't figure out how I'm supposed to do this. I suspect I could use a lambda function, but I'm not too familiar with functional programming so I don't seem to manage to figure it out.
The naive solution (first pick all items that are unique in both lists and then combine that list with what is left of the second list) seems quite long-winded so there must be a simpler way in Python.
| [
"Sounds to me like you might be better off with a dict instead of a list, using the name as the key, and the rest of the object as value. Then you can simply dict1.update(dict2).\n>>> dict1 = {\"Harry\": 18, \"Mary\": 27, \"Tim\": 7}\n>>> dict2 = {\"Harry\": 22, \"Mary\": 27, \"Frank\": 40}\n>>> dict1.update(dict2)... | [
5,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003861491_list_python.txt |
Q:
A data-structure for 1:1 mappings in python?
I have a problem which requires a reversable 1:1 mapping of keys to values.
That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique.
x = D[y]
y == D.inverse[x]
The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, there's a recipe here but for a large dictionary it can be very slow.
The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict.
So is there a better structure I can use?
My application requires that this should be very fast and use as little as possible memory.
The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)
We can guarantee that either the key or the value (or both) will be an integer
It's likely that the structure will be needed to store thousands or possibly millions of items.
Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]
A:
The other alternative is to make a new
class which unites two dictionaries,
one for each kind of lookup. That
would most likely be fast but would
use up twice as much memory as a
single dict.
Not really. Have you measured that? Since both dictionaries would use references to the same objects as keys and values, then the memory spent would be just the dictionary structure. That's a lot less than twice and is a fixed ammount regardless of your data size.
What I mean is that the actual data wouldn't be copied. So you'd spend little extra memory.
Example:
a = "some really really big text spending a lot of memory"
number_to_text = {1: a}
text_to_number = {a: 1}
Only a single copy of the "really big" string exists, so you end up spending just a little more memory. That's generally affordable.
I can't imagine a solution where you'd have the key lookup speed when looking by value, if you don't spend at least enough memory to store a reverse lookup hash table (which is exactly what's being done in your "unite two dicts" solution).
A:
class TwoWay:
def __init__(self):
self.d = {}
def add(self, k, v):
self.d[k] = v
self.d[v] = k
def remove(self, k):
self.d.pop(self.d.pop(k))
def get(self, k):
return self.d[k]
A:
The other alternative is to make a new class which unites two dictionaries, one for each > kind of lookup. That would most likely use up twice as much memory as a single dict.
Not really, since they would just be holding two references to the same data. In my mind, this is not a bad solution.
Have you considered an in-memory database lookup? I am not sure how it will compare in speed, but lookups in relational databases can be very fast.
A:
Here is my own solution to this problem: http://github.com/spenthil/pymathmap/blob/master/pymathmap.py
The goal is to make it as transparent to the user as possible. The only introduced significant attribute is partner.
OneToOneDict subclasses from dict - I know that isn't generally recommended, but I think I have the common use cases covered. The backend is pretty simple, it (dict1) keeps a weakref to a 'partner' OneToOneDict (dict2) which is its inverse. When dict1 is modified dict2 is updated accordingly as well and vice versa.
From the docstring:
>>> dict1 = OneToOneDict()
>>> dict2 = OneToOneDict()
>>> dict1.partner = dict2
>>> assert(dict1 is dict2.partner)
>>> assert(dict2 is dict1.partner)
>>> dict1['one'] = '1'
>>> dict2['2'] = '1'
>>> dict1['one'] = 'wow'
>>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
>>> dict1['one'] = '1'
>>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
>>> dict1.update({'three': '3', 'four': '4'})
>>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
>>> dict3 = OneToOneDict({'4':'four'})
>>> assert(dict3.partner is None)
>>> assert(dict3 == {'4':'four'})
>>> dict1.partner = dict3
>>> assert(dict1.partner is not dict2)
>>> assert(dict2.partner is None)
>>> assert(dict1.partner is dict3)
>>> assert(dict3.partner is dict1)
>>> dict1.setdefault('five', '5')
>>> dict1['five']
'5'
>>> dict1.setdefault('five', '0')
>>> dict1['five']
'5'
When I get some free time, I intend to make a version that doesn't store things twice. No clue when that'll be though :)
A:
Assuming that you have a key with which you look up a more complex mutable object, just make the key a property of that object. It does seem you might be better off thinking about the data model a bit.
A:
"We can guarantee that either the key or the value (or both) will be an integer"
That's weirdly written -- "key or the value (or both)" doesn't feel right. Either they're all integers, or they're not all integers.
It sounds like they're all integers.
Or, it sounds like you're thinking of replacing the target object with an integer value so you only have one copy referenced by an integer. This is a false economy. Just keep the target object. All Python objects are -- in effect -- references. Very little actual copying gets done.
Let's pretend that you simply have two integers and can do a lookup on either one of the pair. One way to do this is to use heap queues or the bisect module to maintain ordered lists of integer key-value tuples.
See http://docs.python.org/library/heapq.html#module-heapq
See http://docs.python.org/library/bisect.html#module-bisect
You have one heapq (key,value) tuples. Or, if your underlying object is more complex, the (key,object) tuples.
You have another heapq (value,key) tuples. Or, if your underlying object is more complex, (otherkey,object) tuples.
An "insert" becomes two inserts, one to each heapq-structured list.
A key lookup is in one queue; a value lookup is in the other queue. Do the lookups using bisect(list,item).
A:
It so happens that I find myself asking this question all the time (yesterday in particular). I agree with the approach of making two dictionaries. Do some benchmarking to see how much memory it's taking. I've never needed to make it mutable, but here's how I abstract it, if it's of any use:
class BiDict(list):
def __init__(self,*pairs):
super(list,self).__init__(pairs)
self._first_access = {}
self._second_access = {}
for pair in pairs:
self._first_access[pair[0]] = pair[1]
self._second_access[pair[1]] = pair[0]
self.append(pair)
def _get_by_first(self,key):
return self._first_access[key]
def _get_by_second(self,key):
return self._second_access[key]
# You'll have to do some overrides to make it mutable
# Methods such as append, __add__, __del__, __iadd__
# to name a few will have to maintain ._*_access
class Constants(BiDict):
# An implementation expecting an integer and a string
get_by_name = BiDict._get_by_second
get_by_number = BiDict._get_by_first
t = Constants(
( 1, 'foo'),
( 5, 'bar'),
( 8, 'baz'),
)
>>> print t.get_by_number(5)
bar
>>> print t.get_by_name('baz')
8
>>> print t
[(1, 'foo'), (5, 'bar'), (8, 'baz')]
A:
How about using sqlite? Just create a :memory: database with a two-column table. You can even add indexes, then query by either one. Wrap it in a class if it's something you're going to use a lot.
| A data-structure for 1:1 mappings in python? | I have a problem which requires a reversable 1:1 mapping of keys to values.
That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique.
x = D[y]
y == D.inverse[x]
The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, there's a recipe here but for a large dictionary it can be very slow.
The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict.
So is there a better structure I can use?
My application requires that this should be very fast and use as little as possible memory.
The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)
We can guarantee that either the key or the value (or both) will be an integer
It's likely that the structure will be needed to store thousands or possibly millions of items.
Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]
| [
"\nThe other alternative is to make a new\n class which unites two dictionaries,\n one for each kind of lookup. That\n would most likely be fast but would\n use up twice as much memory as a\n single dict.\n\nNot really. Have you measured that? Since both dictionaries would use references to the same objects as... | [
28,
11,
5,
2,
1,
1,
0,
0
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0000863935_data_structures_python.txt |
Q:
AppEngine: Query datastore for records with no condition for a specific property
i want to do a query that a user may or may not select a filter, but i don't want to create 2 indexes (tables).
value=self.request.get('filter')
if value:
results=Entity.all().filter('p1 =','v1').filter('p2 =','v2').filter('filter_property =',value)
else:
results=Entity.all().filter('p1 =','v1').filter('p2 =','v2')
i could order the filter_property. like this in the last line:
results=Entity.all().filter('p1 =','v1').filter('p2 =','v2').order('filter_property')
this would be bad if i could or could not filter p1 (property1) and p2 (property2). i would like to do something like:
value = self.request.get('filter')
if value:
operator = '='
else:
operator = '!='
results=Entity.all().filter('p1 =','v1').filter('p2 =','v2').filter('filter_property '+operator,value).order('p4')
".order('p4')" will fail BadArgumentError with the operand !=.
what should i do?
A:
It sounds like you've got a good handle on the alternatives. You can add order clauses to replace filters if you want the datastore to use the same index for each; otherwise, you're stuck with having multiple indexes.
| AppEngine: Query datastore for records with no condition for a specific property | i want to do a query that a user may or may not select a filter, but i don't want to create 2 indexes (tables).
value=self.request.get('filter')
if value:
results=Entity.all().filter('p1 =','v1').filter('p2 =','v2').filter('filter_property =',value)
else:
results=Entity.all().filter('p1 =','v1').filter('p2 =','v2')
i could order the filter_property. like this in the last line:
results=Entity.all().filter('p1 =','v1').filter('p2 =','v2').order('filter_property')
this would be bad if i could or could not filter p1 (property1) and p2 (property2). i would like to do something like:
value = self.request.get('filter')
if value:
operator = '='
else:
operator = '!='
results=Entity.all().filter('p1 =','v1').filter('p2 =','v2').filter('filter_property '+operator,value).order('p4')
".order('p4')" will fail BadArgumentError with the operand !=.
what should i do?
| [
"It sounds like you've got a good handle on the alternatives. You can add order clauses to replace filters if you want the datastore to use the same index for each; otherwise, you're stuck with having multiple indexes.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003860097_google_app_engine_google_cloud_datastore_python.txt |
Q:
how to know on which platform is remote machine running using python code
I just wanted to know that how can we fetch the platform on which a remote machine is running using Python?
A:
Frankly, i'd use python to launch an nmap executable and parse the result. nmap can detect accurately what platform it's talking with based on little variations and details in the packets exchanged.
A:
I don't quite know how to interpret your question, but samy has answered the case of "how to use Python to figure out what another machine is running".
Since you seem to indicate that you have SCP access to the machine in question, I'll assume instead that you want to use a Python script to figure out what that machine is running. If that is the case, you should take a look at the platform module. In particular, platform.platform might be of interest.
| how to know on which platform is remote machine running using python code | I just wanted to know that how can we fetch the platform on which a remote machine is running using Python?
| [
"Frankly, i'd use python to launch an nmap executable and parse the result. nmap can detect accurately what platform it's talking with based on little variations and details in the packets exchanged.\n",
"I don't quite know how to interpret your question, but samy has answered the case of \"how to use Python to f... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003861654_python.txt |
Q:
Split string by number of words with python
How do I split up a string into several parts of a number of words in python. For example, turn a 10,000 word string into ten 1,000 word strings. Thanks.
A:
def splitter(n, s):
pieces = s.split()
return (" ".join(pieces[i:i+n]) for i in range(0, len(pieces), n)
for piece in splitter(1000, really_long_string):
print(piece)
Where n is number of words; s is the long string.
This will yield ten 1000 word strings from a 10000 word string like you ask.
Note that you can also use iterools grouper recipe but that would involve making 1000 copies of the iterator for your string: expensive I think.
Also note that this will replace all whitespace with spaces. If this isn't acceptable, you'll need something else.
A:
Under normal circumstances :
>>> a = "dedff fefef fefwff efef"
>>> a.split()
['dedff', 'fefef', 'fefwff', 'efef']
>>> k = a.split()
>>> [" ".join(k[0:2]), " ".join(k[2:4])]
['dedff fefef', 'fefwff efef']
>>>
A:
Try this:
s = 'a b c d e f g h i j k l'
n = 3
def group_words(s, n):
words = s.split()
for i in xrange(0, len(words), n):
yield ' '.join(words[i:i+n])
list(group_words(s,n))
['a b c', 'd e f', 'g h i', 'j k l']
A:
Pehaps something like this,
>>> s = "aa bb cc dd ee ff gg hh ii jj kk ll mm nn oo pp qq rr ss tt uu vv"
>>> chunks = s.split()
>>> per_line = 5
>>> for i in range(0, len(chunks), per_line):
... print " ".join(chunks[i:i + per_line])
...
aa bb cc dd ee
ff gg hh ii jj
kk ll mm nn oo
pp qq rr ss tt
uu vv
A:
this might help:
s="blah blah .................."
l =[]
for i in xrange(0,len(s),1000):
l.append(s[i:i+1000])
A:
If you're comfortable using regular expressions, you could also try this:
import re
def split_by_number_of_words(input, number_of_words):
regexp = re.compile(r'((?:\w+\W+){0,%d}\w+)' % (number_of_words - 1))
return regexp.findall(input)
s = ' '.join(str(n) for n in range(1, 101)) # "1 2 3 ... 100"
for words in split_by_number_of_words(s, 10):
print words
| Split string by number of words with python | How do I split up a string into several parts of a number of words in python. For example, turn a 10,000 word string into ten 1,000 word strings. Thanks.
| [
"def splitter(n, s):\n pieces = s.split()\n return (\" \".join(pieces[i:i+n]) for i in range(0, len(pieces), n)\n\nfor piece in splitter(1000, really_long_string):\n print(piece)\n\nWhere n is number of words; s is the long string.\nThis will yield ten 1000 word strings from a 10000 word string like you as... | [
5,
3,
2,
0,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003861674_python_string.txt |
Q:
How to prevent boost::python::extract from accepting int
I'm using boost::python::extract<> to convert the items in a boost::python::list to floats. My problem is with int's in python - extract<float> seems to regard int->float as a valid conversion, however I only want true float objects. Is there a way to force extract<> to be more conservative?
extract<float> value(o);
if (value.check()) {
// This is true both for floats and ints
a = value();
}
A:
I'm pretty sure that you can't tell extract<float> not to convert intergers to floats.
What you could do is to query the wrapped PyObject:
const PyObject* pyo = o.ptr();
if (PyFloat_Check(pyo))
{
// True only for floats.
a = extract<float>(o);
}
| How to prevent boost::python::extract from accepting int | I'm using boost::python::extract<> to convert the items in a boost::python::list to floats. My problem is with int's in python - extract<float> seems to regard int->float as a valid conversion, however I only want true float objects. Is there a way to force extract<> to be more conservative?
extract<float> value(o);
if (value.check()) {
// This is true both for floats and ints
a = value();
}
| [
"I'm pretty sure that you can't tell extract<float> not to convert intergers to floats. \nWhat you could do is to query the wrapped PyObject:\nconst PyObject* pyo = o.ptr();\nif (PyFloat_Check(pyo))\n{\n // True only for floats.\n a = extract<float>(o);\n}\n\n"
] | [
1
] | [] | [] | [
"boost_python",
"python"
] | stackoverflow_0003861496_boost_python_python.txt |
Q:
Pickling objects
I need to pickle object [wxpython frame object] and send it as a prameter to this function apply_async on multiproccessing pool module
could someone provide me an example how can I do it
I tried the following and get an error message :
myfile = file(r"C:\binary.dat", "w")
pickle.dump(self, myfile)
myfile.close()
self.my_pool.apply_async(fun,[i,myfile])
def fun(i,self_object):
window = pickle.load(self_oject)
wx.CallAfter(window.LogData, msg)
could someone tell me what could be the problem
If the error give some indicator below the last error message i get:
File "C:\Python26\lib\copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.name
TypeError: can't pickle PySwigObject objects
A:
I don't believe that wxPython objects can be pickled. They are just wrappers around C objects, which contain lots of pointers and other stateful stuff. The pickle module doesn't know enough about them to be able to restore their state afterwards.
A:
You can not serialize a widget for use in another process. I guess you want to change the GUI content from another process that is started by the multiprocessing module. In that case, you should define a callback function in the parent process that gets called when the result of the sub-process is ready. Therefore you can use the "callback" parameter of apply_async.
Something like:
def fun(i):
# do something in this sub-process and then return a log message
return "finished doing something"
def cb(resultFromFun):
wx.CallAfter(window.LogData, resultFromFun)
my_pool.apply_async(fun, [i], callback = cb)
| Pickling objects | I need to pickle object [wxpython frame object] and send it as a prameter to this function apply_async on multiproccessing pool module
could someone provide me an example how can I do it
I tried the following and get an error message :
myfile = file(r"C:\binary.dat", "w")
pickle.dump(self, myfile)
myfile.close()
self.my_pool.apply_async(fun,[i,myfile])
def fun(i,self_object):
window = pickle.load(self_oject)
wx.CallAfter(window.LogData, msg)
could someone tell me what could be the problem
If the error give some indicator below the last error message i get:
File "C:\Python26\lib\copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.name
TypeError: can't pickle PySwigObject objects
| [
"I don't believe that wxPython objects can be pickled. They are just wrappers around C objects, which contain lots of pointers and other stateful stuff. The pickle module doesn't know enough about them to be able to restore their state afterwards.\n",
"You can not serialize a widget for use in another process. I ... | [
1,
1
] | [] | [] | [
"pickle",
"python",
"wxpython"
] | stackoverflow_0003862331_pickle_python_wxpython.txt |
Q:
Setting model level permissions in code for Django admin panel
Is there a way to implement the permissions for models through the code? I have a large set of models and I want some of the models to be just viewable by the admin and not the ability to add them.
Please suggest.
A:
You can set permissions through the admin site itself. For instructions, see the "Users, Groups and Permissions" section in the django book chapter:
The Django Administration Site
A:
Found the solution here: http://code.djangoproject.com/wiki/RowLevelPermissions
works the way I needed.
| Setting model level permissions in code for Django admin panel | Is there a way to implement the permissions for models through the code? I have a large set of models and I want some of the models to be just viewable by the admin and not the ability to add them.
Please suggest.
| [
"You can set permissions through the admin site itself. For instructions, see the \"Users, Groups and Permissions\" section in the django book chapter:\n\nThe Django Administration Site \n\n",
"Found the solution here: http://code.djangoproject.com/wiki/RowLevelPermissions \nworks the way I needed.\n"
] | [
0,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003828084_django_django_admin_python.txt |
Q:
send commands to a backgrounded jobs stdin
I have a java server application that, when its running, you can interact with it sending commands via stdin. I want to write a web interface that can send these commands to it.
In order to do that I need some way of getting commands from php to the stdin for this backgrounded job. Is there a way to do this from console? or possibly write some kind of wrapper that controls the server job and can access its stdin ? could this be done in python?
A:
You could connect its stdin to a FIFO and then have another daemon also connect to the FIFO and send commands. It might be better to have the control daemon start the Java daemon though, so that the Java daemon doesn't shut down if the control daemon does for some reason.
A:
You can use python subprocess module:
Example of calling external shell command:
from subprocess import call
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
A:
you could use the command line, something like this
wrapper.php (using backticks)
$cmd = `php /path/to/background_script.php &`;
echo $cmd;
background_script.php
echo "Hello world in 5 seconds\n";
sleep(5);
echo "Hello again\n";
| send commands to a backgrounded jobs stdin | I have a java server application that, when its running, you can interact with it sending commands via stdin. I want to write a web interface that can send these commands to it.
In order to do that I need some way of getting commands from php to the stdin for this backgrounded job. Is there a way to do this from console? or possibly write some kind of wrapper that controls the server job and can access its stdin ? could this be done in python?
| [
"You could connect its stdin to a FIFO and then have another daemon also connect to the FIFO and send commands. It might be better to have the control daemon start the Java daemon though, so that the Java daemon doesn't shut down if the control daemon does for some reason.\n",
"You can use python subprocess modul... | [
0,
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0003862332_php_python.txt |
Q:
Can I safely use hashes of tuples containing 64 bit integers (longs) as unique keys in a python dictionary?
I have to store objects that have two attributes (ida and idb) inside a dict. Both attributes are 64 bit positive integers and I can only store one object for a unique arrangement(combination in which the order matters) of ida and idb. For example:
obj1 = SomeClass(ida=5223372036854775807, idb=2)
obj2 = SomeClass(ida=2, idb=5223372036854775807)
obj3 = SomeClass(ida=5223372036854775807, idb=2)
Since the objects themselves are mutable, I'm using hashes of tuples '(ida, idb,)' as keys. Following the example, consider this:
d = {}
# storing obj1
k1 = hash((obj1.ida, obj1.idb,))
d[k1] = obj1
# storing obj2
k2 = hash((obj2.ida, obj2.idb,))
d[k2] = obj2
# storing obj3
k3 = hash((obj3.ida, obj3.idb,)) # note that k3 hash should be the same as k1
d[k3] = obj3
#at this point 'd' should contain only 'obj2' and 'obj3' since 'k1' == 'k3'
I tested the above example in my 64 bit machine and it worked as expected.
I have the following questions:
Is it possible for two tuples of big integers to compute the same hash if they have differences either in elements or in ordering?
What about in 32 bit platforms?
If not, is there a platform independent way to guarantee that the above example will work no matter the values of ida and idb?
A:
In [33]: hash?
Return a hash value for the object. Two objects with the same
value have the same hash value. The reverse is not necessarily true, but
likely.
Why not just use the tuple (ida,idb) as the key?
import pprint
class SomeClass(object):
def __init__(self,ida,idb):
self.ida=ida
self.idb=idb
obj1 = SomeClass(ida=5223372036854775807, idb=2)
obj2 = SomeClass(ida=2, idb=5223372036854775807)
obj3 = SomeClass(ida=5223372036854775807, idb=2)
d={}
for obj in (obj1,obj2,obj3):
d[obj.ida,obj.idb]=obj
pprint.pprint(d)
# {(2, 5223372036854775807L): <__main__.SomeClass object at 0xb78839ec>,
(5223372036854775807L, 2): <__main__.SomeClass object at 0xb7883a0c>}
A:
Like Ignacio said, you can have hash collisions. Why don't you just use the tuple itself? Tuples are immutable and it looks like your ida and idb are (immutable) integers.
A:
There are only 2**<word size> possible hashes, so you would have to run a 128-bit version of Python to even store all (2**64)**2 possible hashes in the first place. And yes, it could still be possible to have collisions. Use a set if you need to store unique objects; just define __hash__() and __eq__() in a sane manner.
| Can I safely use hashes of tuples containing 64 bit integers (longs) as unique keys in a python dictionary? | I have to store objects that have two attributes (ida and idb) inside a dict. Both attributes are 64 bit positive integers and I can only store one object for a unique arrangement(combination in which the order matters) of ida and idb. For example:
obj1 = SomeClass(ida=5223372036854775807, idb=2)
obj2 = SomeClass(ida=2, idb=5223372036854775807)
obj3 = SomeClass(ida=5223372036854775807, idb=2)
Since the objects themselves are mutable, I'm using hashes of tuples '(ida, idb,)' as keys. Following the example, consider this:
d = {}
# storing obj1
k1 = hash((obj1.ida, obj1.idb,))
d[k1] = obj1
# storing obj2
k2 = hash((obj2.ida, obj2.idb,))
d[k2] = obj2
# storing obj3
k3 = hash((obj3.ida, obj3.idb,)) # note that k3 hash should be the same as k1
d[k3] = obj3
#at this point 'd' should contain only 'obj2' and 'obj3' since 'k1' == 'k3'
I tested the above example in my 64 bit machine and it worked as expected.
I have the following questions:
Is it possible for two tuples of big integers to compute the same hash if they have differences either in elements or in ordering?
What about in 32 bit platforms?
If not, is there a platform independent way to guarantee that the above example will work no matter the values of ida and idb?
| [
"In [33]: hash?\n\n\nReturn a hash value for the object. Two objects with the same\n value have the same hash value. The reverse is not necessarily true, but\n likely.\n\nWhy not just use the tuple (ida,idb) as the key?\nimport pprint\nclass SomeClass(object):\n def __init__(self,ida,idb):\n self.ida=... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"hash",
"hashtable",
"python",
"tuples"
] | stackoverflow_0003863753_dictionary_hash_hashtable_python_tuples.txt |
Q:
python nose and twisted
I am writing a test for a function that downloads the data from an url with Twisted (I know about twisted.web.client.getPage, but this one adds some extra functionality). Either ways, I want to use nosetests since I am using it throughout the project and it doesn't look appropriate to use Twisted Trial only for this particular test.
So what I am trying to do is something like:
from nose.twistedtools import deferred
@deferred()
def test_download(self):
url = 'http://localhost:8000'
d = getPage(url)
def callback(data):
assert len(data) != 0
d.addCallback(callback)
return d
On localhost:8000 listens a test server. The issue is I always get twisted.internet.error.DNSLookupError
DNSLookupError: DNS lookup failed: address 'localhost:8000' not found: [Errno -5] No address associated with hostname.
Is there a way I can fix this? Does anyone actually uses nose.twistedtools?
Update: A more complete traceback
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/nose-0.11.2-py2.6.egg/nose/twistedtools.py", line 138, in errback
failure.raiseException()
File "/usr/local/lib/python2.6/dist-packages/Twisted-9.0.0-py2.6-linux-x86_64.egg/twisted/python/failure.py", line 326, in raiseException
raise self.type, self.value, self.tb
DNSLookupError: DNS lookup failed: address 'localhost:8000' not found: [Errno -5] No address associated with hostname.
Update 2
My bad, it seems in the implementation of getPage, I was doing something like:
obj = urlparse.urlparse(url)
netloc = obj.netloc
and passing netloc to the the factory when I should've passed netloc.split(':')[0]
A:
Are you sure your getPage function is parsing the URL correctly? The error message seems to suggest that it is using the hostname and port together when doing the dns lookup.
You say your getPage is similar to twisted.web.client.getPage, but that works fine for me when I use it in this complete script:
#!/usr/bin/env python
from nose.twistedtools import deferred
from twisted.web import client
import nose
@deferred()
def test_download():
url = 'http://localhost:8000'
d = client.getPage(url)
def callback(data):
assert len(data) != 0
d.addCallback(callback)
return d
if __name__ == "__main__":
args = ['--verbosity=2', __file__]
nose.run(argv=args)
While running a simple http server in my home directory:
$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
The nose test gives the following output:
.
----------------------------------------------------------------------
Ran 1 test in 0.019s
OK
| python nose and twisted | I am writing a test for a function that downloads the data from an url with Twisted (I know about twisted.web.client.getPage, but this one adds some extra functionality). Either ways, I want to use nosetests since I am using it throughout the project and it doesn't look appropriate to use Twisted Trial only for this particular test.
So what I am trying to do is something like:
from nose.twistedtools import deferred
@deferred()
def test_download(self):
url = 'http://localhost:8000'
d = getPage(url)
def callback(data):
assert len(data) != 0
d.addCallback(callback)
return d
On localhost:8000 listens a test server. The issue is I always get twisted.internet.error.DNSLookupError
DNSLookupError: DNS lookup failed: address 'localhost:8000' not found: [Errno -5] No address associated with hostname.
Is there a way I can fix this? Does anyone actually uses nose.twistedtools?
Update: A more complete traceback
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/nose-0.11.2-py2.6.egg/nose/twistedtools.py", line 138, in errback
failure.raiseException()
File "/usr/local/lib/python2.6/dist-packages/Twisted-9.0.0-py2.6-linux-x86_64.egg/twisted/python/failure.py", line 326, in raiseException
raise self.type, self.value, self.tb
DNSLookupError: DNS lookup failed: address 'localhost:8000' not found: [Errno -5] No address associated with hostname.
Update 2
My bad, it seems in the implementation of getPage, I was doing something like:
obj = urlparse.urlparse(url)
netloc = obj.netloc
and passing netloc to the the factory when I should've passed netloc.split(':')[0]
| [
"Are you sure your getPage function is parsing the URL correctly? The error message seems to suggest that it is using the hostname and port together when doing the dns lookup.\nYou say your getPage is similar to twisted.web.client.getPage, but that works fine for me when I use it in this complete script:\n#!/usr/bi... | [
2
] | [] | [] | [
"nose",
"python",
"twisted"
] | stackoverflow_0003863374_nose_python_twisted.txt |
Q:
How to write tag deleter script in python
I want to implement a file reader (folders and subfolders) script which detects some tags and delete those tags from the files.
The files are .cpp, .h .txt and .xml And they are hundreds of files under same folder.
I have no idea about python, but people told me that I can do it easily.
EXAMPLE:
My main folder is A: C:\A
Inside A, I have folders (B,C,D) and some files A.cpp A.h A.txt and A.xml. In B i have folders B1, B2,B3 and some of them have more subfolders, and files .cpp, .xml and .h....
xml files, contains some tags like <!-- $Mytag: some text$ -->
.h and .cpp files contains another kind of tags like //$TAG some text$
.txt has different format tags: #$This is my tag$
It always starts and ends with $ symbol but it always have a comment character (//,
The idea is to run one script and delete all tags from all files so the script must:
Read folders and subfolders
Open files and find tags
If they are there, delete and save files with changes
WHAT I HAVE:
import os
for root, dirs, files in os.walk(os.curdir):
if files.endswith('.cpp'):
%Find //$ and delete until next $
if files.endswith('.h'):
%Find //$ and delete until next $
if files.endswith('.txt'):
%Find #$ and delete until next $
if files.endswith('.xml'):
%Find <!-- $ and delete until next $ and -->
A:
The general solution would be to:
use the os.walk() function to traverse the directory tree.
Iterate over the filenames and use fn_name.endswith('.cpp') with if/elseif to determine which file you're working with
Use the re module to create a regular expression you can use to determine if a line contains your tag
Open the target file and a temporary file (use the tempfile module). Iterate over the source file line by line and output the filtered lines to your tempfile.
If any lines were replaced, use os.unlink() plus os.rename() to replace your original file
It's a trivial excercise for a Python adept but for someone new to the language, it'll probably take a few hours to get working. You probably couldn't ask for a better task to get introduced to the language though. Good Luck!
----- Update -----
The files attribute returned by os.walk is a list so you'll need to iterate over it as well. Also, the files attribute will only contain the base name of the file. You'll need to use the root value in conjunction with os.path.join() to convert this to a full path name. Try doing just this:
for root, d, files in os.walk('.'):
for base_filename in files:
full_name = os.path.join(root, base_filename)
if full_name.endswith('.h'):
print full_name, 'is a header!'
elif full_name.endswith('.cpp'):
print full_name, 'is a C++ source file!'
If you're using Python 3, the print statements will need to be function calls but the general idea remains the same.
A:
Try something like this:
import os
import re
CPP_TAG_RE = re.compile(r'(?<=// *)\$[^$]+\$')
tag_REs = {
'.h': CPP_TAG_RE,
'.cpp': CPP_TAG_RE,
'.xml': re.compile(r'(?<=<!-- *)\$[^$]+\$(?= *-->)'),
'.txt': re.compile(r'(?<=# *)\$[^$]+\$'),
}
def process_file(filename, regex):
# Set up.
tempfilename = filename + '.tmp'
infile = open(filename, 'r')
outfile = open(tempfilename, 'w')
# Filter the file.
for line in infile:
outfile.write(regex.sub("", line))
# Clean up.
infile.close()
outfile.close()
# Enable only one of the two following lines.
os.rename(filename, filename + '.orig')
#os.remove(filename)
os.rename(tempfilename, filename)
def process_tree(starting_point=os.curdir):
for root, d, files in os.walk(starting_point):
for filename in files:
# Get rid of `.lower()` in the following if case matters.
ext = os.path.splitext(filename)[1].lower()
if ext in tag_REs:
process_file(os.path.join(root, base_filename), tag_REs[ext])
Nice thing about os.splitext is that it does the right thing for filenames that start with a ..
| How to write tag deleter script in python | I want to implement a file reader (folders and subfolders) script which detects some tags and delete those tags from the files.
The files are .cpp, .h .txt and .xml And they are hundreds of files under same folder.
I have no idea about python, but people told me that I can do it easily.
EXAMPLE:
My main folder is A: C:\A
Inside A, I have folders (B,C,D) and some files A.cpp A.h A.txt and A.xml. In B i have folders B1, B2,B3 and some of them have more subfolders, and files .cpp, .xml and .h....
xml files, contains some tags like <!-- $Mytag: some text$ -->
.h and .cpp files contains another kind of tags like //$TAG some text$
.txt has different format tags: #$This is my tag$
It always starts and ends with $ symbol but it always have a comment character (//,
The idea is to run one script and delete all tags from all files so the script must:
Read folders and subfolders
Open files and find tags
If they are there, delete and save files with changes
WHAT I HAVE:
import os
for root, dirs, files in os.walk(os.curdir):
if files.endswith('.cpp'):
%Find //$ and delete until next $
if files.endswith('.h'):
%Find //$ and delete until next $
if files.endswith('.txt'):
%Find #$ and delete until next $
if files.endswith('.xml'):
%Find <!-- $ and delete until next $ and -->
| [
"The general solution would be to:\n\nuse the os.walk() function to traverse the directory tree. \nIterate over the filenames and use fn_name.endswith('.cpp') with if/elseif to determine which file you're working with\nUse the re module to create a regular expression you can use to determine if a line contains your... | [
3,
1
] | [] | [] | [
"directory",
"parsing",
"python",
"tags"
] | stackoverflow_0003856160_directory_parsing_python_tags.txt |
Q:
Cancel a group of HTTP requests in twisted
I'm making several HTTP requests with twisted.web.client.getPage, and would like to be able to cancel some of them at the user's request. Ideally I would like to do something like:
# Pseudocode, getPage doesn't work like this:
getPage(url1, "group1")
getPage(url2, "group1")
getPage(url3, "group1")
...
# Later on
reactor.cancel_all("group1")
Maybe I could add all the Deferreds to a DeferredList, but I have a lot of small requests, so most of the requests would be finished at a given time anyway (plus, I don't know if you can add Deferreds to a existing DeferredList)... Is there a more idiomatic solution?
A:
You are describing two separate issues. First, can an HTTP request made with getPage be cancelled at all? No, it can't. Second, can operations be grouped together so that they can all be cancelled simultaneously. Sure, that doesn't involve anything very special:
def cancel(group):
for job in group:
job.cancel()
group = []
group.append(job1)
group.append(job2)
...
cancel(group)
Nothing particular about Twisted here - this is just creating a collection and then operating on it. You don't need the reactor to help or anything. What you do need is a way to cancel an individual operation. The latest release of Twisted adds Deferred.cancel (so, contrary to the older post linked to in pyfunc's answer, Deferreds do have a notion of being cancelled now). However, for this to actually do anything, each API which creates Deferreds - for example, getPage - has to be updated to perform the relevant cancellation operation. As of Twisted 10.1, getPage has not been updated.
So you can either implement cancellation for getPage (and contribute it to Twisted, please!) or you can forget about actually cancelling the HTTP request and instead just ignore the result when it arrives.
A:
I am not providing the solution but pointing out to a following relevant discussion on twisted mailing list.
http://www.mail-archive.com/twisted-python@twistedmatrix.com/msg01193.html
| Cancel a group of HTTP requests in twisted | I'm making several HTTP requests with twisted.web.client.getPage, and would like to be able to cancel some of them at the user's request. Ideally I would like to do something like:
# Pseudocode, getPage doesn't work like this:
getPage(url1, "group1")
getPage(url2, "group1")
getPage(url3, "group1")
...
# Later on
reactor.cancel_all("group1")
Maybe I could add all the Deferreds to a DeferredList, but I have a lot of small requests, so most of the requests would be finished at a given time anyway (plus, I don't know if you can add Deferreds to a existing DeferredList)... Is there a more idiomatic solution?
| [
"You are describing two separate issues. First, can an HTTP request made with getPage be cancelled at all? No, it can't. Second, can operations be grouped together so that they can all be cancelled simultaneously. Sure, that doesn't involve anything very special:\ndef cancel(group):\n for job in group:\n ... | [
1,
0
] | [] | [] | [
"http",
"python",
"twisted"
] | stackoverflow_0003862129_http_python_twisted.txt |
Q:
WSGI request and response wrappers
I'm looking for WSGI request and response wrappers for having a more convenient interface than the plain WSGI environ and start_response callback. I want something like WebOb or Werkzeug. But I don't like WebOb's PHP-like usage of GET and POST for parameter dictionaries, because HTTP is not limited to GET and POST and the distinction is not necessary when accessing params.
What request/response wrapper do you prefer and why?
A:
WebOb allows you to access POST & GET parameters jointly by accessing Request.str_params attribute. Additionally, Request.method gives you acces to the HTTP request type which is not limited to POST or GET.
| WSGI request and response wrappers | I'm looking for WSGI request and response wrappers for having a more convenient interface than the plain WSGI environ and start_response callback. I want something like WebOb or Werkzeug. But I don't like WebOb's PHP-like usage of GET and POST for parameter dictionaries, because HTTP is not limited to GET and POST and the distinction is not necessary when accessing params.
What request/response wrapper do you prefer and why?
| [
"WebOb allows you to access POST & GET parameters jointly by accessing Request.str_params attribute. Additionally, Request.method gives you acces to the HTTP request type which is not limited to POST or GET.\n"
] | [
1
] | [] | [] | [
"http",
"httprequest",
"httpresponse",
"python",
"wsgi"
] | stackoverflow_0003862966_http_httprequest_httpresponse_python_wsgi.txt |
Q:
Installing psycopg2 in virtualenv (Ubuntu 10.04, Python 2.5)
I had problems installing psycopg2 in a virtualenv.
I tried different things explained there: http://www.saltycrane.com/blog/2009/07/using-psycopg2-virtualenv-ubuntu-jaunty/
The last thing I tried is this...
I created a virtualenv with -p python2.5 --no-site-packages
I installed libpq-dev: apt-get install libpq-dev
In the virtualenv, I did this: easy_install -i http://downloads.egenix.com/python/index/ucs4/ egenix-mx-base
Then when I tried pip install psycopg2==2.0.7, I got this error:
Installing collected packages: psycopg2
Running setup.py install for psycopg2
building 'psycopg2._psycopg' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.2.2 (dt dec ext pq3)" -DPG_VERSION_HEX=0x080404 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -DHAVE_PQPROTOCOL3=1 -I/usr/include/python2.5 -I. -I/usr/include/postgresql -I/usr/include/postgresql/8.4/server -c psycopg/psycopgmodule.c -o build/temp.linux-i686-2.5/psycopg/psycopgmodule.o -Wdeclaration-after-statement
psycopg/psycopgmodule.c:27:20: error: Python.h: No such file or directory
In file included from psycopg/psycopgmodule.c:31:
./psycopg/python.h:31:26: error: structmember.h: No such file or directory
./psycopg/python.h:34:4: error: #error "psycopg requires Python >= 2.4"
In file included from psycopg/psycopgmodule.c:32:
Does anyone have any idea how to solve that?
Thanks.
A:
From python-list:
Diez:
Install the python-dev-package. It
contains the Python.h file, which the
above error message pretty clearly
says. Usually, it's a good idea to
search package descriptions of
debian/ubuntu packages for missing
header files to know what to install.
Pascal:
It's already installed; at least for
Python 2.6, nor sure it's correct for
Python 2.5. python2.5-dev is not available but
python-old-doctools seems to replace it.
Diez:
It is 100% not correct for
python2.5. As the error message shows
- it's missing.
If it's not available somewhere, you
should consider building python
yourself, if you have to use 2.5.
Alex:
Ubuntu 10.04 doesn't have a full
Python 2.5 packaged, as evidenced by
the lack of python2.5-dev. You need to
use Python 2.6 or if you absolutely
must use Python 2.5 build it from
source, try a Debian package or switch
distro. python-old-doctools does not
replace python- dev, it looks like it
was bodged to keep some latex tools
working.
Pascal: I finally created a virtualenv
with Python 2.6 and everything went fine
(with the latest version of psycopg2).
| Installing psycopg2 in virtualenv (Ubuntu 10.04, Python 2.5) | I had problems installing psycopg2 in a virtualenv.
I tried different things explained there: http://www.saltycrane.com/blog/2009/07/using-psycopg2-virtualenv-ubuntu-jaunty/
The last thing I tried is this...
I created a virtualenv with -p python2.5 --no-site-packages
I installed libpq-dev: apt-get install libpq-dev
In the virtualenv, I did this: easy_install -i http://downloads.egenix.com/python/index/ucs4/ egenix-mx-base
Then when I tried pip install psycopg2==2.0.7, I got this error:
Installing collected packages: psycopg2
Running setup.py install for psycopg2
building 'psycopg2._psycopg' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.2.2 (dt dec ext pq3)" -DPG_VERSION_HEX=0x080404 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -DHAVE_PQPROTOCOL3=1 -I/usr/include/python2.5 -I. -I/usr/include/postgresql -I/usr/include/postgresql/8.4/server -c psycopg/psycopgmodule.c -o build/temp.linux-i686-2.5/psycopg/psycopgmodule.o -Wdeclaration-after-statement
psycopg/psycopgmodule.c:27:20: error: Python.h: No such file or directory
In file included from psycopg/psycopgmodule.c:31:
./psycopg/python.h:31:26: error: structmember.h: No such file or directory
./psycopg/python.h:34:4: error: #error "psycopg requires Python >= 2.4"
In file included from psycopg/psycopgmodule.c:32:
Does anyone have any idea how to solve that?
Thanks.
| [
"From python-list: \n\nDiez:\n Install the python-dev-package. It\n contains the Python.h file, which the\n above error message pretty clearly\n says. Usually, it's a good idea to\n search package descriptions of\n debian/ubuntu packages for missing\n header files to know what to install.\n\nPascal:\n It... | [
6
] | [] | [] | [
"psycopg2",
"python",
"virtualenv"
] | stackoverflow_0003847536_psycopg2_python_virtualenv.txt |
Q:
How to get IP when using SimpleXMLRPCDispatcher in Django
Having a code inspired from http://code.djangoproject.com/wiki/XML-RPC :
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse
dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Python 2.5
def rpc_handler(request):
"""
the actual handler:
if you setup your urls.py properly, all calls to the xml-rpc service
should be routed through here.
If post data is defined, it assumes it's XML-RPC and tries to process as such
Empty post assumes you're viewing from a browser and tells you about the service.
"""
if len(request.POST):
response = HttpResponse(mimetype="application/xml")
response.write(dispatcher._marshaled_dispatch(request.raw_post_data))
else:
pass # Not interesting
response['Content-length'] = str(len(response.content))
return response
def post_log(message = "", tags = []):
""" Code called via RPC. Want to know here the remote IP (or hostname). """
pass
dispatcher.register_function(post_log, 'post_log')
How could get the IP address of the client within the "post_log" definition?
I have seen IP address of client in Python SimpleXMLRPCServer? but can't apply it to my case.
Thanks.
A:
Ok I could do it ... with some nifty tips ...
First, I created my own copy of SimpleXMLRPCDispatcher which inherit everything from it and overides 2 methods :
class MySimpleXMLRPCDispatcher (SimpleXMLRPCDispatcher) :
def _marshaled_dispatch(self, data, dispatch_method = None, request = None):
# copy and paste from /usr/lib/python2.6/SimpleXMLRPCServer.py except
response = self._dispatch(method, params)
# which becomes
response = self._dispatch(method, params, request)
def _dispatch(self, method, params, request = None):
# copy and paste from /usr/lib/python2.6/SimpleXMLRPCServer.py except
return func(*params)
# which becomes
return func(request, *params)
Then in my code, all to do is :
# ...
if len(request.POST):
response = HttpResponse(mimetype="application/xml")
response.write(dispatcher._marshaled_dispatch(request.raw_post_data, request = request))
# ...
def post_log(request, message = "", tags = []):
""" Code called via RPC. Want to know here the remote IP (or hostname). """
ip = request.META["REMOTE_ADDR"]
hostname = socket.gethostbyaddr(ip)[0]
That's it.
I know it's not very clean... Any suggestion for cleaner solution is welcome!
| How to get IP when using SimpleXMLRPCDispatcher in Django | Having a code inspired from http://code.djangoproject.com/wiki/XML-RPC :
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse
dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Python 2.5
def rpc_handler(request):
"""
the actual handler:
if you setup your urls.py properly, all calls to the xml-rpc service
should be routed through here.
If post data is defined, it assumes it's XML-RPC and tries to process as such
Empty post assumes you're viewing from a browser and tells you about the service.
"""
if len(request.POST):
response = HttpResponse(mimetype="application/xml")
response.write(dispatcher._marshaled_dispatch(request.raw_post_data))
else:
pass # Not interesting
response['Content-length'] = str(len(response.content))
return response
def post_log(message = "", tags = []):
""" Code called via RPC. Want to know here the remote IP (or hostname). """
pass
dispatcher.register_function(post_log, 'post_log')
How could get the IP address of the client within the "post_log" definition?
I have seen IP address of client in Python SimpleXMLRPCServer? but can't apply it to my case.
Thanks.
| [
"Ok I could do it ... with some nifty tips ...\nFirst, I created my own copy of SimpleXMLRPCDispatcher which inherit everything from it and overides 2 methods :\nclass MySimpleXMLRPCDispatcher (SimpleXMLRPCDispatcher) :\n def _marshaled_dispatch(self, data, dispatch_method = None, request = None):\n # cop... | [
0
] | [] | [] | [
"django",
"ip_address",
"python",
"simplexmlrpcserver",
"xml_rpc"
] | stackoverflow_0003777449_django_ip_address_python_simplexmlrpcserver_xml_rpc.txt |
Q:
Python SocketServer
How can I call shutdown() in a SocketServer after receiving a certain message "exit"? As I know, the call to serve_forever() will block the server.
Thanks!
A:
Use the source, Luke!
Excerpt from SocketServer.py:
def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self.__is_shut_down.clear()
try:
while not self.__shutdown_request:
# XXX: Consider using another file descriptor or
# connecting to the socket to wake this up instead of
# polling. Polling reduces our responsiveness to a
# shutdown request and wastes cpu at all other times.
r, w, e = select.select([self], [], [], poll_interval)
if self in r:
self._handle_request_noblock()
finally:
self.__shutdown_request = False
self.__is_shut_down.set()
def shutdown(self):
"""Stops the serve_forever loop.
Blocks until the loop has finished. This must be called while
serve_forever() is running in another thread, or it will
deadlock.
"""
self.__shutdown_request = True
self.__is_shut_down.wait()
A:
No the serve_forever is checking a flag on a regular basis (by default 0.5 sec). Calling shutdown will raise this flag and cause the serve_forever to end.
| Python SocketServer | How can I call shutdown() in a SocketServer after receiving a certain message "exit"? As I know, the call to serve_forever() will block the server.
Thanks!
| [
"Use the source, Luke!\nExcerpt from SocketServer.py:\n def serve_forever(self, poll_interval=0.5):\n \"\"\"Handle one request at a time until shutdown.\n\n Polls for shutdown every poll_interval seconds. Ignores\n self.timeout. If you need to do periodic tasks, do them in\n another th... | [
6,
4
] | [] | [] | [
"python",
"sockets",
"socketserver"
] | stackoverflow_0003863281_python_sockets_socketserver.txt |
Q:
Adding or merging python dictionaries without loss
I'm trying to count up ip addresses found in a log file on two servers and then merge the dictionary stats together without loosing elements or counts. I found a partial solution in another stack overflow question but as you can see it drops the '10.10.0.1':7 pair.
>>> a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
>>> b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
>>> c = {}
>>> for elem in a:
... c[elem] = b.get(elem, 0) + a[elem]
...
>>> print c
{'55.55.55.55': 10, '12.12.12.12': 5, '127.0.0.1': 6, '192.168.1.21': 50}
The counts are being added together but if the key doesn't exist in dict a, it gets dropped. I'm having trouble figuring out the last bit of logic... perhaps another for elem in b: if a.get(elem, 0) exists: pass else add it to c?
A:
If you have Python 2.7+, try collections.Counter
Otherwise try the following:
a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
c = {}
for dictionary in (a,b):
for k,v in dictionary.iteritems():
c[k] = c.get(k, 0) + v
A:
>>> from collections import Counter
>>> a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
>>> b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
>>> Counter(a) + Counter(b)
Counter({'192.168.1.21': 50, '55.55.55.55': 10, '10.10.0.1': 7, '127.0.0.1': 6, '12.12.12.12': 5})
A:
In your code replace c = {} with c = b.copy()
A:
How about:
c = dict((k, a.get(k, 0) + b.get(k, 0)) for k in set(a.keys() + b.keys()))
A:
This should be a pretty generic answer to your question, if I got it.
def merge_sum_dictionaries(*dicts):
result_dict = {}
for d in dicts:
for key, value in d.iteritems():
result_dict.setdefault(key, 0)
result_dict[key] += value
return result_dict
if __name__ == "__main__":
a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
print merge_sum_dictionaries(a, b)
Output:
{'55.55.55.55': 10, '10.10.0.1': 7, '12.12.12.12': 5, '127.0.0.1': 6, '192.168.1.21': 50}
A:
Solution for python 2.6 and higher:
from collections import defaultdict
def merge_count_dicts(*dicts):
result = defaultdict(int)
for d in dicts:
for k, v in d.items():
result[k] += v
return result
def test():
a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
c = merge_count_dicts(a, b)
print c
if __name__ == '__main_':
test()
| Adding or merging python dictionaries without loss | I'm trying to count up ip addresses found in a log file on two servers and then merge the dictionary stats together without loosing elements or counts. I found a partial solution in another stack overflow question but as you can see it drops the '10.10.0.1':7 pair.
>>> a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
>>> b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
>>> c = {}
>>> for elem in a:
... c[elem] = b.get(elem, 0) + a[elem]
...
>>> print c
{'55.55.55.55': 10, '12.12.12.12': 5, '127.0.0.1': 6, '192.168.1.21': 50}
The counts are being added together but if the key doesn't exist in dict a, it gets dropped. I'm having trouble figuring out the last bit of logic... perhaps another for elem in b: if a.get(elem, 0) exists: pass else add it to c?
| [
"If you have Python 2.7+, try collections.Counter\nOtherwise try the following:\na = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}\nb = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}\nc = {}\nfor dictionary in (a,b):\n for k,v in dictionary.iteritems():\n c[k] = c.get(k, 0) + v\n\n",... | [
5,
5,
5,
2,
1,
1
] | [] | [] | [
"add",
"count",
"dictionary",
"merge",
"python"
] | stackoverflow_0003864517_add_count_dictionary_merge_python.txt |
Q:
in numpy what is the multi dimensional equivalent of take
I have this bit of code
def build_tree_base(blocks, x, y, z):
indicies = [
(x ,z ,y ),
(x ,z+1,y ),
(x ,z ,y+1),
(x ,z+1,y+1),
(x+1,z ,y ),
(x+1,z+1,y ),
(x+1,z ,y+1),
(x+1,z+1,y+1),
]
children = [blocks[i] for i in indicies]
return Node(children=children)
Where blocks is a 3 dimensional numpy array.
What I'd like to do is replace the list comprehension with something like numpy.take, however take seems to only deal with single dimension indices. Is there something like take that will work with multidimensional indices?
Also I know you could do this with a transpose, slice and then reshape, but that was slow so I'm looking for a better option.
A:
Numpy indexing make this quite easy... You should be able to to something like this:
def build_tree_base(blocks, x, y, z):
idx = [x, x, x, x, x+1, x+1, x+1, x+1]
idz = [z, z+1, z, z+1, z, z+1, z, z+1]
idy = [y, y, y+1, y+1, y, y, y+1, y+1]
children = blocks[idx, idz, idy]
return Node(children=children)
Edit: I should point out that this (or any other "fancy" indexing) will return a copy, rather than a view into the original array...
A:
How about taking a 2x2x2 slice, then flat ?
import numpy as np
blocks = np.arange(2*3*4.).reshape((2,3,4))
i,j,k = 0,1,2
print [x for x in blocks[i:i+2, j:j+2, k:k+2].flat]
(flat is an iterator; expand it like this, or with np.fromiter(),
or let Node iter over it.)
| in numpy what is the multi dimensional equivalent of take | I have this bit of code
def build_tree_base(blocks, x, y, z):
indicies = [
(x ,z ,y ),
(x ,z+1,y ),
(x ,z ,y+1),
(x ,z+1,y+1),
(x+1,z ,y ),
(x+1,z+1,y ),
(x+1,z ,y+1),
(x+1,z+1,y+1),
]
children = [blocks[i] for i in indicies]
return Node(children=children)
Where blocks is a 3 dimensional numpy array.
What I'd like to do is replace the list comprehension with something like numpy.take, however take seems to only deal with single dimension indices. Is there something like take that will work with multidimensional indices?
Also I know you could do this with a transpose, slice and then reshape, but that was slow so I'm looking for a better option.
| [
"Numpy indexing make this quite easy... You should be able to to something like this:\ndef build_tree_base(blocks, x, y, z):\n idx = [x, x, x, x, x+1, x+1, x+1, x+1]\n idz = [z, z+1, z, z+1, z, z+1, z, z+1]\n idy = [y, y, y+1, y+1, y, y, y+1, y+1]\n children = blocks[idx, idz, idy]\n return Node(chil... | [
2,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003813344_numpy_python.txt |
Q:
about python __doc__ docstring
i want to show docstring of my function,
but if i use like this
@cost_time
def func():
"define ...."
blabla
print func.__doc__
it will not show the docstring,just because i use some meta programming tricky,
how can fix this?
A:
Your wrapped function returned from the cost_time decorator must have the docstring instead of func. Therefore, use functools.wraps which correctly sets __name__ and __doc__:
from functools import wraps
def cost_time(fn):
@wraps(fn)
def wrapper():
return fn()
return wrapper
A:
Use functools.wraps().
| about python __doc__ docstring | i want to show docstring of my function,
but if i use like this
@cost_time
def func():
"define ...."
blabla
print func.__doc__
it will not show the docstring,just because i use some meta programming tricky,
how can fix this?
| [
"Your wrapped function returned from the cost_time decorator must have the docstring instead of func. Therefore, use functools.wraps which correctly sets __name__ and __doc__:\nfrom functools import wraps\n\ndef cost_time(fn):\n @wraps(fn)\n def wrapper():\n return fn()\n\n return wrapper\n\n",
"U... | [
12,
2
] | [] | [] | [
"doc",
"docstring",
"python"
] | stackoverflow_0003865254_doc_docstring_python.txt |
Q:
Python3 decorating conditionally?
Is it possible to decorate a function based on a condition?
a'la:
if she.weight() == duck.weight():
@burn
def witch():
pass
I'm just wondering if logic could be used (when witch is called?) to figure out whether or not to decorate witch with @burn?
If not, is it possible to create a condition within the decorator to the same effect? (witch being called undecorated.)
A:
You can create a 'conditionally' decorator:
>>> def conditionally(dec, cond):
def resdec(f):
if not cond:
return f
return dec(f)
return resdec
Usage example follows:
>>> def burn(f):
def blah(*args, **kwargs):
print 'hah'
return f(*args, **kwargs)
return blah
>>> @conditionally(burn, True)
def witch(): pass
>>> witch()
hah
>>> @conditionally(burn, False)
def witch(): pass
>>> witch()
A:
It is possible to enable/disable decorators by reassignment.
def unchanged(func):
"This decorator doesn't add any behavior"
return func
def disabled(func):
"This decorator disables the provided function, and does nothing"
def empty_func(*args,**kargs):
pass
return empty_func
# define this as equivalent to unchanged, for nice symmetry with disabled
enabled = unchanged
#
# Sample use
#
GLOBAL_ENABLE_FLAG = True
state = enabled if GLOBAL_ENABLE_FLAG else disabled
@state
def special_function_foo():
print "function was enabled"
A:
Decorators are just syntactical sugar for re-defining the function, ex:
def wrapper(f):
def inner(f, *args):
return f(*args)
return lambda *args: inner(f, *args)
def foo():
return 4
foo = wrapper(foo)
Which means that you could do it the old way, before the syntactical sugar existed:
def foo():
return 4
if [some_condition]:
foo = wrapper(foo)
| Python3 decorating conditionally? | Is it possible to decorate a function based on a condition?
a'la:
if she.weight() == duck.weight():
@burn
def witch():
pass
I'm just wondering if logic could be used (when witch is called?) to figure out whether or not to decorate witch with @burn?
If not, is it possible to create a condition within the decorator to the same effect? (witch being called undecorated.)
| [
"You can create a 'conditionally' decorator: \n>>> def conditionally(dec, cond):\n def resdec(f):\n if not cond:\n return f\n return dec(f)\n return resdec\n\nUsage example follows:\n>>> def burn(f):\n def blah(*args, **kwargs):\n print 'hah'\n return f(*args, **kwarg... | [
13,
7,
5
] | [] | [] | [
"conditional_statements",
"decorator",
"python"
] | stackoverflow_0003773555_conditional_statements_decorator_python.txt |
Q:
HTML form POST to a python script?
Does anyone know of any good resources for information on how to POST data from a HTML form over to a python script?
A:
For a very basic CGI script, you can use the cgi module. Check out the following article from the Python documentation for a very basic example on how to handle an HTML form submitted through POST:
Web Programming in Python : CGI Scripts
Example from the above article:
#!/usr/bin/env python
import cgi
import cgitb; cgitb.enable() # for troubleshooting
print "Content-type: text/html"
print
print """
<html>
<head><title>Sample CGI Script</title></head>
<body>
<h3> Sample CGI Script </h3>
"""
form = cgi.FieldStorage()
message = form.getvalue("message", "(no message)")
print """
<p>Previous message: %s</p>
<p>form
<form method="post" action="index.cgi">
<p>message: <input type="text" name="message"/></p>
</form>
</body>
</html>
""" % message
A:
You can also just use curl on the command line. If you're just wanting to emulate a user posting a form to the web server, you'd do something like:
curl -F "user=1" -F "fname=Larry" -F "lname=Luser" http://localhost:8080
There are tons of other options as well. IIRC, '-F' uses 'multipart/form-data' and replacing -F with '--data' would use urlencoded form data. Great for a quick test.
If you need to post files you can use
curl -F"@mypic.jpg" http://localhost:8080
And if you have to use Python for this and not a command line, I highly recommend the 'poster' module. http://atlee.ca/software/poster/ -- it makes this really, really easy (I know, 'cos I've done it without this module, and it's a headache).
| HTML form POST to a python script? | Does anyone know of any good resources for information on how to POST data from a HTML form over to a python script?
| [
"For a very basic CGI script, you can use the cgi module. Check out the following article from the Python documentation for a very basic example on how to handle an HTML form submitted through POST:\n\nWeb Programming in Python : CGI Scripts\n\nExample from the above article:\n#!/usr/bin/env python\n\nimport cgi\ni... | [
9,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003862788_html_python.txt |
Q:
sorting by first group element in python
I was wondering how can I make python order my collection of tuples so that first similar items would appear grouped and groups ordered by first item.
order group
3 1
4 2
2 2
1 1
After sort
order group
1 1
3 1
2 2
4 2
Python list
unordered = [(3, 1), (4, 2), (2, 2), (1, 1)]
A:
I assume you meant unordered = [(3, 1), (4, 2), (2, 2), (1, 1)] because that part of your example as you typed it is incompatible with the other two, right?
If so, then
>>> import operator
>>> sorted(unordered, key=operator.itemgetter(1,0))
[(1, 1), (3, 1), (2, 2), (4, 2)]
or similarly unordered.sort(key=operator.itemgetter(1,0)) if you wanted to sort in place (which given the variable name I'm pretty sure you don't -- it would be seriously weird to name a variable "unordered" if it's meant to be ordered!-).
| sorting by first group element in python | I was wondering how can I make python order my collection of tuples so that first similar items would appear grouped and groups ordered by first item.
order group
3 1
4 2
2 2
1 1
After sort
order group
1 1
3 1
2 2
4 2
Python list
unordered = [(3, 1), (4, 2), (2, 2), (1, 1)]
| [
"I assume you meant unordered = [(3, 1), (4, 2), (2, 2), (1, 1)] because that part of your example as you typed it is incompatible with the other two, right?\nIf so, then\n>>> import operator\n>>> sorted(unordered, key=operator.itemgetter(1,0))\n[(1, 1), (3, 1), (2, 2), (4, 2)]\n\nor similarly unordered.sort(key=op... | [
16
] | [] | [] | [
"python"
] | stackoverflow_0003865779_python.txt |
Q:
Nautilus extensions written in Python does not run when it calls gtk.main()
I'm developing a nautilus extension and I have the following code:
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import urllib
import gtk
import pygtk
import nautilus
import gconf
import gtk.glade
class Slide (nautilus.MenuProvider):
f = None
def __init__(self):
self.client = gconf.client_get_default()
self.f = gtk.glade.XML( "papel.glade" )
self.window = self.f.get_widget("window1")
gtk.main()
def oi (self):
self.window.show()
def menu_activate_cb(self, menu, file):
self.oi()
def get_file_items(self, window, files):
if len(files) != 1:
return
item = nautilus.MenuItem('NautilusPython::slide_file_item', 'Slide', 'Slide')
item.connect('activate', self.menu_activate_cb, files[0])
return item,
def get_background_items(self, window, file):
item = nautilus.MenuItem('NautilusPython::slide_item', 'Slide', 'Slide')
item.connect('activate', self.menu_background_activate_cb, file)
return item,
def menu_background_activate_cb(self, menu, file):
self.oi()
The code does not work (Slide does not appear in the context menu). But if I comment the lines:
self.f = gtk.glade.XML( "papel.glade" )
self.window = self.f.get_widget("window1")
gtk.main()
then the code runs. I can't see any problem with those lines, any help?
A:
Try only commenting gtk.main(). If it still runs after that I'm guessing that since nautilus is already running, calling gtk.main() launches a new gtk application. separate from nautilus. All you need to do is connect to nautilus and hit window.show(), which you do in your oi method.
| Nautilus extensions written in Python does not run when it calls gtk.main() | I'm developing a nautilus extension and I have the following code:
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import urllib
import gtk
import pygtk
import nautilus
import gconf
import gtk.glade
class Slide (nautilus.MenuProvider):
f = None
def __init__(self):
self.client = gconf.client_get_default()
self.f = gtk.glade.XML( "papel.glade" )
self.window = self.f.get_widget("window1")
gtk.main()
def oi (self):
self.window.show()
def menu_activate_cb(self, menu, file):
self.oi()
def get_file_items(self, window, files):
if len(files) != 1:
return
item = nautilus.MenuItem('NautilusPython::slide_file_item', 'Slide', 'Slide')
item.connect('activate', self.menu_activate_cb, files[0])
return item,
def get_background_items(self, window, file):
item = nautilus.MenuItem('NautilusPython::slide_item', 'Slide', 'Slide')
item.connect('activate', self.menu_background_activate_cb, file)
return item,
def menu_background_activate_cb(self, menu, file):
self.oi()
The code does not work (Slide does not appear in the context menu). But if I comment the lines:
self.f = gtk.glade.XML( "papel.glade" )
self.window = self.f.get_widget("window1")
gtk.main()
then the code runs. I can't see any problem with those lines, any help?
| [
"Try only commenting gtk.main(). If it still runs after that I'm guessing that since nautilus is already running, calling gtk.main() launches a new gtk application. separate from nautilus. All you need to do is connect to nautilus and hit window.show(), which you do in your oi method.\n"
] | [
1
] | [] | [] | [
"gnome",
"nautilus",
"pygtk",
"python"
] | stackoverflow_0003860021_gnome_nautilus_pygtk_python.txt |
Q:
Translating PHP’s preg_match_all to Python
Can I have a translation of PHP’s preg_match_all('/(https?:\/\/\S+)/', $text, $links) in Python, please? (ie) I need to get the links present in the plain text argument in an array.
A:
This will do it:
import re
links = re.findall('(https?://\S+)', text)
If you plan to use this multiple times than you can consider doing this:
import re
link_re = re.compile('(https?://\S+)')
links = link_re.findall(text)
| Translating PHP’s preg_match_all to Python | Can I have a translation of PHP’s preg_match_all('/(https?:\/\/\S+)/', $text, $links) in Python, please? (ie) I need to get the links present in the plain text argument in an array.
| [
"This will do it:\nimport re\nlinks = re.findall('(https?://\\S+)', text)\n\nIf you plan to use this multiple times than you can consider doing this:\nimport re\nlink_re = re.compile('(https?://\\S+)')\nlinks = link_re.findall(text)\n\n"
] | [
16
] | [] | [] | [
"php",
"python",
"regex"
] | stackoverflow_0003865896_php_python_regex.txt |
Q:
What are the full implications of not using the default 'id' primary_key in your Django model?
Consider the case where a CHAR field primary_key is required in order to define a ForeignKey relationship.
After some initial investigation I have identified the following possibilities, each with their own drawbacks:
1) Using 'primary_key=True'.
Example 1:
class Collection(models.Model):
code = models.CharField(primary_key=True, max_length=3)
class Item(models.Model):
code = models.CharField(primary_key=True, max_length=255, unique=True)
collection = models.ForeignKey('Collection', related_name='items')
Potential Drawback: Might result in issues when incorporating 3rd party apps as certain 3rd party django apps depend on the default 'id' PK integer field.
2) Use the 'to_field' / 'through' option instead.
Example 2:
class Collection(models.Model):
code = models.CharField(Max_length=3, unique=True)
class Item(models.Model):
collection = models.ForeignKey('Collection', to_field='code', related_name='items')
This will allow 'Collection' to have its own id primary_key, so it solves the problem of playing nicely with 3rd party django apps.
Potential drawbacks: After further investigation I discovered the following open Django ORM tickets and bugs with regards to dealing with mix of CHAR / INT primary_keys in FK and many-to-many relationships.
http://code.djangoproject.com/ticket/11319 and 13343
Conclusion:
Option 1 is better than Option 2.
However:
Are there many 3rd party apps that depend on the integer primary_key?
Is there an easy workaround for this limitation?
Are there any other drawbacks using a CHAR primary_key?
A:
GenericForeignKeys would suffer since they all need to use the same type for a foreign PK. As long as you stay away from them, you should be fine.
A:
I had troubles in the django admin application when using char field as primary key. See unicode error when saving an object in django admin for details
Restoring the id as primary key was difficult see What is the best approach to change primary keys in an existing Django app?.
From this experience, I think that using something else than the id as primary key is a bad idea.
A:
I personally go for Option 2 in my apps, as that's how I've seen most third-party applications do it, and it avoids the slew of problems that you already brought up in your post with regards to mixing CHAR and INT Primary Keys in the Django ORM.
I haven't run into a single issue yet just using unique=True, so I don't really see any drawbacks to doing that instead.
| What are the full implications of not using the default 'id' primary_key in your Django model? | Consider the case where a CHAR field primary_key is required in order to define a ForeignKey relationship.
After some initial investigation I have identified the following possibilities, each with their own drawbacks:
1) Using 'primary_key=True'.
Example 1:
class Collection(models.Model):
code = models.CharField(primary_key=True, max_length=3)
class Item(models.Model):
code = models.CharField(primary_key=True, max_length=255, unique=True)
collection = models.ForeignKey('Collection', related_name='items')
Potential Drawback: Might result in issues when incorporating 3rd party apps as certain 3rd party django apps depend on the default 'id' PK integer field.
2) Use the 'to_field' / 'through' option instead.
Example 2:
class Collection(models.Model):
code = models.CharField(Max_length=3, unique=True)
class Item(models.Model):
collection = models.ForeignKey('Collection', to_field='code', related_name='items')
This will allow 'Collection' to have its own id primary_key, so it solves the problem of playing nicely with 3rd party django apps.
Potential drawbacks: After further investigation I discovered the following open Django ORM tickets and bugs with regards to dealing with mix of CHAR / INT primary_keys in FK and many-to-many relationships.
http://code.djangoproject.com/ticket/11319 and 13343
Conclusion:
Option 1 is better than Option 2.
However:
Are there many 3rd party apps that depend on the integer primary_key?
Is there an easy workaround for this limitation?
Are there any other drawbacks using a CHAR primary_key?
| [
"GenericForeignKeys would suffer since they all need to use the same type for a foreign PK. As long as you stay away from them, you should be fine.\n",
"I had troubles in the django admin application when using char field as primary key. See unicode error when saving an object in django admin for details\nRestori... | [
1,
1,
0
] | [] | [] | [
"django",
"django_models",
"orm",
"python"
] | stackoverflow_0003862739_django_django_models_orm_python.txt |
Q:
Can this Python postfix notation (reverse polish notation) interpreter be made more efficient and accurate?
Here is a Python postfix notation interpreter which utilizes a stack to evaluate the expressions. Is it possible to make this function more efficient and accurate?
#!/usr/bin/env python
import operator
import doctest
class Stack:
"""A stack is a collection, meaning that it is a data structure that
contains multiple elements.
"""
def __init__(self):
"""Initialize a new empty stack."""
self.items = []
def push(self, item):
"""Add a new item to the stack."""
self.items.append(item)
def pop(self):
"""Remove and return an item from the stack. The item
that is returned is always the last one that was added.
"""
return self.items.pop()
def is_empty(self):
"""Check whether the stack is empty."""
return (self.items == [])
# Map supported arithmetic operators to their functions
ARITHMETIC_OPERATORS = {"+":"add", "-":"sub", "*":"mul", "/":"div",
"%":"mod", "**":"pow", "//":"floordiv"}
def postfix(expression, stack=Stack(), operators=ARITHMETIC_OPERATORS):
"""Postfix is a mathematical notation wherein every operator follows all
of its operands. This function accepts a string as a postfix mathematical
notation and evaluates the expressions.
1. Starting at the beginning of the expression, get one term
(operator or operand) at a time.
* If the term is an operand, push it on the stack.
* If the term is an operator, pop two operands off the stack,
perform the operation on them, and push the result back on
the stack.
2. When you get to the end of the expression, there should be exactly
one operand left on the stack. That operand is the result.
See http://en.wikipedia.org/wiki/Reverse_Polish_notation
>>> expression = "1 2 +"
>>> postfix(expression)
3
>>> expression = "5 4 3 + *"
>>> postfix(expression)
35
>>> expression = "3 4 5 * -"
>>> postfix(expression)
-17
>>> expression = "5 1 2 + 4 * + 3 -"
>>> postfix(expression, Stack(), ARITHMETIC_OPERATORS)
14
"""
if not isinstance(expression, str):
return
for val in expression.split(" "):
if operators.has_key(val):
method = getattr(operator, operators.get(val))
# The user has not input sufficient values in the expression
if len(stack.items) < 2:
return
first_out_one = stack.pop()
first_out_two = stack.pop()
operand = method(first_out_two, first_out_one)
stack.push(operand)
else:
# Type check and force int
try:
operand = int(val)
stack.push(operand)
except ValueError:
continue
return stack.pop()
if __name__ == '__main__':
doctest.testmod()
A:
General suggestions:
Avoid unnecessary type checks, and rely on default exception behavior.
has_key() has long been deprecated in favor of the in operator: use that instead.
Profile your program, before attempting any performance optimization. For a zero-effort profiling run of any given code, just run: python -m cProfile -s cumulative foo.py
Specific points:
list makes a good stack out of the box. In particular, it allows you to use slice notation (tutorial) to replace the pop/pop/append dance with a single step.
ARITHMETIC_OPERATORS can refer to operator implementations directly, without the getattr indirection.
Putting all this together:
ARITHMETIC_OPERATORS = {
'+': operator.add, '-': operator.sub,
'*': operator.mul, '/': operator.div, '%': operator.mod,
'**': operator.pow, '//': operator.floordiv,
}
def postfix(expression, operators=ARITHMETIC_OPERATORS):
stack = []
for val in expression.split():
if val in operators:
f = operators[val]
stack[-2:] = [f(*stack[-2:])]
else:
stack.append(int(val))
return stack.pop()
A:
Lists can be used directly as stacks:
>>> stack = []
>>> stack.append(3) # push
>>> stack.append(2)
>>> stack
[3, 2]
>>> stack.pop() # pop
2
>>> stack
[3]
You can also put the operator functions directly into your ARITHMETIC_OPERATORS dict:
ARITHMETIC_OPERATORS = {"+":operator.add,
"-":operator.sub,
"*":operator.mul,
"/":operator.div,
"%":operator.mod,
"**":operator.pow,
"//":operator.floordiv}
then
if operators.has_key(val):
method = operators[val]
The goal of these is not to make things more efficient (though it may have that effect) but to make them more obvious to the reader. Get rid of unnecessary levels of indirection and wrappers. That will tend to make your code less obfuscated. It will also provide (trivial) improvements in performance, but don't believe that unless you measure it.
Incidentally, using lists as stacks is fairly common idiomatic Python.
A:
You can directly map the operators: {"+": operator.add, "-": operator.sub, ...}. This is simpler, doesn't need the unnecessary getattr and also allows adding additional functions (without hacking the operator module).
You could also drop a few temporary variables that are only used once anyway:
rhs, lhs = stack.pop(), stack.pop()
stack.push(operators[val](lhs, rhs)).
Also (less of a performance and more of a style issue, also subjective), I would propably don't do error handling at all in the loop and wrap it in one try block with an except KeyError block ("Unknown operand"), an except IndexError block (empty stack), ...
But accurate? Does it give wrong results?
| Can this Python postfix notation (reverse polish notation) interpreter be made more efficient and accurate? | Here is a Python postfix notation interpreter which utilizes a stack to evaluate the expressions. Is it possible to make this function more efficient and accurate?
#!/usr/bin/env python
import operator
import doctest
class Stack:
"""A stack is a collection, meaning that it is a data structure that
contains multiple elements.
"""
def __init__(self):
"""Initialize a new empty stack."""
self.items = []
def push(self, item):
"""Add a new item to the stack."""
self.items.append(item)
def pop(self):
"""Remove and return an item from the stack. The item
that is returned is always the last one that was added.
"""
return self.items.pop()
def is_empty(self):
"""Check whether the stack is empty."""
return (self.items == [])
# Map supported arithmetic operators to their functions
ARITHMETIC_OPERATORS = {"+":"add", "-":"sub", "*":"mul", "/":"div",
"%":"mod", "**":"pow", "//":"floordiv"}
def postfix(expression, stack=Stack(), operators=ARITHMETIC_OPERATORS):
"""Postfix is a mathematical notation wherein every operator follows all
of its operands. This function accepts a string as a postfix mathematical
notation and evaluates the expressions.
1. Starting at the beginning of the expression, get one term
(operator or operand) at a time.
* If the term is an operand, push it on the stack.
* If the term is an operator, pop two operands off the stack,
perform the operation on them, and push the result back on
the stack.
2. When you get to the end of the expression, there should be exactly
one operand left on the stack. That operand is the result.
See http://en.wikipedia.org/wiki/Reverse_Polish_notation
>>> expression = "1 2 +"
>>> postfix(expression)
3
>>> expression = "5 4 3 + *"
>>> postfix(expression)
35
>>> expression = "3 4 5 * -"
>>> postfix(expression)
-17
>>> expression = "5 1 2 + 4 * + 3 -"
>>> postfix(expression, Stack(), ARITHMETIC_OPERATORS)
14
"""
if not isinstance(expression, str):
return
for val in expression.split(" "):
if operators.has_key(val):
method = getattr(operator, operators.get(val))
# The user has not input sufficient values in the expression
if len(stack.items) < 2:
return
first_out_one = stack.pop()
first_out_two = stack.pop()
operand = method(first_out_two, first_out_one)
stack.push(operand)
else:
# Type check and force int
try:
operand = int(val)
stack.push(operand)
except ValueError:
continue
return stack.pop()
if __name__ == '__main__':
doctest.testmod()
| [
"General suggestions:\n\nAvoid unnecessary type checks, and rely on default exception behavior.\nhas_key() has long been deprecated in favor of the in operator: use that instead.\nProfile your program, before attempting any performance optimization. For a zero-effort profiling run of any given code, just run: pytho... | [
10,
3,
2
] | [] | [] | [
"postfix_notation",
"python",
"rpn"
] | stackoverflow_0003865939_postfix_notation_python_rpn.txt |
Q:
IronPython & WPF: Binding a checkbox's IsChecked property to a class member variable
I've seen many similar questions on how to get data binding working with a checkbox, but all of the examples I've seen are in C# and I can't seem to make the leap to convert it to IronPython. I have a checkbox defined in a window thusly:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="Test" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<DockPanel>
<CheckBox Name="bindtest" IsChecked="{Binding Path=o1checked, Mode=OneWay}"></CheckBox>
<Button Content="Toggle" Name="Toggle" Padding="5"></Button>
</DockPanel>
</Window>
And I want its IsChecked value to automatically update when self.o1checked is toggled in the following class:
class MaikoCu64(object):
def __init__(self):
self.o1checked = False
ui.win['Button']['Toggle'].Click += self.Toggle_OnClick
def Toggle_OnClick(self, sender, event):
self.o1checked = not self.o1checked
(That ui object is a class that has the xaml loaded into it as a dictonary of ui controls. See here)
So how do I make this happen? After hours of reading through the MSDN binding documentation (also all in C#) I've tried adding this:
import System
myBinding = System.Windows.Data.Binding("o1checked")
myBinding.Source = self
myBinding.Mode = System.Windows.Data.BindingMode.OneWay
ui.win['CheckBox']['bindtest'].SetBinding(System.Windows.Controls.CheckBox.IsCheckedProperty, myBinding)
It doesn't work, but it seems like it makes at least some sense. Am I on the right track?
A:
The property should use INotifyPropertyChanged interface. See my blog for an example how to implement it in IronPython.
Also note there is a Silverlight bug in .NET or IronPython causing an error when anything else than string should be propagated back into viewmodel.
| IronPython & WPF: Binding a checkbox's IsChecked property to a class member variable | I've seen many similar questions on how to get data binding working with a checkbox, but all of the examples I've seen are in C# and I can't seem to make the leap to convert it to IronPython. I have a checkbox defined in a window thusly:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="Test" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<DockPanel>
<CheckBox Name="bindtest" IsChecked="{Binding Path=o1checked, Mode=OneWay}"></CheckBox>
<Button Content="Toggle" Name="Toggle" Padding="5"></Button>
</DockPanel>
</Window>
And I want its IsChecked value to automatically update when self.o1checked is toggled in the following class:
class MaikoCu64(object):
def __init__(self):
self.o1checked = False
ui.win['Button']['Toggle'].Click += self.Toggle_OnClick
def Toggle_OnClick(self, sender, event):
self.o1checked = not self.o1checked
(That ui object is a class that has the xaml loaded into it as a dictonary of ui controls. See here)
So how do I make this happen? After hours of reading through the MSDN binding documentation (also all in C#) I've tried adding this:
import System
myBinding = System.Windows.Data.Binding("o1checked")
myBinding.Source = self
myBinding.Mode = System.Windows.Data.BindingMode.OneWay
ui.win['CheckBox']['bindtest'].SetBinding(System.Windows.Controls.CheckBox.IsCheckedProperty, myBinding)
It doesn't work, but it seems like it makes at least some sense. Am I on the right track?
| [
"The property should use INotifyPropertyChanged interface. See my blog for an example how to implement it in IronPython.\nAlso note there is a Silverlight bug in .NET or IronPython causing an error when anything else than string should be propagated back into viewmodel.\n"
] | [
3
] | [] | [] | [
"binding",
"ironpython",
"python",
"visual_studio_2010",
"wpf"
] | stackoverflow_0003856905_binding_ironpython_python_visual_studio_2010_wpf.txt |
Q:
django error: 'unicode' object is not callable
im attempting to do the django tutorial from the django website, and ive run into a bit of an issue: ive got to adding my __unicode__ methods to my models classes, but when ever i try to return the objects of that model i get the following error:
in __unicode__
return self.question()
TypeError: 'unicode' object is not callable
im fairly new to python and very new to django, and i cant really see what ive missed here, if someone could point it out id be very grateful. A bit of code:
My models.py:
# The code is straightforward. Each model is represented by a class that subclasses django.db.models.Model. Each model has a number of
# class variables, each of which represents a database field in the model.
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice()
and in the interactive shell:
from pysite.polls.models import Poll, Choice
Poll.objects.all()
A:
self.choice is a string value, but the code is trying to call it like a function. Just remove the () after it.
| django error: 'unicode' object is not callable | im attempting to do the django tutorial from the django website, and ive run into a bit of an issue: ive got to adding my __unicode__ methods to my models classes, but when ever i try to return the objects of that model i get the following error:
in __unicode__
return self.question()
TypeError: 'unicode' object is not callable
im fairly new to python and very new to django, and i cant really see what ive missed here, if someone could point it out id be very grateful. A bit of code:
My models.py:
# The code is straightforward. Each model is represented by a class that subclasses django.db.models.Model. Each model has a number of
# class variables, each of which represents a database field in the model.
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice()
and in the interactive shell:
from pysite.polls.models import Poll, Choice
Poll.objects.all()
| [
"self.choice is a string value, but the code is trying to call it like a function. Just remove the () after it.\n"
] | [
29
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003866577_django_python.txt |
Q:
understanding zip function
All discussion is about python 3.1.2; see Python docs for the source of my question.
I know what zip does; I just don't understand why it can be implemented like this:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))
Let's say I call zip(c1, c2, c3). If I understand correctly, iterables is initially the tuple (c1, c2, c3).
The line iterables = map(iter, iterables) converts it to an iterator that would return iter(c1), iter(c2), iter(c3) if iterated through.
Inside the loop, map(next, iterables) is an iterator that would return next(iter(c1)), next(iter(c2)), and next(iter(c3)) if iterated through. The tuple call converts it to (next(iter(c1)), next(iter(c2)), next(iter(c3)), exhausting its argument (iterables) on the very first call as far as I can tell. I don't understand how the while loop manages to continue given that it checks iterables; and if it does continue why the tuple call doesn't return empty tuple (the iterator being exhausted).
I'm sure I'm missing something very simple..
A:
It looks like it's a bug in the documentation. The 'equivalent' code works in python2 but not in python3, where it goes into an infinite loop.
And the latest version of the documentation has the same problem: http://docs.python.org/release/3.1.2/library/functions.html
Looks like change 61361 was the problem, as it merged changes from python 2.6 without verifying that they were correct for python3.
It looks like the issue doesn't exist on the trunk documentation set, but you probably should report a bug about it at http://bugs.python.org/.
A:
It seems like this code is supposed to be read as python-2.x code. It doesn't even run properly in py3k.
What happens in python-2.x is that map return a list of iterators, when next is called it returns an element of iterator, those elements combined into tuple. So, given
>>> zip('ABCD', 'xy')
iterables is a list of 2 iterators, on each iteration within the while loop, next (first remaining) element of iterator is consumed (''A' and 'x', etc), and yielded as an element of a tuple, then after last elements are yielded, (on 3rd iteration) raised StopIteration stops the generator. while iterables always remains True.
| understanding zip function | All discussion is about python 3.1.2; see Python docs for the source of my question.
I know what zip does; I just don't understand why it can be implemented like this:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))
Let's say I call zip(c1, c2, c3). If I understand correctly, iterables is initially the tuple (c1, c2, c3).
The line iterables = map(iter, iterables) converts it to an iterator that would return iter(c1), iter(c2), iter(c3) if iterated through.
Inside the loop, map(next, iterables) is an iterator that would return next(iter(c1)), next(iter(c2)), and next(iter(c3)) if iterated through. The tuple call converts it to (next(iter(c1)), next(iter(c2)), next(iter(c3)), exhausting its argument (iterables) on the very first call as far as I can tell. I don't understand how the while loop manages to continue given that it checks iterables; and if it does continue why the tuple call doesn't return empty tuple (the iterator being exhausted).
I'm sure I'm missing something very simple..
| [
"It looks like it's a bug in the documentation. The 'equivalent' code works in python2 but not in python3, where it goes into an infinite loop.\nAnd the latest version of the documentation has the same problem: http://docs.python.org/release/3.1.2/library/functions.html\nLooks like change 61361 was the problem, as ... | [
9,
7
] | [] | [] | [
"iterator",
"python",
"python_3.x",
"zip"
] | stackoverflow_0003865640_iterator_python_python_3.x_zip.txt |
Q:
How to extract the bitrate and other statistics of a video file with Python
I am trying to extract the prevailing bitrate of a video file (e.g. .mkv file containing a movie) at a regular sampling interval of between 1-10 seconds under conditions of normal playback. Kind of like you may see in vlc, during playback of the file in the statistics window.
Can anyone suggest the best way to bootstrap the coding of such an analyser? Is there a library that provides an API to such information that people know of? Perhaps a Python wrapper for ffmpeg or equivalent tool that processes video files and can thereby extract such statistics.
What I am really aiming for is a CSV format file containing the seconds offset and the average or actual bitrate in KiB/s at that offset into the asset.
Update:
I built pyffmpeg and wrote the following spike:
import pyffmpeg
reader = pyffmpeg.FFMpegReader(False)
reader.open("/home/mark/Videos/BBB.m2ts", pyffmpeg.TS_VIDEO)
tracks=reader.get_tracks()
# Called for each frame
def obs(f):
pass
tracks[0].set_observer(obs)
reader.run()
But observing frame information (f) in the callback does not appear to give me any hooks to calculate per second bitrates. In fact bitrate calculations within pyffmpeg are measured across the entire file (filesize / duration) and so the treatment within the library is very superficial. Clearly its focus is on extract i-frames and other frame/GOP specific work.
A:
Something like these:
http://code.google.com/p/pyffmpeg/
http://pymedia.org/
A:
You should be able to do this with gstreamer. http://pygstdocs.berlios.de/pygst-tutorial/seeking.html has an example of a simple media player. It calls
pos_int = self.player.query_position(gst.FORMAT_TIME, None)[0]
periodically. All you have to do is call query_position() a second time with gst.FORMAT_BYTES, do some simple math, and voila! Bitrate vs. time.
| How to extract the bitrate and other statistics of a video file with Python | I am trying to extract the prevailing bitrate of a video file (e.g. .mkv file containing a movie) at a regular sampling interval of between 1-10 seconds under conditions of normal playback. Kind of like you may see in vlc, during playback of the file in the statistics window.
Can anyone suggest the best way to bootstrap the coding of such an analyser? Is there a library that provides an API to such information that people know of? Perhaps a Python wrapper for ffmpeg or equivalent tool that processes video files and can thereby extract such statistics.
What I am really aiming for is a CSV format file containing the seconds offset and the average or actual bitrate in KiB/s at that offset into the asset.
Update:
I built pyffmpeg and wrote the following spike:
import pyffmpeg
reader = pyffmpeg.FFMpegReader(False)
reader.open("/home/mark/Videos/BBB.m2ts", pyffmpeg.TS_VIDEO)
tracks=reader.get_tracks()
# Called for each frame
def obs(f):
pass
tracks[0].set_observer(obs)
reader.run()
But observing frame information (f) in the callback does not appear to give me any hooks to calculate per second bitrates. In fact bitrate calculations within pyffmpeg are measured across the entire file (filesize / duration) and so the treatment within the library is very superficial. Clearly its focus is on extract i-frames and other frame/GOP specific work.
| [
"Something like these:\nhttp://code.google.com/p/pyffmpeg/\nhttp://pymedia.org/\n",
"You should be able to do this with gstreamer. http://pygstdocs.berlios.de/pygst-tutorial/seeking.html has an example of a simple media player. It calls\npos_int = self.player.query_position(gst.FORMAT_TIME, None)[0]\n\nperiodical... | [
1,
0
] | [] | [] | [
"analysis",
"ffmpeg",
"python",
"video_processing"
] | stackoverflow_0003863432_analysis_ffmpeg_python_video_processing.txt |
Q:
Python error when running script - "IndentationError: unindent does not match any outer indentation"
I'm getting an error when I try to run my script
Error:"IndentationError: unindent does not match any outer indentation"
Code snipet that throws the error:
def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except(IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
try:
This is the actual line that occurs the error:
print "[-] Update Failed\n"
A:
Put a space before sys.exit(1) or remove space before print "[-] Error: Check your phpvuln.txt path and permissions" and print "[-] Update Failed\n".
A:
As others have mentioned, you need to make sure that each code block has the exact same indentation.
What they haven't mentioned is that the widely adopted convention is to always use exactly 4 spaces per indentation. In your code, the print statements are indented using 5 spaces (most likely by accident.) So do not add another space to sys.exit(1); remove the spaces from the print statements.
Revised code:
def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except (IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
A:
A good way to maintain a standard for your indentations is to use the tab key instead of spacebar.
A:
You have an empty try block with nothing underneath it. This is causing the error.
BTW, your sys.exit(1) is off-indent as well. In python, Indentation is important because this is how Python interpreter determines code blocks. So, you have to indent your code properly to get your code running.
A:
The indentation error happens where you have indented incorrectly. Which is clearly visible by the fact that you have different indentation in the line starting with "sys".
| Python error when running script - "IndentationError: unindent does not match any outer indentation" | I'm getting an error when I try to run my script
Error:"IndentationError: unindent does not match any outer indentation"
Code snipet that throws the error:
def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except(IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
try:
This is the actual line that occurs the error:
print "[-] Update Failed\n"
| [
"Put a space before sys.exit(1) or remove space before print \"[-] Error: Check your phpvuln.txt path and permissions\" and print \"[-] Update Failed\\n\".\n",
"As others have mentioned, you need to make sure that each code block has the exact same indentation.\nWhat they haven't mentioned is that the widely adop... | [
6,
3,
1,
0,
0
] | [] | [] | [
"indentation",
"python",
"syntax"
] | stackoverflow_0001124823_indentation_python_syntax.txt |
Q:
Clicking links by regexp in python selenium
I've been looking around and trying to find a way to click on a link in selenium that's matched by a regexp.
Here is the code that works;
from selenium import selenium
sel = selenium("localhost", 4444, "*chrome", "http://www.ncbi.nlm.nih.gov/")
sel.start()
sel.open('/pubmed')
sel.type("search_term", "20032207[uid]")
sel.click("search")
sel.click("linkout-icon-unknown-vir_full")
However if I search across different IDs the link-text will be different but it always matches the regexp linkout-icon[\w-_]*.
But I can't seem to find the right command for clicking a link which matches a regexp ... I've tried:
sel.click('link=regex:linkout-icon[\w-_]*')
sel.click('regex:linkout-icon[\w-_]*')
sel.click('link=regexp:linkout-icon[\w-_]*')
sel.click('regexp:linkout-icon[\w-_]*')
But none of them seem to work at all. Any suggestions?
EDIT:
So after comments in an answer below: The clicked item is actually an image with the id=linkout-icon-unknown-viro_full. The full line is below:
<a href="http://vir.sgmjournals.org/cgi/pmidlookup?view=long&pmid=20032207" ref="PrId=3051&itool=Abstract-def&uid=20032207&nlmid=0077340&db=pubmed&log$=linkouticon" target="_blank"><img alt="Click here to read" id="linkout-icon-unknown-vir_full" border="0" src="http://www.ncbi.nlm.nih.gov/corehtml/query/egifs/http:--highwire.stanford.edu-icons-externalservices-pubmed-standard-vir_full.gif" /></a> </div>
If your wondering I got the code from the Selenium IDE recorder.
A:
sel.click can take an XPath as an argument. Using Firebug I found (what I believe is) the XPath to "linkout-icon-unknown-vir_full" link:
sel.click("//*[@id='linkout-icon-unknown-vir_full']")
Using the above command takes me to this page.
I wasn't able to get matches to work -- I'm not sure why -- but this seems to work using contains:
sel = selenium.selenium("localhost", 4444, "*firefox", "http://www.ncbi.nlm.nih.gov/")
sel.start()
sel.open('/pubmed')
sel.type("search_term", "20032207[uid]")
sel.click("search")
sel.wait_for_page_to_load(30000)
sel.click("//*[contains(@id,'linkout')]")
A:
I think you are very close. First, regexp: is the right text pattern for saying you want to use a regular expression.
The other thing that probably isn't quite right is saying link=, as that refers to the text of the link, i.e.:
<a href="path/to/mylink">Text of the link, this is what will be searched</a>
So what part of the anchor do you want to use your regular expression on, the href?
Something that might lead towards the right answer is this: selenium: Is it possible to use the regexp in selenium locators
Maybe that get function could be repurposed to search all a.href properties for your regexp and then return the XPath of each of them to then be fed to click()
A:
After doing some hacking around I've come up with probably the most asinine way to do it but it works until someone can provide me with a better answer:
import re
val = re.findall('linkout-icon-unknown[\w-]*', sel.get_html_source())[0]
sel.click(val)
It requires me to search the entire html and will likely come up with issues if the design changes.
I'd love to see a more robust method.
| Clicking links by regexp in python selenium | I've been looking around and trying to find a way to click on a link in selenium that's matched by a regexp.
Here is the code that works;
from selenium import selenium
sel = selenium("localhost", 4444, "*chrome", "http://www.ncbi.nlm.nih.gov/")
sel.start()
sel.open('/pubmed')
sel.type("search_term", "20032207[uid]")
sel.click("search")
sel.click("linkout-icon-unknown-vir_full")
However if I search across different IDs the link-text will be different but it always matches the regexp linkout-icon[\w-_]*.
But I can't seem to find the right command for clicking a link which matches a regexp ... I've tried:
sel.click('link=regex:linkout-icon[\w-_]*')
sel.click('regex:linkout-icon[\w-_]*')
sel.click('link=regexp:linkout-icon[\w-_]*')
sel.click('regexp:linkout-icon[\w-_]*')
But none of them seem to work at all. Any suggestions?
EDIT:
So after comments in an answer below: The clicked item is actually an image with the id=linkout-icon-unknown-viro_full. The full line is below:
<a href="http://vir.sgmjournals.org/cgi/pmidlookup?view=long&pmid=20032207" ref="PrId=3051&itool=Abstract-def&uid=20032207&nlmid=0077340&db=pubmed&log$=linkouticon" target="_blank"><img alt="Click here to read" id="linkout-icon-unknown-vir_full" border="0" src="http://www.ncbi.nlm.nih.gov/corehtml/query/egifs/http:--highwire.stanford.edu-icons-externalservices-pubmed-standard-vir_full.gif" /></a> </div>
If your wondering I got the code from the Selenium IDE recorder.
| [
"sel.click can take an XPath as an argument. Using Firebug I found (what I believe is) the XPath to \"linkout-icon-unknown-vir_full\" link:\nsel.click(\"//*[@id='linkout-icon-unknown-vir_full']\")\n\nUsing the above command takes me to this page. \n\nI wasn't able to get matches to work -- I'm not sure why -- but t... | [
2,
0,
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0003865678_python_selenium.txt |
Q:
MySQL: Get dates with and without category/subcategory in ONE query (and sorted)
I have a database with 4 tables with this structure:
categories
subcategories
dates
events
We have events, that can have multiple dates. Events are categorized in categories and subcategories, but can have only a category and no subcategory, too.
I tried this query:
SELECT
t.id as sortid,
t.numprint,
s.titel,
s.intro,
s.inhalte,
s.zielgruppe,
s.methoden,
s.kapitelprint,
s.unterkapitelprint,
t.ort,
t.bundesland,
t.email,
t.telefon,
t.preis,
t.dateprint
FROM
kapitel k
LEFT JOIN
unterkapitel u
ON u.parent = k.id
LEFT JOIN
seminare s
ON s.kapitel = k.id
AND s.unterkapitel = u.id
AND s.aktiv = 1
LEFT JOIN
termine t
ON t.parent = s.id
But this doesn't get the events with no subcategory - they all have NONE in all fields.
Is there a way to get all dates in one query?
Thanks in advance,
Sebastian
A:
OK, last shot:
if you want all kapitels, regardless of whether they have an event.
SELECT *
FROM kapitel k
LEFT JOIN seminare s
ON s.kapitel = k.id
AND s.aktiv = 1
LEFT JOIN termine t
ON t.parent = s.id
LEFT JOIN unterkapitel u
ON u.parent = k.id
AND s.unterkapitel = u.id
If you want only events / siminare:
SELECT *
FROM seminare s
JOIN kapitel k
ON s.kapitel = k.id
AND s.aktiv = 1
LEFT JOIN termine t
ON t.parent = s.id
LEFT JOIN unterkapitel u
ON u.parent = k.id
AND s.unterkapitel = u.id
But I don't really like it that in theory is is possible a Seminar can have a Kapital & Unterkapitel which aren't related (which you can prevent in script of course), I keep thinking there should be a better layout for this, but the only thing I can think of is merging Kapitel & Unterkapitel into 1 table with a simple Adjancency Model, keeping you free to enter either an Kapitel or Unterkapitel in a single 'kapitel' field in Seminare, dropping the Unterkapitel field entirely.
A:
Wrikken, thanks! But this doesn't return the correct order.
I need all events (termine) from all kapitel (categories), including their unterkapitel (subcategories), but in their correct order:
sample date 1 with category a
sample date 2 with category b, subcategory b.a
sample date 3 with category b, subcategory b.a
sample date 4 with category b, subcategory b.b
sample date 6 with category b, subcategory b.c
sample date 7 with category c, subcagetory c.a
... and so on.
ie.: go into the categories, return any dates without subcategory or go into the subcategories, loop trough all of them and return all dates from these subcategories.
at the moment I'm doing this logic inside my python script, but I thought this should be possible with MySQL directly.
| MySQL: Get dates with and without category/subcategory in ONE query (and sorted) | I have a database with 4 tables with this structure:
categories
subcategories
dates
events
We have events, that can have multiple dates. Events are categorized in categories and subcategories, but can have only a category and no subcategory, too.
I tried this query:
SELECT
t.id as sortid,
t.numprint,
s.titel,
s.intro,
s.inhalte,
s.zielgruppe,
s.methoden,
s.kapitelprint,
s.unterkapitelprint,
t.ort,
t.bundesland,
t.email,
t.telefon,
t.preis,
t.dateprint
FROM
kapitel k
LEFT JOIN
unterkapitel u
ON u.parent = k.id
LEFT JOIN
seminare s
ON s.kapitel = k.id
AND s.unterkapitel = u.id
AND s.aktiv = 1
LEFT JOIN
termine t
ON t.parent = s.id
But this doesn't get the events with no subcategory - they all have NONE in all fields.
Is there a way to get all dates in one query?
Thanks in advance,
Sebastian
| [
"OK, last shot:\nif you want all kapitels, regardless of whether they have an event.\nSELECT * \nFROM kapitel k\n\nLEFT JOIN seminare s\nON s.kapitel = k.id\n AND s.aktiv = 1\n\nLEFT JOIN termine t\nON t.parent = s.id\n\nLEFT JOIN unterkapitel u\nON u.parent = k.id\n AND s.unterkapitel = u.id\n\nIf you want o... | [
0,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003866329_mysql_python.txt |
Q:
Resampling irregularly spaced data to a regular grid in Python
I need to resample 2D-data to a regular grid.
This is what my code looks like:
import matplotlib.mlab as ml
import numpy as np
y = np.zeros((512,115))
x = np.zeros((512,115))
# Just random data for this test:
data = np.random.randn(512,115)
# filling the grid coordinates:
for i in range(512):
y[i,:]=np.arange(380,380+4*115,4)
for i in range(115):
x[:,i] = np.linspace(-8,8,512)
y[:,i] -= np.linspace(-0.1,0.2,512)
# Defining the regular grid
y_i = np.arange(380,380+4*115,4)
x_i = np.linspace(-8,8,512)
resampled_data = ml.griddata(x,y,data,x_i,y_i)
(512,115) is the shape of the 2D data, and I already installed mpl_toolkits.natgrid.
My issue is that I get back a masked array, where most of the entries are nan, instead of an array that is mostly composed of regular entries and just nan at the borders.
Could someone point me to what I am doing wrong?
Thanks!
A:
Comparing your code example to your question's title, I think you're a bit confused...
In your example code, you're creating regularly gridded random data and then resampling it onto another regular grid. You don't have irregular data anywhere in your example...
(Also, the code doesn't run as-is, and you should look into meshgrid rather than looping through to generate your x & y grids.)
If you're wanting to re-sample an already regularly-sampled grid, as you do in your example, there are more efficient methods than griddata or anything I'm about to describe below. (scipy.ndimage.map_coordinates would be well suited to your problem, it that case.)
Based on your question, however, it sounds like you have irregularly spaced data that you want to interpolate onto a regular grid.
In that case, you might have some points like this:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# Bounds and number of the randomly generated data points
ndata = 20
xmin, xmax = -8, 8
ymin, ymax = 380, 2428
# Generate random data
x = np.random.randint(xmin, xmax, ndata)
y = np.random.randint(ymin, ymax, ndata)
z = np.random.random(ndata)
# Plot the random data points
plt.scatter(x,y,c=z)
plt.axis([xmin, xmax, ymin, ymax])
plt.colorbar()
plt.show()
You can then interpolate the data as you were doing before... (Continued from code snippet above...)
# Size of regular grid
ny, nx = 512, 115
# Generate a regular grid to interpolate the data.
xi = np.linspace(xmin, xmax, nx)
yi = np.linspace(ymin, ymax, ny)
xi, yi = np.meshgrid(xi, yi)
# Interpolate using delaunay triangularization
zi = mlab.griddata(x,y,z,xi,yi)
# Plot the results
plt.figure()
plt.pcolormesh(xi,yi,zi)
plt.scatter(x,y,c=z)
plt.colorbar()
plt.axis([xmin, xmax, ymin, ymax])
plt.show()
However, you'll notice that you're getting lots of artifacts in the grid. This is due to the fact that your x coordinates range from -8 to 8, while y coordinates range from ~300 to ~2500. The interpolation algorithm is trying to make things isotropic, while you may want a highly anisotropic interpolation (so that it appears isotropic when the grid is plotted).
To correct for this, you need to create a new coordinate system to do your interpolation in. There is no one right way to do this. What I'm using below will work, but the "best" way depends heavily on what your data actually represents.
(In other words, use what you know about the system that your data is measuring to decide how to do it. This is always true with interpolation! You should not interpolate unless you know what the result should look like, and are familiar enough with the interpolation algorithm to use that a priori information to your advantage!! There are also much more flexible interpolation algorithms than the Delaunay triangulation that griddata uses by default, as well, but it's fine for a simple example...)
At any rate, one way to do this is to rescale the x and y coordinates so that they range over roughly the same magnitudes. In this case. we'll rescale them from 0 to 1... (forgive the spaghetti string code... I'm just intending this to be an example...)
# (Continued from examples above...)
# Normalize coordinate system
def normalize_x(data):
data = data.astype(np.float)
return (data - xmin) / (xmax - xmin)
def normalize_y(data):
data = data.astype(np.float)
return (data - ymin) / (ymax - ymin)
x_new, xi_new = normalize_x(x), normalize_x(xi)
y_new, yi_new = normalize_y(y), normalize_y(yi)
# Interpolate using delaunay triangularization
zi = mlab.griddata(x_new, y_new, z, xi_new, yi_new)
# Plot the results
plt.figure()
plt.pcolormesh(xi,yi,zi)
plt.scatter(x,y,c=z)
plt.colorbar()
plt.axis([xmin, xmax, ymin, ymax])
plt.show()
Hope that helps, at any rate... Sorry for the length of the answer!
| Resampling irregularly spaced data to a regular grid in Python | I need to resample 2D-data to a regular grid.
This is what my code looks like:
import matplotlib.mlab as ml
import numpy as np
y = np.zeros((512,115))
x = np.zeros((512,115))
# Just random data for this test:
data = np.random.randn(512,115)
# filling the grid coordinates:
for i in range(512):
y[i,:]=np.arange(380,380+4*115,4)
for i in range(115):
x[:,i] = np.linspace(-8,8,512)
y[:,i] -= np.linspace(-0.1,0.2,512)
# Defining the regular grid
y_i = np.arange(380,380+4*115,4)
x_i = np.linspace(-8,8,512)
resampled_data = ml.griddata(x,y,data,x_i,y_i)
(512,115) is the shape of the 2D data, and I already installed mpl_toolkits.natgrid.
My issue is that I get back a masked array, where most of the entries are nan, instead of an array that is mostly composed of regular entries and just nan at the borders.
Could someone point me to what I am doing wrong?
Thanks!
| [
"Comparing your code example to your question's title, I think you're a bit confused... \nIn your example code, you're creating regularly gridded random data and then resampling it onto another regular grid. You don't have irregular data anywhere in your example...\n(Also, the code doesn't run as-is, and you shoul... | [
75
] | [] | [] | [
"matplotlib",
"python",
"resampling"
] | stackoverflow_0003864899_matplotlib_python_resampling.txt |
Q:
Descriptor that auto-detects the name of another attribute passed to it?
Can a descriptor auto-detect the name of an object passed to it?
class MyDecorator( object ):
def __init__(self, wrapped):
# Detect that wrapped's name is 'some_attr' here
pass
class SomeClass( object ):
some_attr = dict()
wrapper = MyDecorator( some_attr )
A:
No, not really. You can hack something together with introspection of call frames, but it's not a nice -- or robust -- solution. (What would you do if SomeClass had two descriptors, some_attr=MyDecorator() and someother_attr=some_attr??)
It's better to be explicit:
def mydecorator(attr):
class MyDecorator( object ):
def __get__(self,inst,instcls):
print(attr)
return MyDecorator()
class SomeClass( object ):
some_attr = mydecorator('some_attr')
someother_attr = mydecorator('someother_attr')
s=SomeClass()
s.some_attr
# some_attr
s.someother_attr
# someother_attr
| Descriptor that auto-detects the name of another attribute passed to it? | Can a descriptor auto-detect the name of an object passed to it?
class MyDecorator( object ):
def __init__(self, wrapped):
# Detect that wrapped's name is 'some_attr' here
pass
class SomeClass( object ):
some_attr = dict()
wrapper = MyDecorator( some_attr )
| [
"No, not really. You can hack something together with introspection of call frames, but it's not a nice -- or robust -- solution. (What would you do if SomeClass had two descriptors, some_attr=MyDecorator() and someother_attr=some_attr??)\nIt's better to be explicit:\ndef mydecorator(attr):\n class MyDecorator( ... | [
2
] | [
"(Answering my own question for posterity.)\nThis is the best I've come up with so far:\nclass MyDecorator( object ): \n def __init__(self, wrapped): \n import inspect ... | [
-1
] | [
"descriptor",
"metaprogramming",
"python"
] | stackoverflow_0003867472_descriptor_metaprogramming_python.txt |
Q:
How do I abort object instance creation in Python?
I want to set up a class that will abort during instance creation based on the value of the the argument passed to the class. I've tried a few things, one of them being raising an error in the __new__ method:
class a():
def __new__(cls, x):
if x == True:
return cls
else:
raise ValueError
This is what I was hoping would happen:
>>obj1 = a(True)
>>obj2 = a(False)
ValueError Traceback (most recent call last)
obj1 exists but obj2 doesn't.
Any ideas?
A:
When you override __new__, dont forget to call to super!
>>> class Test(object):
... def __new__(cls, x):
... if x:
... return super(Test, cls).__new__(cls)
... else:
... raise ValueError
...
>>> obj1 = Test(True)
>>> obj2 = Test(False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __new__
ValueError
>>> obj1
<__main__.Test object at 0xb7738b2c>
>>> obj2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'obj2' is not defined
Simply returning the class does nothing when it was your job to create an instance. This is what the super class's __new__ method does, so take advantage of it.
A:
Just raise an exception in the initializer:
class a(object):
def __init__(self, x):
if not x:
raise Exception()
| How do I abort object instance creation in Python? | I want to set up a class that will abort during instance creation based on the value of the the argument passed to the class. I've tried a few things, one of them being raising an error in the __new__ method:
class a():
def __new__(cls, x):
if x == True:
return cls
else:
raise ValueError
This is what I was hoping would happen:
>>obj1 = a(True)
>>obj2 = a(False)
ValueError Traceback (most recent call last)
obj1 exists but obj2 doesn't.
Any ideas?
| [
"When you override __new__, dont forget to call to super!\n>>> class Test(object):\n... def __new__(cls, x):\n... if x:\n... return super(Test, cls).__new__(cls)\n... else:\n... raise ValueError\n... \n>>> obj1 = Test(True)\n>>> obj2 = Test(False)\nTraceback (most recent ... | [
22,
7
] | [] | [] | [
"object",
"python"
] | stackoverflow_0003867718_object_python.txt |
Q:
MatplotLib - Displaying Data under Graph / Plot
My graph has Xticks Yticks , Xlabels , Ylabels .
My Code
firmwareList = self.firmware # Gets the list of all firmwares , this is a list
I need to put this firmware data under each bar .
Basically i need to put the build version below the X axis for each bar.
Example |
|
|
|
|
|
|____________________
0.0.1 0.0.2 0.0.3
I have already used Xticks, Xlabels .
How do i put the data on the x axis. its a list.
A:
Maybe I'm misunderstanding things, but based on your comments to @ars, simply putting appending \n and the firmware version to your xticklabels should do what you want... (I'm posting this as an answer so that I can include an example image) E.g.:
import matplotlib.pyplot as plt
plt.bar(range(3), [10,20,30], align='center')
plt.xticks(range(3), ['frogs\n1.0.0', 'turtles\n1.0.1', 'cheetas\n2.0.0'])
plt.show()
Is that what you wanted, or are you needing something more complex?
A:
You should be able to do this with the second argument to xticks function:
xticks(arange(3), ('firmware 1', 'firmware 2', 'firmware 3'))
Update: I think the following first example named "tick label like annotations" on the Matplotlib Transformations page of the SciPy cookbook covers the general method you're after.
Note that there was an API change, so line 4 should be:
blend = M.transforms.blended_transform_factory
| MatplotLib - Displaying Data under Graph / Plot | My graph has Xticks Yticks , Xlabels , Ylabels .
My Code
firmwareList = self.firmware # Gets the list of all firmwares , this is a list
I need to put this firmware data under each bar .
Basically i need to put the build version below the X axis for each bar.
Example |
|
|
|
|
|
|____________________
0.0.1 0.0.2 0.0.3
I have already used Xticks, Xlabels .
How do i put the data on the x axis. its a list.
| [
"Maybe I'm misunderstanding things, but based on your comments to @ars, simply putting appending \\n and the firmware version to your xticklabels should do what you want... (I'm posting this as an answer so that I can include an example image) E.g.:\nimport matplotlib.pyplot as plt\nplt.bar(range(3), [10,20,30], a... | [
2,
1
] | [] | [] | [
"bar_chart",
"graph",
"matplotlib",
"python"
] | stackoverflow_0003860549_bar_chart_graph_matplotlib_python.txt |
Q:
Is there a design pattern for this: hide certain methods from certain classes
I'm writing a simulation in Python for a dice game, and am trying to find the best way to handle the following situation in an Object Oriented manner.
I have a Dice class that handles rolling the dice and reporting things about the dice. This class's methods include a roll() method which modifies the dice values, and various reporting methods that describe the state of the dice, such as have_n_of_a_kind(), is_scoring_combination(), and get_roll_value().
There are two classes which make use of this Dice class. The Player, controlled directly by a human, is untrusted to always make legal moves. There is also a Turn class which enforces the rules of the game.
So then, both the Player and Turn class need to be able to ask the Dice about its values by calling the state describing methods, but the Player cannot be allowed to directly call the roll() method, because the human Player might roll when it is not supposed to.
Is there a good way for me to allow the Turn class to call a Dice object's roll() method but not allow a Player to do so?
A:
Have the Player ask the Turn to roll, by calling e.g. turn.roll_dice(). The Turn can then decide whether to roll the dice or e.g. to raise NotYourTurnError.
You can't prevent the Player class directly calling die.roll(), although you can make roll private by renaming it __roll. However, since I assume the player is controlling the die via some sort of (G?) UI, you can simply not include any way of telling the die to roll in said interface.
In general, you can't hide methods like this from arbitrary Python code with any degree of security; Python is so powerful that you'll almost certainly be able to find a way around the protection. Instead, you make them protected (_foo) or private (__foo) and assume that people who call them know what they're doing.
| Is there a design pattern for this: hide certain methods from certain classes | I'm writing a simulation in Python for a dice game, and am trying to find the best way to handle the following situation in an Object Oriented manner.
I have a Dice class that handles rolling the dice and reporting things about the dice. This class's methods include a roll() method which modifies the dice values, and various reporting methods that describe the state of the dice, such as have_n_of_a_kind(), is_scoring_combination(), and get_roll_value().
There are two classes which make use of this Dice class. The Player, controlled directly by a human, is untrusted to always make legal moves. There is also a Turn class which enforces the rules of the game.
So then, both the Player and Turn class need to be able to ask the Dice about its values by calling the state describing methods, but the Player cannot be allowed to directly call the roll() method, because the human Player might roll when it is not supposed to.
Is there a good way for me to allow the Turn class to call a Dice object's roll() method but not allow a Player to do so?
| [
"Have the Player ask the Turn to roll, by calling e.g. turn.roll_dice(). The Turn can then decide whether to roll the dice or e.g. to raise NotYourTurnError.\nYou can't prevent the Player class directly calling die.roll(), although you can make roll private by renaming it __roll. However, since I assume the player ... | [
1
] | [] | [] | [
"design_patterns",
"oop",
"python"
] | stackoverflow_0003867945_design_patterns_oop_python.txt |
Q:
imageData function in OpenCV with Python
I am trying to make some transformations on an image with OpenCV and Python. I started by reading the image with cvLoadImage function, and then I got the image data with imageData function.
img = highgui.cvLoadImage("x.png",1)
data = img.imageData
The problem is, the imageData function returns a string data and when I try to do some calculations on the image data, it gives me error because e.g. it is not allowed to do substraction on strings in Python.
I have a C code as an example, and the following calculation works completely well:
x= data[100] + 4*data[40] -data[20]
But in Python, as I said, I can't do this. Any clue about this? What is the difference about Python vs C about this statement and how can apply this kind of calculations in Python?
A:
As you've said, the imageData property returns a binary string containing the "raw image data" (I don't recall what format, though). Instead, you should access the image data by indexing into the img object:
>>> img = cv.CreateImage((10, 10), 8, 1)
>>> img[0, 0]
0.0
>>> img[0, 3] = 1.3
>>>
A:
If you're sure that the data you're getting as a string is actually an integer, you can cast it to an int.
i.e.
data = int(img.imageData)
http://docs.python.org/library/functions.html#int
This probably isn't the right way to achieve your goals however. Have you looked at the built-in library function examples?
http://opencv.willowgarage.com/documentation/python/operations_on_arrays.html
A:
Try this:
Capture Image as Array with Python OpenCV
I encourage you to take a look at Python OpenCV Cookbook.
| imageData function in OpenCV with Python | I am trying to make some transformations on an image with OpenCV and Python. I started by reading the image with cvLoadImage function, and then I got the image data with imageData function.
img = highgui.cvLoadImage("x.png",1)
data = img.imageData
The problem is, the imageData function returns a string data and when I try to do some calculations on the image data, it gives me error because e.g. it is not allowed to do substraction on strings in Python.
I have a C code as an example, and the following calculation works completely well:
x= data[100] + 4*data[40] -data[20]
But in Python, as I said, I can't do this. Any clue about this? What is the difference about Python vs C about this statement and how can apply this kind of calculations in Python?
| [
"As you've said, the imageData property returns a binary string containing the \"raw image data\" (I don't recall what format, though). Instead, you should access the image data by indexing into the img object:\n>>> img = cv.CreateImage((10, 10), 8, 1)\n>>> img[0, 0]\n0.0\n>>> img[0, 3] = 1.3\n>>>\n\n",
"If you'r... | [
1,
0,
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0003859902_opencv_python.txt |
Q:
Newbie Confusion regarding classes
I have been trying, without success, to control an object within a class from without such class. These are the important bits (not the whole thing!)
def GOGO(): ################################################
VFrame.SetStatusText("Ok") # ----> THIS IS WHAT I AM TRYING TO FIX #
# ----> I have tried all sorts of combinations #
# ----> and I still can't change this property #
################################################
# How do I fix this? What am I doing wrong??? #
################################################
class VFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, _("Glob"),
size=(1024, 768), style=wx.DEFAULT_FRAME_STYLE)
self.SetStatusText("Ready - Disconnected from Database.")
class MySplashScreen(wx.SplashScreen):
def __init__(self, parent=None):
aBitmap = wx.Image(name=img_splash).ConvertToBitmap()
splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
splashDuration = 50
wx.SplashScreen.__init__(self, aBitmap, splashStyle, splashDuration, parent)
self.Bind(wx.EVT_CLOSE, self.CloseSplash)
wx.Yield()
def CloseSplash(self, evt):
self.Hide()
frame = VFrame(parent=None)
app.SetTopWindow(frame)
frame.Show(True)
evt.Skip()
class MyApp(wx.App):
def OnInit(self):
MySplash = MySplashScreen()
MySplash.Show()
return True
if __name__ == '__main__':
app = MyApp()
app.MainLoop()
A:
You need to instantiate your VFrame class.
frame = VFrame(parent)
frame.SetStatusText("OK")
This is mostly syntactic sugar for
frame = VFrame(parent)
VFrame.SetStatusText(frame, "OK")
Essentially, you have to tell the computer which VFrame's status text you want to set.
| Newbie Confusion regarding classes | I have been trying, without success, to control an object within a class from without such class. These are the important bits (not the whole thing!)
def GOGO(): ################################################
VFrame.SetStatusText("Ok") # ----> THIS IS WHAT I AM TRYING TO FIX #
# ----> I have tried all sorts of combinations #
# ----> and I still can't change this property #
################################################
# How do I fix this? What am I doing wrong??? #
################################################
class VFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, _("Glob"),
size=(1024, 768), style=wx.DEFAULT_FRAME_STYLE)
self.SetStatusText("Ready - Disconnected from Database.")
class MySplashScreen(wx.SplashScreen):
def __init__(self, parent=None):
aBitmap = wx.Image(name=img_splash).ConvertToBitmap()
splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
splashDuration = 50
wx.SplashScreen.__init__(self, aBitmap, splashStyle, splashDuration, parent)
self.Bind(wx.EVT_CLOSE, self.CloseSplash)
wx.Yield()
def CloseSplash(self, evt):
self.Hide()
frame = VFrame(parent=None)
app.SetTopWindow(frame)
frame.Show(True)
evt.Skip()
class MyApp(wx.App):
def OnInit(self):
MySplash = MySplashScreen()
MySplash.Show()
return True
if __name__ == '__main__':
app = MyApp()
app.MainLoop()
| [
"You need to instantiate your VFrame class.\nframe = VFrame(parent)\nframe.SetStatusText(\"OK\")\n\nThis is mostly syntactic sugar for\nframe = VFrame(parent)\nVFrame.SetStatusText(frame, \"OK\")\n\nEssentially, you have to tell the computer which VFrame's status text you want to set.\n"
] | [
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0003868019_class_python.txt |
Q:
how to make a Command Line Interface from a given data model used for GUI
HI, guys. I am developing a GUI to configure and call several external programs with Python and I use wxPython for the GUI toolkits. Basically, instead of typing commands and parameters in each shell for each application (one application via one shell), the GUI is visualizing these parameters and call them as subprocesses. I have built the data model and the relevant view/gui controls (mainly by using the observer pattern or try to separate model with the gui widgets), and it is OK.
Now there is a request from my colleagues and many other people (even including myself), is it possible to have a command line interface for the subprocesses, or even for the whole configuration GUI, based on the data model I already have? This is due to the fact that many people prefer CLI, CLI is better in reliability, and also needs of programmer debugging and interfacing.
As I am rather new to developing a CLI, I really need some help from you. I appreciate any advice and information from you.
to be more specific,
If I completely forget about the data model built for GUI, start from scratch. Is there some good materials or samples to have a reference?
If I still want to utilize the data model built for GUI, is it possible? If possible, what shall I do and any samples to follow? Do I need to refactor the data model?
Is it possible to have the CLI and GUI at the same time? I mean, can I take the CLI as another view of the data model? Or there is other right approach?
Thank you very much for your help!!
A:
If you can call your data model's methods from your GUI and they don't depend on anything in the GUI, then yes, you should be able to call those same methods from another GUI, be it CLI, pyGTK or whatever.
A:
Is it possible to have the CLI and GUI at the same time? I mean, can I take the CLI as another view of the data model? Or there is other right approach?
That's correct, a CLI is just another frontend to access the data model. You said your model is clean of GUI code? (it should, even if you only had one frontend) in this case adding CLI capabilities should be trivial; a sane command-line design (options, subcommands) and optparse is all you need.
| how to make a Command Line Interface from a given data model used for GUI | HI, guys. I am developing a GUI to configure and call several external programs with Python and I use wxPython for the GUI toolkits. Basically, instead of typing commands and parameters in each shell for each application (one application via one shell), the GUI is visualizing these parameters and call them as subprocesses. I have built the data model and the relevant view/gui controls (mainly by using the observer pattern or try to separate model with the gui widgets), and it is OK.
Now there is a request from my colleagues and many other people (even including myself), is it possible to have a command line interface for the subprocesses, or even for the whole configuration GUI, based on the data model I already have? This is due to the fact that many people prefer CLI, CLI is better in reliability, and also needs of programmer debugging and interfacing.
As I am rather new to developing a CLI, I really need some help from you. I appreciate any advice and information from you.
to be more specific,
If I completely forget about the data model built for GUI, start from scratch. Is there some good materials or samples to have a reference?
If I still want to utilize the data model built for GUI, is it possible? If possible, what shall I do and any samples to follow? Do I need to refactor the data model?
Is it possible to have the CLI and GUI at the same time? I mean, can I take the CLI as another view of the data model? Or there is other right approach?
Thank you very much for your help!!
| [
"If you can call your data model's methods from your GUI and they don't depend on anything in the GUI, then yes, you should be able to call those same methods from another GUI, be it CLI, pyGTK or whatever.\n",
"Is it possible to have the CLI and GUI at the same time? I mean, can I take the CLI as another view of... | [
1,
1
] | [] | [] | [
"command_line_interface",
"python",
"user_interface",
"wxpython",
"wxwidgets"
] | stackoverflow_0003867500_command_line_interface_python_user_interface_wxpython_wxwidgets.txt |
Q:
Trouble with Emacs pdb and breakpoints in multi-threaded Python code
I am running Emacs 23.2 with python.el and debugging some Python code with pdb.
My code spawns a sibling thread using the threading module and I set a breakpoint at the start of the run() method, but the break is never handled by pdb even though the code definitely runs and works for all intents and purposes.
I was under the impression that I could use pdb to establish breakpoints in any thread, even though full multi-threaded debugging is in fact not supported.
Am I wrong in assuming pdb within an M-x pdb invocation can break within any thread? If you don't believe me try this minimal example for yourself.
import threading
class ThreadTest(threading.Thread):
def __init__(self,):
threading.Thread.__init__(self)
def run(self):
print "Type M-x pdb, set a breakpoint here then type c <RET>..."
print "As you can see it does not break!"
if __name__ == '__main__':
tt = ThreadTest()
tt.start()
Thanks to Pierre and the book text he refers to, I tried the option to include pdb.set_trace() as follows:
def run(self):
import pdb; pdb.set_trace()
print "Set a breakpoint here then M-x pdb and type c..."
But this only breaks and offers pdb controls for step, next, continue etcetera, if it is executed from a console and run directly within the Python interpreter, and crucially not via M-x pdb - at least with my Emacs and pdb configuration.
So my original question could do with being rephrased:
Is there a way to invoke a Python program from within Emacs, where that program uses inlined invocation of pdb (thereby supporting breaks in multi-threaded applications), and for there to be a pdb comint control buffer established auto-magically?
or
If I run my Python application using M-x pdb and it contains an inline invocation of pdb, how best to handle the fact that this results in a pdb-session-within-a-pdb-session with the associated loss of control?
A:
See http://heather.cs.ucdavis.edu/~matloff/158/PLN/ParProcBook.pdf, there's a section on multithreaded debugging.
3.6.1 Using PDB to Debug Threaded Programs
Using PDB is a bit more complex when threads are involved. One cannot, for instance, simply do something
like this:
pdb.py buggyprog.py
because the child threads will not inherit the PDB process from the main thread. You can still run PDB in
the latter, but will not be able to set breakpoints in threads.
What you can do, though, is invoke PDB from within the function which is run by the thread, by calling
pdb.set trace() at one or more points within the code:
import pdb
pdb.set_trace()
In essence, those become breakpoints.
For example, in our program srvr.py in Section 3.1.1, we could add a PDB call at the beginning of the loop
in serveclient():
while 1:
import pdb
pdb.set_trace()
# receive letter from client, if it is still connected
k = c.recv(1)
if k == ’’: break
You then run the program directly through the Python interpreter as usual, NOT through PDB, but then the
program suddenly moves into debugging mode on its own. At that point, one can then step through the code
using the n or s commands, query the values of variables, etc.
PDB’s c (“continue”) command still works. Can one still use the b command to set additional breakpoints?
Yes, but it might be only on a one-time basis, depending on the context. A breakpoint might work only once,
due to a scope problem. Leaving the scope where we invoked PDB causes removal of the trace object. Thus
I suggested setting up the trace inside the loop above.
A:
Are you using the default python.el? I've given up on that and started using python-mode.el. Then type M-x shell, from the prompt type python myproblem.py (replace with your program name of course) and it will stop at the set_trace line. It works out of the box with pdb integration. (And it works on your program).
| Trouble with Emacs pdb and breakpoints in multi-threaded Python code | I am running Emacs 23.2 with python.el and debugging some Python code with pdb.
My code spawns a sibling thread using the threading module and I set a breakpoint at the start of the run() method, but the break is never handled by pdb even though the code definitely runs and works for all intents and purposes.
I was under the impression that I could use pdb to establish breakpoints in any thread, even though full multi-threaded debugging is in fact not supported.
Am I wrong in assuming pdb within an M-x pdb invocation can break within any thread? If you don't believe me try this minimal example for yourself.
import threading
class ThreadTest(threading.Thread):
def __init__(self,):
threading.Thread.__init__(self)
def run(self):
print "Type M-x pdb, set a breakpoint here then type c <RET>..."
print "As you can see it does not break!"
if __name__ == '__main__':
tt = ThreadTest()
tt.start()
Thanks to Pierre and the book text he refers to, I tried the option to include pdb.set_trace() as follows:
def run(self):
import pdb; pdb.set_trace()
print "Set a breakpoint here then M-x pdb and type c..."
But this only breaks and offers pdb controls for step, next, continue etcetera, if it is executed from a console and run directly within the Python interpreter, and crucially not via M-x pdb - at least with my Emacs and pdb configuration.
So my original question could do with being rephrased:
Is there a way to invoke a Python program from within Emacs, where that program uses inlined invocation of pdb (thereby supporting breaks in multi-threaded applications), and for there to be a pdb comint control buffer established auto-magically?
or
If I run my Python application using M-x pdb and it contains an inline invocation of pdb, how best to handle the fact that this results in a pdb-session-within-a-pdb-session with the associated loss of control?
| [
"See http://heather.cs.ucdavis.edu/~matloff/158/PLN/ParProcBook.pdf, there's a section on multithreaded debugging.\n\n3.6.1 Using PDB to Debug Threaded Programs\nUsing PDB is a bit more complex when threads are involved. One cannot, for instance, simply do something\nlike this:\npdb.py buggyprog.py\nbecause the chi... | [
1,
1
] | [] | [] | [
"emacs",
"multithreading",
"pdb",
"python"
] | stackoverflow_0003867892_emacs_multithreading_pdb_python.txt |
Q:
Please Help: IPython for Emacs on Windows crashes
Questions Update: Why there is no In[1]: prompt?
Please see the following output of IPython command line in Emacs.
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
import sys
sys.path
Out[4]:
['',
'C:\\Python25\\scripts',
'C:\\Python25\\lib\\site-packages\\pyflakes-0.4.0-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\pylint-0.21.3-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\logilab_astng-0.20.3-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\logilab_common-0.52.0-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\unittest2-0.5.1-py2.5.egg',
'C:\\Python25\\Lib\\site-packages\\pyflakes',
'C:\\Python25\\Lib\\site-packages\\Pymacs',
'C:\\Python25\\Lib\\site-packages\\rope',
'C:\\Python25\\Lib\\site-packages\\ropemacs',
'C:\\Python25\\Lib\\site-packages\\ropemode',
'C:\\WINDOWS\\system32\\python25.zip',
'C:\\Python25\\DLLs',
'C:\\Python25\\lib',
'C:\\Python25\\lib\\plat-win',
'C:\\Python25\\lib\\lib-tk',
'C:\\Python25',
'C:\\Python25\\lib\\site-packages',
'C:\\Python25\\lib\\site-packages\\win32',
'C:\\Python25\\lib\\site-packages\\win32\\lib',
'C:\\Python25\\lib\\site-packages\\Pythonwin',
'C:\\Python25\\lib\\site-packages\\IPython/Extensions',
u'C:\\Home\\_ipython']
Hi,
I am using IPython 0.10, Python 2.5, and EmacsW32 23.1 and ipython.el Rev.2927 on Windows XP. It always crashes when I invoke python-shell in Emacs. Could somebody helps on this problem? Thanks a lot!
update: I've tried the fix https://bugs.launchpad.net/ipython/+bug/290228 , but it doesn't help.
IPython crashes with the following long debugging information:
ERROR: An unexpected error occurred
while tokenizing input The following
traceback may be corrupted or invalid
The error message is: ('EOF in
multi-line statement', (14, 0))
--------------------------------------------------------------------------- TypeError
Python 2.5.2: C: \Python25\python.exe
Thu Sep 30 14:00:08 2010 A problem
occured executing Python code. Here
is the sequence of function calls
leading up to the error, with the most
recent (innermost) call last.
c:\Python25\Scripts\ipython-script.py
in ()
1
2
3
4
5
6
7
----> 8
global load_entry_point =
9 #!C:\Python25\python.exe
10 # EASY-INSTALL-ENTRY-SCRIPT: 'ipython==0.10','console_scripts','ipython'
11 requires = 'ipython==0.10'
12 import sys
13 from pkg_resources import load_entry_point
14
15 sys.exit(
16 load_entry_point('ipython==0.10',
'console_scripts', 'ipython')()
17 )
18
19
20
21
22
23
24
25
26
27
28
29
30
31
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\ipapi.pyc
in launch_new_instance(user_ns=None,
shellclass=None)
541
542 def check_hotname(self,name):
543 if name in self.hotnames:
544 self.debug_stack( "HotName '%s' caught" % name)
545
546
547 def launch_new_instance(user_ns =
None,shellclass = None):
548 """ Make and start a new ipython instance.
549
550 This can be called even without having an already initialized
551 ipython session running.
552
553 This is also used as the egg entry point for the 'ipython'
script.
554
555 """
--> 556 ses = make_session(user_ns,shellclass)
557 ses.mainloop()
558
559
560 def make_user_ns(user_ns = None):
561 """Return a valid user interactive namespace.
562
563 This builds a dict with the minimal information needed to
operate as a
564 valid IPython user namespace, which you can pass to the
various embedding
565 classes in ipython.
566
567 This API is currently deprecated. Use
ipapi.make_user_namespaces() instead
568 to make both the local and global namespace objects
simultaneously.
569
570 :Parameters:
571 user_ns : dict-like, optional
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\ipapi.pyc
in make_session(user_ns=None,
shellclass=None)
669
670 def make_session(user_ns = None, shellclass = None):
671 """Makes, but does not launch an IPython session.
672
673 Later on you can call obj.mainloop() on the returned object.
674
675 Inputs:
676
677 - user_ns(None): a dict to be used as the user's namespace
with initial
678 data.
679
680 WARNING: This should not be run when a session exists
already."""
681
682 import IPython.Shell
683 if shellclass is None:
--> 684 return IPython.Shell.start(user_ns)
685 return shellclass(user_ns = user_ns)
686
687
688
689
690
691
692
693
694
695
696
697
698
699
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\Shell.pyc
in start(user_ns=None) 1226
th_mode = special_opts.pop() 1227
except KeyError: 1228
th_mode = 'tkthread' 1229
return th_shell[th_mode] 1230
1231 1232 # This is the one which
should be called by external code.
1233 def start(user_ns = None):
1234 """Return a running shell
instance, dealing with threading
options. 1235 1236 This is a
factory function which will
instantiate the proper IPython shell
1237 based on the user's threading
choice. Such a selector is needed
because 1238 different GUI
toolkits require different thread
handling details.""" 1239 1240
shell = _select_shell(sys.argv)
-> 1241 return shell(user_ns = user_ns) 1242 1243 # Some
aliases for backwards compatibility
1244 IPythonShell = IPShell 1245
IPythonShellEmbed = IPShellEmbed
1246 #************ End of
file
************* 1247 1248 1249 1250 1251 1252
1253 1254 1255 1256
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\Shell.pyc
in
init(self=, argv=None,
user_ns=None, user_global_ns=None,
debug=1, shell_class=)
58 # Default timeout for waiting for multithreaded shells (in seconds)
59 GUI_TIMEOUT = 10
60
61
-----------------------------------------------------------------------------
62 # This class is trivial now, but I want to have it in to publish a
clean
63 # interface. Later when the internals are reorganized, code that
uses this
64 # shouldn't have to change.
65
66 class IPShell:
67 """Create an IPython instance."""
68
69 def
init(self,argv=None,user_ns=None,user_global_ns=None,
70 debug=1,shell_class=InteractiveShell):
71 self.IP = make_IPython(argv,user_ns=user_ns,
72 user_global_ns=user_global_ns,
---> 73 debug=debug,shell_class=shell_class)
global that = undefined
global gets = undefined
global prepended = undefined
global to = undefined
global all = undefined
global calls = undefined
global so = undefined
global header = undefined
global used = undefined
74
75 def mainloop(self,sys_exit=0,banner=None):
76 self.IP.mainloop(banner)
77 if sys_exit:
78 sys.exit()
79
80
-----------------------------------------------------------------------------
81 def kill_embedded(self,parameter_s=''):
82 """%kill_embedded : deactivate for good the current
embedded IPython.
83
84 This function (after asking for confirmation) sets an
internal flag so that
85 an embedded IPython will never activate again. This is useful
to
86 permanently disable a shell that is being called inside a
loop: once you've
87 figured out what you needed from it, you may then kill it
and the program
88 will then continue to run without the interactive shell
interfering again.
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython
\ipmaker.pyc in
make_IPython(argv=[r'c:\Python25\Scripts\ipython-
script.py', '-i'], user_ns=None,
user_global_ns=None, debug=1,
rc_override=None, shell_class=,
embedded=False, kw={})
755 IP_rc.banner = 0
756 if IP_rc.banner:
757 BANN_P = IP.BANNER_PARTS
758 else:
759 BANN_P = []
760
761 if IP_rc.profile: BANN_P.append('IPython profile: %s\n'
% IP_rc.profile)
762
763 # add message log (possibly empty)
764 if msg.summary: BANN_P.append(msg.summary)
765 # Final banner is a string
766 IP.BANNER = '\n'.join(BANN_P)
767
768 # Finalize the IPython instance. This assumes the rc
structure is fully
769 # in place.
--> 770 IP.post_config_initialization()
771
772 return IP
773 #************** end of file
774
775
776
777
778
779
780
781
782
783
784
785
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\iplib.pyc
in
post_config_initialization(self=)
847 This is called after the configuration files have been
processed to
848 'finalize' the initialization."""
849
850 rc = self.rc
851
852 # Object inspector
853 self.inspector = OInspect.Inspector(OInspect.InspectColors,
854 PyColorize.ANSICodeColors,
855 'NoColor',
856 rc.object_info_string_level)
857
858 self.rl_next_input = None
859 self.rl_do_indent = False
860 # Load readline proper
861 if rc.readline:
--> 862 self.init_readline()
863
864 # local shortcut, this is used a LOT
865 self.log = self.logger.log
866
867 # Initialize cache, set in/out prompts and printing system
868 self.outputcache = CachedOutput(self,
869 rc.cache_size,
870 rc.pprint,
871 input_sep = rc.separate_in,
872 output_sep = rc.separate_out,
873 output_sep2 = rc.separate_out2,
874 ps1 = rc.prompt_in1,
875 ps2 = rc.prompt_in2,
876 ps_out = rc.prompt_out,
877 pad_left = rc.prompts_pad_left)
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\iplib.pyc
in
init_readline(self=) 1476
if not readline.uses_libedit: 1477
for rlcommand in
self.rc.readline_parse_and_bind:
1478 #print
"loading rl:",rlcommand # dbg 1479
readline.parse_and_bind(rlcommand)
1480 1481 # Remove some
chars from the delimiters list. If we
encounter 1482 #
unicode chars, discard them. 1483
delims =
readline.get_completer_delims().encode("ascii",
"ignore") 1484 delims =
delims.translate(string._idmap,
1485 self.rc.readline_remove_delims)
1486
readline.set_completer_delims(delims)
1487 # otherwise we end up
with a monster history after a while:
1488
readline.set_history_length(1000)
1489 try: 1490
print '* Reading readline history' # dbg
-> 1491 readline.read_history_file(self.histfile)
1492 except IOError:
1493 pass # It
doesn't exist yet. 1494 1495
atexit.register(self.atexit_operations)
1496 del atexit 1497
1498 # Configure auto-indent
for all platforms 1499
self.set_autoindent(self.rc.autoindent)
1500 1501 def
ask_yes_no(self,prompt,default=True):
1502 if self.rc.quiet: 1503
return True 1504 return
ask_yes_no(prompt,default) 1505
1506 def
new_main_mod(self,ns=None):
C:\Python25\lib\site-packages\pyreadline\rlmain.pyc
in
read_history_file(self=,
filename=u'C:\Home\_ipython\history')
168
169 def set_history_length(self, length):
170 '''Set the number of lines to save in the history file.
171
172 write_history_file() uses this value to truncate the
history file
173 when saving. Negative values imply unlimited history file
size.
174 '''
175 self._history.set_history_length(length)
176
177 def clear_history(self):
178 '''Clear readline history'''
179 self._history.clear_history()
180
181 def read_history_file(self,
filename=None):
182 '''Load a readline history file. The default filename is
~/.history.'''
--> 183 self._history.read_history_file(filename)
184
185 def write_history_file(self,
filename=None):
186 '''Save a readline history file. The default filename is
~/.history.'''
187 self._history.write_history_file(filename)
188
189 #Completer functions
190
191 def set_completer(self, function=None):
192 '''Set or remove the completer function.
193
194 If function is specified, it will be used as the new
completer
195 function; if omitted or None, any completer function
already
196 installed is removed. The completer function is called as
197 function(text, state), for state in 0, 1, 2, ..., until it
returns a
198 non-string value. It should return the next possible
completion
C:\Python25\lib\site-packages\pyreadline\lineeditor\history.pyc
in
read_history_file(self=,
filename=u'C:\Home\_ipython\history')
55
56 history_length=property(get_history_length,set_history_length)
57 history_cursor=property(get_history_cursor,set_history_cursor)
58
59 def clear_history(self):
60 '''Clear readline history.'''
61 self.history[:] = []
62 self.history_cursor = 0
63
64 def read_history_file(self,
filename=None):
65 '''Load a readline history file.'''
66 if filename is None:
67 filename=self.history_filename
68 try:
69 for line in open(filename, 'r'):
---> 70 self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip())))
global n = undefined
global Xd = undefined
global S = undefined
global NR = undefined
global i = undefined
global R2 = undefined
global R = undefined
global t = undefined
global history_search_forwardt = undefined
global history_search_backwardt = undefined
global joinR2 = undefined
global maxR = undefined
global mint = undefined
global IndexError = undefined
global RX = undefined
global partialt = undefined
global hcstartt = undefined
global hct = undefined
global ht = undefined
global result = undefined
global s = undefined
global C = undefined
global Python25 = undefined
global lib = undefined
global site = undefined
global packages = undefined
global pyreadline =
global lineeditor = undefined
global history.pyt = undefined
global search = undefined
global I = undefined
global c = undefined
global d = undefined
global Search = undefined
global forward = undefined
global through = undefined
global the = undefined
global history = undefined
global string =
global of = undefined
global characters = undefined
global between = undefined
global start = undefined
global current = undefined
line = 'import sys\n'
global point.This = undefined
global a = undefined
global non = undefined
global incremental = undefined
global search.By = undefined
global default = undefined
global this = undefined
global command = undefined
global unbound.i = undefined
global Rj = undefined
global Re = undefined
global q = undefined
global history.pyR = undefined
global backward = undefined
global Rk = undefined
global history.pyR = undefined
global N = undefined
global propertyR = undefined
global R4 = undefined
global R5 = undefined
global R7 = undefined
global R8 = undefined
global RC = undefined
global RD = undefined
global R_ = undefined
global s.t = undefined
Press enter to exit: global
_main_t = undefined
global aaaat = undefined
global aabat = undefined
global aacat = undefined
global akcat = undefined
global bbbt = undefined
global ako = undefined
global ret = undefined
global operatorRS = undefined
global sysR = undefined
global pyreadline.unicode_helperR = undefined
global modulesR = undefined
global exceptionst = undefined
global ExceptionR = undefined
global pyreadline.loggerR = undefined
global FalseR9 = undefined
global objectR = undefined
global RLR = undefined
global history.pys = undefined
global module = undefined
71 except IOError:
72 self.history = []
73 self.history_cursor = 0
74
75 def write_history_file(self,
filename=None):
76 '''Save a readline history file.'''
77 if filename is None:
78 filename=self.history_filename
79 fp = open(filename, 'wb')
80 for line in self.history[-self.history_length:]:
81 fp.write(ensure_str(line.get_line_text()))
82 fp.write('\n')
83 fp.close()
84
85
C:\Python25\lib\site-packages\pyreadline\unicode_helper.pyc
in ensure_unicode(text='import sys')
5 # Distributed under the terms of the BSD License. The full license
is in
6 # the file COPYING, distributed as part of this software.
7
*******************************************
8 import sys
9
10 try:
11 pyreadline_codepage=sys.stdout.encoding
12 except AttributeError: #This error occurs when pdb imports readline and doctest has replaced
13 #stdout with stdout collector
14 pyreadline_codepage="ascii" #assume
ascii codepage
15
16
17 def ensure_unicode(text):
18 """helper to ensure that text passed to WriteConsoleW is
unicode"""
19 if isinstance(text, str):
---> 20 return text.decode(pyreadline_codepage,
"replace")
21 return text
22
23 def ensure_str(text):
24 """Convert unicode to str using pyreadline_codepage"""
25 if isinstance(text, unicode):
26 return text.encode(pyreadline_codepage,
"replace")
27 return text
28
29
30
31
32
33
34
35
TypeError: decode() argument 1 must be
string, not None
Oops, IPython crashed. We do our best
to make it stable, but...
A crash report was automatically
generated with the following
information:
- A verbatim copy of the crash traceback.
- A copy of your input history during this session.
- Data on your current IPython configuration.
It was left in the file named:
'C:\Home_ipython\IPython_crash_report.txt'
If you can email this file to the
developers, the information in it will
help them in understanding and
correcting the problem.
You can mail it to: Fernando Perez at
fperez....@gmail.com with the subject
'IPython Crash Report'.
If you want to do it now, the
following command will work (under
Unix): mail -s 'IPython Crash Report'
fperez....@gmail.com <
C:\Home_ipython
\IPython_crash_report.txt
To ensure accurate tracking of this
issue, please file a report about it
at:
https://bugs.launchpad.net/ipython/+filebug
A:
Installing pyreadline should help.
| Please Help: IPython for Emacs on Windows crashes | Questions Update: Why there is no In[1]: prompt?
Please see the following output of IPython command line in Emacs.
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
import sys
sys.path
Out[4]:
['',
'C:\\Python25\\scripts',
'C:\\Python25\\lib\\site-packages\\pyflakes-0.4.0-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\pylint-0.21.3-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\logilab_astng-0.20.3-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\logilab_common-0.52.0-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\unittest2-0.5.1-py2.5.egg',
'C:\\Python25\\Lib\\site-packages\\pyflakes',
'C:\\Python25\\Lib\\site-packages\\Pymacs',
'C:\\Python25\\Lib\\site-packages\\rope',
'C:\\Python25\\Lib\\site-packages\\ropemacs',
'C:\\Python25\\Lib\\site-packages\\ropemode',
'C:\\WINDOWS\\system32\\python25.zip',
'C:\\Python25\\DLLs',
'C:\\Python25\\lib',
'C:\\Python25\\lib\\plat-win',
'C:\\Python25\\lib\\lib-tk',
'C:\\Python25',
'C:\\Python25\\lib\\site-packages',
'C:\\Python25\\lib\\site-packages\\win32',
'C:\\Python25\\lib\\site-packages\\win32\\lib',
'C:\\Python25\\lib\\site-packages\\Pythonwin',
'C:\\Python25\\lib\\site-packages\\IPython/Extensions',
u'C:\\Home\\_ipython']
Hi,
I am using IPython 0.10, Python 2.5, and EmacsW32 23.1 and ipython.el Rev.2927 on Windows XP. It always crashes when I invoke python-shell in Emacs. Could somebody helps on this problem? Thanks a lot!
update: I've tried the fix https://bugs.launchpad.net/ipython/+bug/290228 , but it doesn't help.
IPython crashes with the following long debugging information:
ERROR: An unexpected error occurred
while tokenizing input The following
traceback may be corrupted or invalid
The error message is: ('EOF in
multi-line statement', (14, 0))
--------------------------------------------------------------------------- TypeError
Python 2.5.2: C: \Python25\python.exe
Thu Sep 30 14:00:08 2010 A problem
occured executing Python code. Here
is the sequence of function calls
leading up to the error, with the most
recent (innermost) call last.
c:\Python25\Scripts\ipython-script.py
in ()
1
2
3
4
5
6
7
----> 8
global load_entry_point =
9 #!C:\Python25\python.exe
10 # EASY-INSTALL-ENTRY-SCRIPT: 'ipython==0.10','console_scripts','ipython'
11 requires = 'ipython==0.10'
12 import sys
13 from pkg_resources import load_entry_point
14
15 sys.exit(
16 load_entry_point('ipython==0.10',
'console_scripts', 'ipython')()
17 )
18
19
20
21
22
23
24
25
26
27
28
29
30
31
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\ipapi.pyc
in launch_new_instance(user_ns=None,
shellclass=None)
541
542 def check_hotname(self,name):
543 if name in self.hotnames:
544 self.debug_stack( "HotName '%s' caught" % name)
545
546
547 def launch_new_instance(user_ns =
None,shellclass = None):
548 """ Make and start a new ipython instance.
549
550 This can be called even without having an already initialized
551 ipython session running.
552
553 This is also used as the egg entry point for the 'ipython'
script.
554
555 """
--> 556 ses = make_session(user_ns,shellclass)
557 ses.mainloop()
558
559
560 def make_user_ns(user_ns = None):
561 """Return a valid user interactive namespace.
562
563 This builds a dict with the minimal information needed to
operate as a
564 valid IPython user namespace, which you can pass to the
various embedding
565 classes in ipython.
566
567 This API is currently deprecated. Use
ipapi.make_user_namespaces() instead
568 to make both the local and global namespace objects
simultaneously.
569
570 :Parameters:
571 user_ns : dict-like, optional
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\ipapi.pyc
in make_session(user_ns=None,
shellclass=None)
669
670 def make_session(user_ns = None, shellclass = None):
671 """Makes, but does not launch an IPython session.
672
673 Later on you can call obj.mainloop() on the returned object.
674
675 Inputs:
676
677 - user_ns(None): a dict to be used as the user's namespace
with initial
678 data.
679
680 WARNING: This should not be run when a session exists
already."""
681
682 import IPython.Shell
683 if shellclass is None:
--> 684 return IPython.Shell.start(user_ns)
685 return shellclass(user_ns = user_ns)
686
687
688
689
690
691
692
693
694
695
696
697
698
699
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\Shell.pyc
in start(user_ns=None) 1226
th_mode = special_opts.pop() 1227
except KeyError: 1228
th_mode = 'tkthread' 1229
return th_shell[th_mode] 1230
1231 1232 # This is the one which
should be called by external code.
1233 def start(user_ns = None):
1234 """Return a running shell
instance, dealing with threading
options. 1235 1236 This is a
factory function which will
instantiate the proper IPython shell
1237 based on the user's threading
choice. Such a selector is needed
because 1238 different GUI
toolkits require different thread
handling details.""" 1239 1240
shell = _select_shell(sys.argv)
-> 1241 return shell(user_ns = user_ns) 1242 1243 # Some
aliases for backwards compatibility
1244 IPythonShell = IPShell 1245
IPythonShellEmbed = IPShellEmbed
1246 #************ End of
file
************* 1247 1248 1249 1250 1251 1252
1253 1254 1255 1256
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\Shell.pyc
in
init(self=, argv=None,
user_ns=None, user_global_ns=None,
debug=1, shell_class=)
58 # Default timeout for waiting for multithreaded shells (in seconds)
59 GUI_TIMEOUT = 10
60
61
-----------------------------------------------------------------------------
62 # This class is trivial now, but I want to have it in to publish a
clean
63 # interface. Later when the internals are reorganized, code that
uses this
64 # shouldn't have to change.
65
66 class IPShell:
67 """Create an IPython instance."""
68
69 def
init(self,argv=None,user_ns=None,user_global_ns=None,
70 debug=1,shell_class=InteractiveShell):
71 self.IP = make_IPython(argv,user_ns=user_ns,
72 user_global_ns=user_global_ns,
---> 73 debug=debug,shell_class=shell_class)
global that = undefined
global gets = undefined
global prepended = undefined
global to = undefined
global all = undefined
global calls = undefined
global so = undefined
global header = undefined
global used = undefined
74
75 def mainloop(self,sys_exit=0,banner=None):
76 self.IP.mainloop(banner)
77 if sys_exit:
78 sys.exit()
79
80
-----------------------------------------------------------------------------
81 def kill_embedded(self,parameter_s=''):
82 """%kill_embedded : deactivate for good the current
embedded IPython.
83
84 This function (after asking for confirmation) sets an
internal flag so that
85 an embedded IPython will never activate again. This is useful
to
86 permanently disable a shell that is being called inside a
loop: once you've
87 figured out what you needed from it, you may then kill it
and the program
88 will then continue to run without the interactive shell
interfering again.
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython
\ipmaker.pyc in
make_IPython(argv=[r'c:\Python25\Scripts\ipython-
script.py', '-i'], user_ns=None,
user_global_ns=None, debug=1,
rc_override=None, shell_class=,
embedded=False, kw={})
755 IP_rc.banner = 0
756 if IP_rc.banner:
757 BANN_P = IP.BANNER_PARTS
758 else:
759 BANN_P = []
760
761 if IP_rc.profile: BANN_P.append('IPython profile: %s\n'
% IP_rc.profile)
762
763 # add message log (possibly empty)
764 if msg.summary: BANN_P.append(msg.summary)
765 # Final banner is a string
766 IP.BANNER = '\n'.join(BANN_P)
767
768 # Finalize the IPython instance. This assumes the rc
structure is fully
769 # in place.
--> 770 IP.post_config_initialization()
771
772 return IP
773 #************** end of file
774
775
776
777
778
779
780
781
782
783
784
785
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\iplib.pyc
in
post_config_initialization(self=)
847 This is called after the configuration files have been
processed to
848 'finalize' the initialization."""
849
850 rc = self.rc
851
852 # Object inspector
853 self.inspector = OInspect.Inspector(OInspect.InspectColors,
854 PyColorize.ANSICodeColors,
855 'NoColor',
856 rc.object_info_string_level)
857
858 self.rl_next_input = None
859 self.rl_do_indent = False
860 # Load readline proper
861 if rc.readline:
--> 862 self.init_readline()
863
864 # local shortcut, this is used a LOT
865 self.log = self.logger.log
866
867 # Initialize cache, set in/out prompts and printing system
868 self.outputcache = CachedOutput(self,
869 rc.cache_size,
870 rc.pprint,
871 input_sep = rc.separate_in,
872 output_sep = rc.separate_out,
873 output_sep2 = rc.separate_out2,
874 ps1 = rc.prompt_in1,
875 ps2 = rc.prompt_in2,
876 ps_out = rc.prompt_out,
877 pad_left = rc.prompts_pad_left)
C:\Python25\lib\site-packages\ipython-0.10-py2.5.egg\IPython\iplib.pyc
in
init_readline(self=) 1476
if not readline.uses_libedit: 1477
for rlcommand in
self.rc.readline_parse_and_bind:
1478 #print
"loading rl:",rlcommand # dbg 1479
readline.parse_and_bind(rlcommand)
1480 1481 # Remove some
chars from the delimiters list. If we
encounter 1482 #
unicode chars, discard them. 1483
delims =
readline.get_completer_delims().encode("ascii",
"ignore") 1484 delims =
delims.translate(string._idmap,
1485 self.rc.readline_remove_delims)
1486
readline.set_completer_delims(delims)
1487 # otherwise we end up
with a monster history after a while:
1488
readline.set_history_length(1000)
1489 try: 1490
print '* Reading readline history' # dbg
-> 1491 readline.read_history_file(self.histfile)
1492 except IOError:
1493 pass # It
doesn't exist yet. 1494 1495
atexit.register(self.atexit_operations)
1496 del atexit 1497
1498 # Configure auto-indent
for all platforms 1499
self.set_autoindent(self.rc.autoindent)
1500 1501 def
ask_yes_no(self,prompt,default=True):
1502 if self.rc.quiet: 1503
return True 1504 return
ask_yes_no(prompt,default) 1505
1506 def
new_main_mod(self,ns=None):
C:\Python25\lib\site-packages\pyreadline\rlmain.pyc
in
read_history_file(self=,
filename=u'C:\Home\_ipython\history')
168
169 def set_history_length(self, length):
170 '''Set the number of lines to save in the history file.
171
172 write_history_file() uses this value to truncate the
history file
173 when saving. Negative values imply unlimited history file
size.
174 '''
175 self._history.set_history_length(length)
176
177 def clear_history(self):
178 '''Clear readline history'''
179 self._history.clear_history()
180
181 def read_history_file(self,
filename=None):
182 '''Load a readline history file. The default filename is
~/.history.'''
--> 183 self._history.read_history_file(filename)
184
185 def write_history_file(self,
filename=None):
186 '''Save a readline history file. The default filename is
~/.history.'''
187 self._history.write_history_file(filename)
188
189 #Completer functions
190
191 def set_completer(self, function=None):
192 '''Set or remove the completer function.
193
194 If function is specified, it will be used as the new
completer
195 function; if omitted or None, any completer function
already
196 installed is removed. The completer function is called as
197 function(text, state), for state in 0, 1, 2, ..., until it
returns a
198 non-string value. It should return the next possible
completion
C:\Python25\lib\site-packages\pyreadline\lineeditor\history.pyc
in
read_history_file(self=,
filename=u'C:\Home\_ipython\history')
55
56 history_length=property(get_history_length,set_history_length)
57 history_cursor=property(get_history_cursor,set_history_cursor)
58
59 def clear_history(self):
60 '''Clear readline history.'''
61 self.history[:] = []
62 self.history_cursor = 0
63
64 def read_history_file(self,
filename=None):
65 '''Load a readline history file.'''
66 if filename is None:
67 filename=self.history_filename
68 try:
69 for line in open(filename, 'r'):
---> 70 self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip())))
global n = undefined
global Xd = undefined
global S = undefined
global NR = undefined
global i = undefined
global R2 = undefined
global R = undefined
global t = undefined
global history_search_forwardt = undefined
global history_search_backwardt = undefined
global joinR2 = undefined
global maxR = undefined
global mint = undefined
global IndexError = undefined
global RX = undefined
global partialt = undefined
global hcstartt = undefined
global hct = undefined
global ht = undefined
global result = undefined
global s = undefined
global C = undefined
global Python25 = undefined
global lib = undefined
global site = undefined
global packages = undefined
global pyreadline =
global lineeditor = undefined
global history.pyt = undefined
global search = undefined
global I = undefined
global c = undefined
global d = undefined
global Search = undefined
global forward = undefined
global through = undefined
global the = undefined
global history = undefined
global string =
global of = undefined
global characters = undefined
global between = undefined
global start = undefined
global current = undefined
line = 'import sys\n'
global point.This = undefined
global a = undefined
global non = undefined
global incremental = undefined
global search.By = undefined
global default = undefined
global this = undefined
global command = undefined
global unbound.i = undefined
global Rj = undefined
global Re = undefined
global q = undefined
global history.pyR = undefined
global backward = undefined
global Rk = undefined
global history.pyR = undefined
global N = undefined
global propertyR = undefined
global R4 = undefined
global R5 = undefined
global R7 = undefined
global R8 = undefined
global RC = undefined
global RD = undefined
global R_ = undefined
global s.t = undefined
Press enter to exit: global
_main_t = undefined
global aaaat = undefined
global aabat = undefined
global aacat = undefined
global akcat = undefined
global bbbt = undefined
global ako = undefined
global ret = undefined
global operatorRS = undefined
global sysR = undefined
global pyreadline.unicode_helperR = undefined
global modulesR = undefined
global exceptionst = undefined
global ExceptionR = undefined
global pyreadline.loggerR = undefined
global FalseR9 = undefined
global objectR = undefined
global RLR = undefined
global history.pys = undefined
global module = undefined
71 except IOError:
72 self.history = []
73 self.history_cursor = 0
74
75 def write_history_file(self,
filename=None):
76 '''Save a readline history file.'''
77 if filename is None:
78 filename=self.history_filename
79 fp = open(filename, 'wb')
80 for line in self.history[-self.history_length:]:
81 fp.write(ensure_str(line.get_line_text()))
82 fp.write('\n')
83 fp.close()
84
85
C:\Python25\lib\site-packages\pyreadline\unicode_helper.pyc
in ensure_unicode(text='import sys')
5 # Distributed under the terms of the BSD License. The full license
is in
6 # the file COPYING, distributed as part of this software.
7
*******************************************
8 import sys
9
10 try:
11 pyreadline_codepage=sys.stdout.encoding
12 except AttributeError: #This error occurs when pdb imports readline and doctest has replaced
13 #stdout with stdout collector
14 pyreadline_codepage="ascii" #assume
ascii codepage
15
16
17 def ensure_unicode(text):
18 """helper to ensure that text passed to WriteConsoleW is
unicode"""
19 if isinstance(text, str):
---> 20 return text.decode(pyreadline_codepage,
"replace")
21 return text
22
23 def ensure_str(text):
24 """Convert unicode to str using pyreadline_codepage"""
25 if isinstance(text, unicode):
26 return text.encode(pyreadline_codepage,
"replace")
27 return text
28
29
30
31
32
33
34
35
TypeError: decode() argument 1 must be
string, not None
Oops, IPython crashed. We do our best
to make it stable, but...
A crash report was automatically
generated with the following
information:
- A verbatim copy of the crash traceback.
- A copy of your input history during this session.
- Data on your current IPython configuration.
It was left in the file named:
'C:\Home_ipython\IPython_crash_report.txt'
If you can email this file to the
developers, the information in it will
help them in understanding and
correcting the problem.
You can mail it to: Fernando Perez at
fperez....@gmail.com with the subject
'IPython Crash Report'.
If you want to do it now, the
following command will work (under
Unix): mail -s 'IPython Crash Report'
fperez....@gmail.com <
C:\Home_ipython
\IPython_crash_report.txt
To ensure accurate tracking of this
issue, please file a report about it
at:
https://bugs.launchpad.net/ipython/+filebug
| [
"Installing pyreadline should help.\n"
] | [
3
] | [] | [] | [
"emacs",
"ipython",
"python",
"windows"
] | stackoverflow_0003867236_emacs_ipython_python_windows.txt |
Q:
Pylons + Mako -- Access POST data from templates
How can I access my request.params post data from my Mako template with Pylons?
A:
Same as in the controller.
${request.params['my_param']}
or preferably:
${request.params.get('my_param', '')}
| Pylons + Mako -- Access POST data from templates | How can I access my request.params post data from my Mako template with Pylons?
| [
"Same as in the controller.\n${request.params['my_param']}\n\nor preferably:\n${request.params.get('my_param', '')}\n\n"
] | [
2
] | [] | [] | [
"mako",
"pylons",
"python",
"templates"
] | stackoverflow_0003867426_mako_pylons_python_templates.txt |
Q:
Is it possible to generate variables from a list?
Is it possible to generate variables on the fly from a list?
In my program I am using the following instruction:
for i in re.findall(r"...(?=-)", str(vr_ctrs.getNodeNames())):
tmp_obj = vr_ctrs.getChild(i+"-GEODE")
TMP.append([tmp_obj.getPosition(viz.ABS_GLOBAL)[0],
tmp_obj.getPosition(viz.ABS_GLOBAL)[1],
tmp_obj.getPosition(viz.ABS_GLOBAL)[2]])
which builds me a list on TMP. Would be possible to generate a new variable for each one of the elements that I am appending to TMP?
Thanks
A:
I would suggest that instead of creating variables, that you capture these entries in a dict, using what you would have used as the variable name for the dict keys. Then you can easily navigate through the parsed data by accessing dict.keys(), and you wont have to sort out your variables from other local or global variables. Also, if you happen to parse something that accidentally collides with a Python keyword (like 'for', for example), then using that as a dict key will still work, while using it as a variable or attribute name is not going to work.
A:
The global variables are in a dictionary that you can get by calling the globals() function.
globals()["foo"] = 17
foo # => 17
But you should probably refactor your code to use objects, and then use setattr() instead.
| Is it possible to generate variables from a list? | Is it possible to generate variables on the fly from a list?
In my program I am using the following instruction:
for i in re.findall(r"...(?=-)", str(vr_ctrs.getNodeNames())):
tmp_obj = vr_ctrs.getChild(i+"-GEODE")
TMP.append([tmp_obj.getPosition(viz.ABS_GLOBAL)[0],
tmp_obj.getPosition(viz.ABS_GLOBAL)[1],
tmp_obj.getPosition(viz.ABS_GLOBAL)[2]])
which builds me a list on TMP. Would be possible to generate a new variable for each one of the elements that I am appending to TMP?
Thanks
| [
"I would suggest that instead of creating variables, that you capture these entries in a dict, using what you would have used as the variable name for the dict keys. Then you can easily navigate through the parsed data by accessing dict.keys(), and you wont have to sort out your variables from other local or globa... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003868191_python.txt |
Q:
Setuptools : how to use the setup() function within a script (no setup specific command line argument)
I'm writing a tool to automatically generate .egg files from python projects.
The tool basically discovers some properties to guess the setup options (such as version number etc).
Now I would like to call the setup() function, with the context bdist_egg.
I do as such :
if __name__ == '__main__'
project_dir = _get_dir(sys.argv)
os.chdir(project_dir)
config = _guess_configuration(project_dir) # returns a dict
sys.argv = ['', 'bdist_egg']
setup(**config)
And then I can call my script
python make_egg.py /path/to/project
What I would like is to skip the sys.argv = ['', 'bdist_egg'] part. Is there a way to have the setup command passed to the setup function?
Thanks
A:
setup(script_args=['bdist_egg'], **config)
| Setuptools : how to use the setup() function within a script (no setup specific command line argument) | I'm writing a tool to automatically generate .egg files from python projects.
The tool basically discovers some properties to guess the setup options (such as version number etc).
Now I would like to call the setup() function, with the context bdist_egg.
I do as such :
if __name__ == '__main__'
project_dir = _get_dir(sys.argv)
os.chdir(project_dir)
config = _guess_configuration(project_dir) # returns a dict
sys.argv = ['', 'bdist_egg']
setup(**config)
And then I can call my script
python make_egg.py /path/to/project
What I would like is to skip the sys.argv = ['', 'bdist_egg'] part. Is there a way to have the setup command passed to the setup function?
Thanks
| [
"setup(script_args=['bdist_egg'], **config)\n"
] | [
0
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0003863082_python_setuptools.txt |
Q:
How do I replace the current working MySQL database with a .sql file?
I'm trying to restore the current working database to the data stored in a .sql file from within Django. Whats the best way to do this? Does django have an good way to do this or do I need to grab the connection string from the settings.py file and send command line mysql commands to do this?
Thanks for your help.
A:
Django doesn't have any built-in commands for loading SQL fixtures. If you happen to have it in some sort of serialized file, like JSON, you can use the loaddata command of django-admin or manage.py.
You can read about it here.
A:
You can't import sql dumps through django; import it through mysql directly, if you run mysql locally you can find various graphical mysql clients that can help you with doing so; if you need to do it remotely, find out if your server has any web interfaces for that installed!
| How do I replace the current working MySQL database with a .sql file? | I'm trying to restore the current working database to the data stored in a .sql file from within Django. Whats the best way to do this? Does django have an good way to do this or do I need to grab the connection string from the settings.py file and send command line mysql commands to do this?
Thanks for your help.
| [
"Django doesn't have any built-in commands for loading SQL fixtures. If you happen to have it in some sort of serialized file, like JSON, you can use the loaddata command of django-admin or manage.py.\nYou can read about it here.\n",
"You can't import sql dumps through django; import it through mysql directly, if... | [
1,
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003866989_django_mysql_python.txt |
Q:
Creating User Profiles In Python
I'm making a small python game with pygame. I'd like to be able to have multiple profiles with different stats, upgrades, etc. My biggest problem is storing this information persistently. I've already thought about MySql but I don't know how I could connect to it and I would prefer some way to be able to distribute it without requiring a database. Any suggestions? Many thanks.
A:
You can use the sqlite3 module which comes with python or you could use the shelve module
You can use the shelve module as an object database and just save the user classes directly.
The sqlite3 module will let you store a relational database in a file. It's used by firefox for example.
A:
sqllite3 will probably be the easiest way forward. It's lightweight and doesn't need to be installed by users. To access it though, consider using an ORM (Object Relational Mapper) to simplify things. SQL Alchemy and Storm are both good tools.
An ORM deals with the nitty-gritty of writing SQL code and so forth. If you want to hop between databases, it's often just a matter of changing a single line of code.
| Creating User Profiles In Python | I'm making a small python game with pygame. I'd like to be able to have multiple profiles with different stats, upgrades, etc. My biggest problem is storing this information persistently. I've already thought about MySql but I don't know how I could connect to it and I would prefer some way to be able to distribute it without requiring a database. Any suggestions? Many thanks.
| [
"You can use the sqlite3 module which comes with python or you could use the shelve module\nYou can use the shelve module as an object database and just save the user classes directly.\nThe sqlite3 module will let you store a relational database in a file. It's used by firefox for example.\n",
"sqllite3 will prob... | [
3,
2
] | [] | [] | [
"pygame",
"python",
"user_profile"
] | stackoverflow_0003868385_pygame_python_user_profile.txt |
Q:
Web.py template error: 'sum' does not exist
I use the built in 'sum' function in a web.py templator template and I get the following error:
global name 'sum' is not defined
Source code is below:
$if profs:
$for prof in profs:
$sum([1, 2, 3])
I can use 'sum' just fine at a Python REPL in the terminal.
What could be the issue?
Thanks,
Jacob
A:
Add the functions in a dict and pass as the globals argument to render:
render = web.template.render('templates/', globals={'sum': sum})
Then in your template you can just use it:
$def with (numbers)
<h1>Numbers add to $sum(numbers)</h1>
A:
Not all python code is available in template notation, try something like this:
$if profs:
$for prof in profs:
$code:
mysum = sum([1, 2, 3])
$mysum
| Web.py template error: 'sum' does not exist | I use the built in 'sum' function in a web.py templator template and I get the following error:
global name 'sum' is not defined
Source code is below:
$if profs:
$for prof in profs:
$sum([1, 2, 3])
I can use 'sum' just fine at a Python REPL in the terminal.
What could be the issue?
Thanks,
Jacob
| [
"Add the functions in a dict and pass as the globals argument to render:\nrender = web.template.render('templates/', globals={'sum': sum})\n\nThen in your template you can just use it:\n$def with (numbers)\n\n<h1>Numbers add to $sum(numbers)</h1>\n\n",
"Not all python code is available in template notation, try s... | [
4,
0
] | [] | [] | [
"python",
"web.py"
] | stackoverflow_0001741022_python_web.py.txt |
Q:
programmatically find and replace content dynamically in a string in python
i need to find and replace patterns in a string with a dynamically generated content.
lets say i want to find all strings within '' in the string and double the string.
a string like:
my 'cat' is 'white' should become my 'catcat' is 'whitewhite'
all matches could also appear twice in the string.
thank you
A:
Make use of the power of regular expressions. In this particular case:
import re
s = "my 'cat' is 'white'"
print re.sub("'([^']+)'", r"'\1\1'", s) # prints my 'catcat' is 'whitewhite'
\1 refers to the first group in the regex (called $1 in some other implementations).
A:
It's also pretty easy to do it without regex in your case:
s = "my 'cat' is 'white'".split("'")
# the parts between the ' are at the 1, 3, 5 .. index
print s[1::2]
# replace them with new elements
s[1::2] = [x+x for x in s[1::2]]
# join that stuff back together
print "'".join(s)
| programmatically find and replace content dynamically in a string in python | i need to find and replace patterns in a string with a dynamically generated content.
lets say i want to find all strings within '' in the string and double the string.
a string like:
my 'cat' is 'white' should become my 'catcat' is 'whitewhite'
all matches could also appear twice in the string.
thank you
| [
"Make use of the power of regular expressions. In this particular case:\nimport re\n\ns = \"my 'cat' is 'white'\"\n\nprint re.sub(\"'([^']+)'\", r\"'\\1\\1'\", s) # prints my 'catcat' is 'whitewhite'\n\n\\1 refers to the first group in the regex (called $1 in some other implementations).\n",
"It's also pretty eas... | [
7,
1
] | [] | [] | [
"python",
"replace"
] | stackoverflow_0003868330_python_replace.txt |
Q:
Grepping for Python processes
I'm running a script that executes either:
./ide.py
# or
python ./ide.py
After that I use pstree -p | grep ide.py to check, but I only found a Python process. If I have many Python scripts running, how can I distinguish them from each other?
A:
Use the -a switch:
pstree -p -a
to show process command line arguments.
A:
You need to run the pstree command with the "-a" switch to show command line arguments. Here's why:
All python scripts are run through the python interpreter... Even if you run them directly (i.e. ./ide.py).
| Grepping for Python processes | I'm running a script that executes either:
./ide.py
# or
python ./ide.py
After that I use pstree -p | grep ide.py to check, but I only found a Python process. If I have many Python scripts running, how can I distinguish them from each other?
| [
"Use the -a switch:\npstree -p -a\n\nto show process command line arguments.\n",
"You need to run the pstree command with the \"-a\" switch to show command line arguments. Here's why:\nAll python scripts are run through the python interpreter... Even if you run them directly (i.e. ./ide.py).\n"
] | [
2,
0
] | [] | [] | [
"pid",
"process",
"python"
] | stackoverflow_0003868792_pid_process_python.txt |
Q:
Omit iterator in list comprehension?
Is there a more elegant way to write the following piece of Python?
[foo() for i in range(10)]
I want to accumulate the results of foo() in a list, but I don't need the iterator i.
A:
One way to do this is to use _:
[foo() for _ in range(10)]
This means exactly the same thing, but by convention the use of _ indicates to the reader that the index isn't actually used for anything.
Presumably foo() returns something different every time you call it. If it doesn't, and it returns the same thing each time, then you can:
[foo()] * 10
to replicate the result of calling foo() once, 10 times into a list.
A:
map would be nice if foo() took an argument, but it doesn't. So instead, create a dummy lambda that takes an integer argument, but just calls foo():
map(lambda i:foo(), range(10))
If you are on Python 3.x, map returns an iterator instead of a list - just construct a list with it:
list(map(lambda i:foo(), range(10)))
| Omit iterator in list comprehension? | Is there a more elegant way to write the following piece of Python?
[foo() for i in range(10)]
I want to accumulate the results of foo() in a list, but I don't need the iterator i.
| [
"One way to do this is to use _:\n[foo() for _ in range(10)]\n\nThis means exactly the same thing, but by convention the use of _ indicates to the reader that the index isn't actually used for anything.\nPresumably foo() returns something different every time you call it. If it doesn't, and it returns the same thin... | [
5,
0
] | [
"By no means more elegant, but:\n[x() for x in [foo]*10]\n\nI think beyond that you have to go to Ruby ;)\n",
"map(lambda _ : foo(), range(10))\nalthough this trades your problem with a meaningless iterator i with a new meaningless argument to the lambda expression.\n"
] | [
-1,
-2
] | [
"list_comprehension",
"python"
] | stackoverflow_0003868752_list_comprehension_python.txt |
Q:
Google App Engine-Ajax refresh from datastore using python
I have an application(developed in python) that requires a refreshed view from the datastore after every 5 seconds. I have came out with an javascript function and handle the refresh using ajax.
Ajax function
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript"> var refreshId = setInterval(function() { $('#responsecontainer').fadeOut("slow").load('/refresh').fadeIn("slow"); }, 5000); </script>
After which, I have a set of div tags(responsecontainer) that enclosed the parameters returned from the server side for display.
<div id="responsecontainer">
{% for greeting in greetings %}
{% if greeting.author %}
<b>{{ greeting.author.nickname }}</b> wrote:
<a href="/sign?key={{ greeting.key.id }}&auth={{ greeting.author.nickname }}">Delete</a>
{% else %}
An anonymous person wrote:
{% endif %}
<blockquote>{{ greeting.content|escape }}</blockquote>
{% endfor %}
</div>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook" name="submitGuestBk"></div>
</form>
My server side code is to query the datastore and render the result back to the template file(index.html).
class RefreshPage(webapp.RequestHandler):
def get(self):
greetings_query = Greeting.all().order('-date')
greetings = greetings_query.fetch(10)
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'Login'
template_values = {
'greetings': greetings,
'url': url,
'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, {}))
However, when I run the application, the results got refreshed together with the html contents such as forms and tables. Together, I am seeing 2 forms after the index.html refreshed by itself every 5 seconds.
Can anybody guide me on the possible cause and solution?
A:
The call to load('/refresh') replaces the contents of the responsecontainer div with the loaded HTML.
You therefore need the RefreshPage handler to just return that HTML, and not the whole page. For example, it should use a template which just contains this:
{% for greeting in greetings %}
{% if greeting.author %}
<b>{{ greeting.author.nickname }}</b> wrote:
<a href="/sign?key={{ greeting.key.id }}&auth={{ greeting.author.nickname }}">Delete</a>
{% else %}
An anonymous person wrote:
{% endif %}
<blockquote>{{ greeting.content|escape }}</blockquote>
{% endfor %}
To avoid duplicating that content in both templates, you could potentially make your main template include this sub-template inside the div, for example:
<div id="responsecontainer">
{% include "sub_template.html" %}
</div>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook" name="submitGuestBk"></div>
</form>
| Google App Engine-Ajax refresh from datastore using python | I have an application(developed in python) that requires a refreshed view from the datastore after every 5 seconds. I have came out with an javascript function and handle the refresh using ajax.
Ajax function
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript"> var refreshId = setInterval(function() { $('#responsecontainer').fadeOut("slow").load('/refresh').fadeIn("slow"); }, 5000); </script>
After which, I have a set of div tags(responsecontainer) that enclosed the parameters returned from the server side for display.
<div id="responsecontainer">
{% for greeting in greetings %}
{% if greeting.author %}
<b>{{ greeting.author.nickname }}</b> wrote:
<a href="/sign?key={{ greeting.key.id }}&auth={{ greeting.author.nickname }}">Delete</a>
{% else %}
An anonymous person wrote:
{% endif %}
<blockquote>{{ greeting.content|escape }}</blockquote>
{% endfor %}
</div>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook" name="submitGuestBk"></div>
</form>
My server side code is to query the datastore and render the result back to the template file(index.html).
class RefreshPage(webapp.RequestHandler):
def get(self):
greetings_query = Greeting.all().order('-date')
greetings = greetings_query.fetch(10)
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'Login'
template_values = {
'greetings': greetings,
'url': url,
'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, {}))
However, when I run the application, the results got refreshed together with the html contents such as forms and tables. Together, I am seeing 2 forms after the index.html refreshed by itself every 5 seconds.
Can anybody guide me on the possible cause and solution?
| [
"The call to load('/refresh') replaces the contents of the responsecontainer div with the loaded HTML.\nYou therefore need the RefreshPage handler to just return that HTML, and not the whole page. For example, it should use a template which just contains this:\n{% for greeting in greetings %} \n {% if greeting.aut... | [
8
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003868710_google_app_engine_google_cloud_datastore_python.txt |
Q:
Sort by 2 fields? is there any hacks or with index.yaml? or geoPT?
q = WorldObject.all()
# define boundaries
# left
q.filter('x >=', x)
# right
q.filter('x <', x + width)
# top
q.filter('y >=', y)
# bottom
q.filter('y <', y + height)
#q.filter('world', world_key)
wobjects = q.fetch(1000)
I got an error saying I can't use multiple sorts
q = WorldObject.all()
q.filter('xy >=', db.GeoPt(1, 1))
q.filter('xy <', db.GeoPt(4, 4))
wobjects = q.fetch(1000)
I've found this http://www.spatialdatabox.com/ it might be interesting as it uses the Amazon EC3 for retriving geo data.
this query gives me wrong world objects: with lat=9 why? if i limit between 1 and 4?
thanks
Blockquote
A:
google's datastore indexes are sequential. furthermore, the datastore refuses to satisfy range queries that require more than one index. You can either implement a GiS index on top of the datastore (hard) or just do the range query on one axis and exclude out of range results in your application code (easy).
So if you want to go the hard way, you can get that using geohash
Example of the easy way:
myquery = MyModel.all()
myquery.filter("x >=" x)
myquery.filter("x <" x+delta_x)
resultset = [result for result in myquery.fetch(1000) if y <= result.y < y+delta_y]
A:
App Engine does not currently support the type of querying you are trying to do. Although they have mentioned that a solution is in the works.
But Google does have a nice walk through on how to build something like what you are asking about. Also see one of Nick Johnson's blog posts for some interesting discussion on the general topic.
A:
I got to work it in some way, thanks to GeoModel.
What do you think? it might work on large scale?
I would like to know how many queries it does under the hood if possible. thanks for all your help:
def get_world_objects_in_area(input):
try:
x = input.x
y = input.y
width = input.w
height = input.h
world_key = input.k
except:
return False
# boundaries
top = to_map_unit(y)
bottom = to_map_unit(y-height) # this is "-" because in flash the vertical axis is inverted
left = to_map_unit(x)
right = to_map_unit(x+width)
bounding_box = geo.geotypes.Box(top, right, bottom, left)
query = WorldObject.all()
query.filter('world', world_key)
r = WorldObject.bounding_box_fetch(query,
bounding_box,
max_results=1000)
return r
def to_map_unit(n):
if n is not 0:
divide_by = 1000000000000
r = Decimal(n) / Decimal(divide_by)
return float(r)
else:
return 0
| Sort by 2 fields? is there any hacks or with index.yaml? or geoPT? | q = WorldObject.all()
# define boundaries
# left
q.filter('x >=', x)
# right
q.filter('x <', x + width)
# top
q.filter('y >=', y)
# bottom
q.filter('y <', y + height)
#q.filter('world', world_key)
wobjects = q.fetch(1000)
I got an error saying I can't use multiple sorts
q = WorldObject.all()
q.filter('xy >=', db.GeoPt(1, 1))
q.filter('xy <', db.GeoPt(4, 4))
wobjects = q.fetch(1000)
I've found this http://www.spatialdatabox.com/ it might be interesting as it uses the Amazon EC3 for retriving geo data.
this query gives me wrong world objects: with lat=9 why? if i limit between 1 and 4?
thanks
Blockquote
| [
"google's datastore indexes are sequential. furthermore, the datastore refuses to satisfy range queries that require more than one index. You can either implement a GiS index on top of the datastore (hard) or just do the range query on one axis and exclude out of range results in your application code (easy).\nSo... | [
2,
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003852532_google_app_engine_python.txt |
Q:
Passing variables between modules
I'm wonder why this simple code doesn't work.
In main.py I have
def foo():
HTTPHelper.setHost("foo")
host = HTTPHelper.host()
and in HTTPHelper.py:
_host = None
def setHost(host):
_host = host
def host():
return _host
But when I step through foo() host becomes NoneType, even though I set it on the line before. Very confused...
A:
Glenn's answer will fix your immediate issue from within a module, but for the sake of giving a man a fishing pole rather than a fish:
Short Description of the Scoping Rules?
You'd do well reading on scopes and Python's LEGB rule.
Scope and domain of existence concepts also apply to programming and analysis in general, and will be worth the time spent understanding the concepts.
It's also worth noting that if you're treating such things as objects (and what you write makes it seem like you intend to), you should be writing a class and set its attributes, and not global variables that you handle after a module import.
A:
def setHost(host):
global _host
_host = host
| Passing variables between modules | I'm wonder why this simple code doesn't work.
In main.py I have
def foo():
HTTPHelper.setHost("foo")
host = HTTPHelper.host()
and in HTTPHelper.py:
_host = None
def setHost(host):
_host = host
def host():
return _host
But when I step through foo() host becomes NoneType, even though I set it on the line before. Very confused...
| [
"Glenn's answer will fix your immediate issue from within a module, but for the sake of giving a man a fishing pole rather than a fish:\nShort Description of the Scoping Rules?\nYou'd do well reading on scopes and Python's LEGB rule.\nScope and domain of existence concepts also apply to programming and analysis in ... | [
9,
5
] | [] | [] | [
"python"
] | stackoverflow_0003868928_python.txt |
Q:
Convert Python string to its ASCII representants
How do I convert a string in Python to its ASCII hex representants?
Example: I want to result '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' in 001bd47da4f3.
A:
>>> text = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.rstrip('\0')
>>> print "".join("%02x" % ord(c) for c in text)
001bd47da4f3
As per martineau's comment, here is the Python 3 way:
>>> "".join(format(ord(c),"02x") for c in text)
A:
With python 2.x you can encode a string to it's hex representation. It will not work with python3.x
>>> print '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.encode("hex")
'001bd47da4f300000000000000000000'
It's not entirely clear if you have a literal string containing the escapes (so basically r'\x00\x1b' and so on) or not. Also, it's unclear why you don't expect the trailing zeroes, but you can remove those before the encode using .rstrip("\x00")
A:
Alternative:
[Python 2.7]
>>> data = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> import binascii
>>> binascii.b2a_hex(data.rstrip('\x00'))
'001bd47da4f3'
>>>
[Python 3.1.2]
>>> data = b'\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> import binascii
>>> binascii.b2a_hex(data.rstrip(b'\x00'))
b'001bd47da4f3'
>>>
A:
Here's another answer that ought to work with all Python versions from 3.x all the way back to 2.0 (min version according to pyqver). Despite that, because it's based on a simple table (not dict) lookup, it should also be relatively quick.
A little one-time set-up is required, but is very simple and avoids using the any of the many enhancements that have were added (or removed) along the way in a quest for version independence.
numerals = "0123456789abcdef"
hexadecimal = [i+j for i in numerals for j in numerals]
text = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
print ''.join([hexadecimal[ord(c)] for c in text.rstrip('\0')])
# 001bd47da4f3
| Convert Python string to its ASCII representants | How do I convert a string in Python to its ASCII hex representants?
Example: I want to result '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' in 001bd47da4f3.
| [
">>> text = '\\x00\\x1b\\xd4}\\xa4\\xf3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'.rstrip('\\0')\n>>> print \"\".join(\"%02x\" % ord(c) for c in text)\n001bd47da4f3\n\nAs per martineau's comment, here is the Python 3 way:\n>>> \"\".join(format(ord(c),\"02x\") for c in text)\n\n",
"With python 2.x you can ... | [
6,
5,
4,
2
] | [
"binascii.hexlify():\nimport binascii\n\nbyte_string = '\\x00\\x1b\\xd4}\\xa4\\xf3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \nprint binascii.hexlify(byte_string.rstrip('\\x00'))\n\n# -> 001bd47da4f3\n\nSee @John Machin's answer.\n"
] | [
-4
] | [
"python"
] | stackoverflow_0003850531_python.txt |
Q:
SQL templating engine to mix SQL with dynamic language? (similar to Ruby's erb)
Has anyone comes across a SQL templating engine which allows one to mix SQL with a dynamic language like Ruby or Python?
I'm looking for something similar to Ruby erb templates. For example, in Ruby on Rails you can have various templates for a view:
customers.html.erb (html + ruby)
customers.js.erb (javascript + ruby)
Though I want something like:
customers.sql.erb
The output could be a text string result of the ad-hoc SQL mixed with Ruby code. Or even, if it's Python-based that's fine too.
A:
Well, I found out that Ruby's erb works just fine for a SQL template. I was able to use it very easily in my Rails 3 project.
I also found that Python has a templating engine, Cheetah, which can do the same thing.
References
An Introduction to ERB Templating
Class: ERB (RDoc Documentation)
Cheetah - The Python-Powered Template Engine
Using Cheetah templates to make multiples outputs
| SQL templating engine to mix SQL with dynamic language? (similar to Ruby's erb) | Has anyone comes across a SQL templating engine which allows one to mix SQL with a dynamic language like Ruby or Python?
I'm looking for something similar to Ruby erb templates. For example, in Ruby on Rails you can have various templates for a view:
customers.html.erb (html + ruby)
customers.js.erb (javascript + ruby)
Though I want something like:
customers.sql.erb
The output could be a text string result of the ad-hoc SQL mixed with Ruby code. Or even, if it's Python-based that's fine too.
| [
"Well, I found out that Ruby's erb works just fine for a SQL template. I was able to use it very easily in my Rails 3 project.\nI also found that Python has a templating engine, Cheetah, which can do the same thing.\nReferences\n\nAn Introduction to ERB Templating\n\nClass: ERB (RDoc Documentation)\n\nCheetah - The... | [
0
] | [] | [] | [
"erb",
"python",
"ruby_on_rails",
"sql",
"templates"
] | stackoverflow_0003866421_erb_python_ruby_on_rails_sql_templates.txt |
Q:
Python: Overwriting a directory with another directory containing the same files
I'm trying to overwrite a directory with another directory that contains the same files.
I've tried using distutils.dir_util.copy_tree(src, dst) but it tried to make a directory for dst instead.
The objective is to overwrite the directory and its contents silently.
Is there any other way to do so?
A:
Edit: This rigamarole is apparently not necessary; see the OP's answer for the reason.
You'll probably want to first rename the destination directory to something else. If that goes okay, then copy the source directory to the original name of the destination directory. Then, if that worked, delete the destination directory from its new location.
You should first create a temporary directory into which to move the destination directory using tempfile.mkdtemp.
A:
oops... Turns out that distutils.dir_util.copy_tree(src, dst) works.
It's just that I got my directory path from environment variables and '\n' was stuck at the back of my path.
Adding in a .strip() to my path variable solved the problem.
| Python: Overwriting a directory with another directory containing the same files | I'm trying to overwrite a directory with another directory that contains the same files.
I've tried using distutils.dir_util.copy_tree(src, dst) but it tried to make a directory for dst instead.
The objective is to overwrite the directory and its contents silently.
Is there any other way to do so?
| [
"Edit: This rigamarole is apparently not necessary; see the OP's answer for the reason.\nYou'll probably want to first rename the destination directory to something else. If that goes okay, then copy the source directory to the original name of the destination directory. Then, if that worked, delete the destinati... | [
1,
0
] | [] | [] | [
"copy",
"overwrite",
"python",
"windows"
] | stackoverflow_0003869280_copy_overwrite_python_windows.txt |
Q:
Python: 2.6 and 3.1 string matching inconsistencies
I wrote my module in Python 3.1.2, but now I have to validate it for 2.6.4.
I'm not going to post all my code since it may cause confusion.
Brief explanation:
I'm writing a XML parser (my first interaction with XML) that creates objects from the XML file. There are a lot of objects, so I have a 'unit test' that manually scans the XML and tries to find a matching object. It will print out anything that doesn't have a match.
I open the XML file and use a simple 'for' loop to read line-by-line through the file. If I match a regular expression for an 'application' (XML has different 'application' nodes), then I add it to my dictionary, d, as the key. I perform a lxml.etree.xpath() query on the title and store it as the value.
After I go through the whole thing, I iterate through my dictionary, d, and try to match the key to my value (I have to use the get() method from my 'application' class). Any time a mismatch is found, I print the key and title.
Python 3.1.2 has all matching items in the dictionary, so nothing is printed. In 2.6.4, every single value is printed (~600) in all. I can't figure out why my string comparisons aren't working.
Without further ado, here's the relevant code:
for i in d:
if i[1:-2] != d[i].get('id'):
print('X%sX Y%sY' % (i[1:-3], d[i].get('id')))
I slice the strings because the strings are different. Where the key would be "9626-2008olympics_Prod-SH"\n the value would be 9626-2008olympics_Prod-SH, so I have to cut the quotes and newline. I also added the Xs and Ys to the print statements to make sure that there wasn't any kind of whitespace issues.
Here is an example line of output:
X9626-2008olympics_Prod-SHX Y9626-2008olympics_Prod-SHY
Remember to ignore the Xs and Ys. Those strings are identical. I don't understand why Python2 can't match them.
Edit:
So the problem seems to be the way that I am slicing.
In Python3,
if i[1:-2] != d[i].get('id'):
this comparison works fine.
In Python2,
if i[1:-3] != d[i].get('id'):
I have to change the offset by one.
Why would strings need different offsets? The only possible thing that I can think of is that Python2 treats a newline as two characters (i.e. '\' + 'n').
Edit 2:
Updated with requested repr() information.
I added a small amount of code to produce the repr() info from the "2008olympics" exmpale above. I have not done any slicing. It actually looks like it might not be a unicode issue. There is now a "\r" character.
Python2:
'"9626-2008olympics_Prod-SH"\r\n'
'9626-2008olympics_Prod-SH'
Python3:
'"9626-2008olympics_Prod-SH"\n'
'9626-2008olympics_Prod-SH'
Looks like this file was created/modified on Windows. Is there a way in Python2 to automatically suppress '\r'?
A:
You are printing i[1:-3] but comparing i[1:-2] in the loop.
Very Important Question
Why are you writing code to parse XML when lxml will do all that for you? The point of unit tests is to test your code, not to ensure that the libraries you are using work!
A:
repr() and %r format are your friends ... they show you (for basic types like str/unicode/bytes) exactly what you've got, including type.
Instead of
print('X%sX Y%sY' % (i[1:-3], d[i].get('id')))
do
print('%r %r' % (i, d[i].get('id')))
Note leaving off the [1:-3] so that you can see what is in i before you slice it.
Update after comment "You are perfectly right about comparing the wrong slice. However, once I change it, python2.6 works, but python3 has the problem now (i.e. it doesn't match any objects)":
How are you opening the file (two answers please, for Python 2 and 3). Are you running on Windows? Have you tried getting the repr() as I suggested?
Update after actual input finally provided by OP:
If, as it appears, your input file was created on Windows (lines are separated by "\r\n"), you can read Windows and *x text files portably by using the "universal newlines" option ... open('datafile.txt', 'rU') on Python2 -- read this. Universal newlines mode is the default in Python3. Note that the Python3 docs say that you can use 'rU' also in Python3; this would save you having to test which Python version you are using.
A:
Russell Borogrove is right.
Python 3 defaults to unicode, and the newline character is correctly interpreted as one character. That's why my offset of [1:-2] worked in 3 because I needed to eliminate three characters: ", ", and \n.
In Python 2, the newline is being interpreted as two characters, meaning I have to eliminate four characters and use [1:-3].
I just added a manual check for the Python major version.
Here is the fixed code:
for i in d:
# The keys in D contain quotes and a newline which need
# to be removed. In v3, newline = 1 char and in v2,
# newline = 2 char.
if sys.version_info[0] < 3:
if i[1:-3] != d[i].get('id'):
print('%s %s' % (i[1:-3], d[i].get('id')))
else:
if i[1:-2] != d[i].get('id'):
print('%s %s' % (i[1:-2], d[i].get('id')))
Thanks for the responses everyone! I appreciate your help.
A:
I don't understand what you're doing exactly, but would you try using strip() instead of slicing and see whether it helps?
for i in d:
stripped = i.strip()
if stripped != d[i].get('id'):
print('X%sX Y%sY' % (stripped, d[i].get('id')))
| Python: 2.6 and 3.1 string matching inconsistencies | I wrote my module in Python 3.1.2, but now I have to validate it for 2.6.4.
I'm not going to post all my code since it may cause confusion.
Brief explanation:
I'm writing a XML parser (my first interaction with XML) that creates objects from the XML file. There are a lot of objects, so I have a 'unit test' that manually scans the XML and tries to find a matching object. It will print out anything that doesn't have a match.
I open the XML file and use a simple 'for' loop to read line-by-line through the file. If I match a regular expression for an 'application' (XML has different 'application' nodes), then I add it to my dictionary, d, as the key. I perform a lxml.etree.xpath() query on the title and store it as the value.
After I go through the whole thing, I iterate through my dictionary, d, and try to match the key to my value (I have to use the get() method from my 'application' class). Any time a mismatch is found, I print the key and title.
Python 3.1.2 has all matching items in the dictionary, so nothing is printed. In 2.6.4, every single value is printed (~600) in all. I can't figure out why my string comparisons aren't working.
Without further ado, here's the relevant code:
for i in d:
if i[1:-2] != d[i].get('id'):
print('X%sX Y%sY' % (i[1:-3], d[i].get('id')))
I slice the strings because the strings are different. Where the key would be "9626-2008olympics_Prod-SH"\n the value would be 9626-2008olympics_Prod-SH, so I have to cut the quotes and newline. I also added the Xs and Ys to the print statements to make sure that there wasn't any kind of whitespace issues.
Here is an example line of output:
X9626-2008olympics_Prod-SHX Y9626-2008olympics_Prod-SHY
Remember to ignore the Xs and Ys. Those strings are identical. I don't understand why Python2 can't match them.
Edit:
So the problem seems to be the way that I am slicing.
In Python3,
if i[1:-2] != d[i].get('id'):
this comparison works fine.
In Python2,
if i[1:-3] != d[i].get('id'):
I have to change the offset by one.
Why would strings need different offsets? The only possible thing that I can think of is that Python2 treats a newline as two characters (i.e. '\' + 'n').
Edit 2:
Updated with requested repr() information.
I added a small amount of code to produce the repr() info from the "2008olympics" exmpale above. I have not done any slicing. It actually looks like it might not be a unicode issue. There is now a "\r" character.
Python2:
'"9626-2008olympics_Prod-SH"\r\n'
'9626-2008olympics_Prod-SH'
Python3:
'"9626-2008olympics_Prod-SH"\n'
'9626-2008olympics_Prod-SH'
Looks like this file was created/modified on Windows. Is there a way in Python2 to automatically suppress '\r'?
| [
"You are printing i[1:-3] but comparing i[1:-2] in the loop.\n\nVery Important Question\nWhy are you writing code to parse XML when lxml will do all that for you? The point of unit tests is to test your code, not to ensure that the libraries you are using work!\n",
"repr() and %r format are your friends ... they ... | [
3,
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003868006_python_string.txt |
Q:
How do I modify variables in the SocketServer server instance from within a RequestHandler handler instance in Python?
Here's the code in question:
class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer):
__slots__ = ("loaded")
class Handler(SocketServer.StreamRequestHandler):
def handle(self):
print self.server.loaded # Prints "False" at every call, why?
self.server.loaded = True
print self.server.loaded # Prints "True" at every call, obvious!
server = Server(('localhost', port), Handler)
server.loaded = False
while True:
server.handle_request()
Every time a new request comes in, the output I get is False followed by True. What I want is False followed by True the first time, and True followed by True henceforth.
Why aren't the modifications I made to the variable in the server instance persisting outside the scope of the handler's handle() function?
UPDATED:
So, I try using global variables to achieve what I want:
loaded = False
class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer):
pass
class Handler(SocketServer.StreamRequestHandler):
def handle(self):
global loaded
print loaded # Prints "False" at every call still, why?
loaded = True
print loaded # Prints "True" at every call, obvious!
def main():
server = Server(('localhost', 4444), Handler)
global loaded
loaded = False
while True:
server.handle_request()
if (__name__ == '__main__'):
main()
And it still doesn't work, i.e. produces the same output as before. Could anyone please tell me where I'm going wrong?
A:
Forking creates a new process, so you can't modify the server's variables in the original process. Try the ThreadingTCPServer instead:
import SocketServer
class Server(SocketServer.ThreadingTCPServer):
__slots__ = ("loaded")
class Handler(SocketServer.StreamRequestHandler):
def handle(self):
self.server.loaded = not self.server.loaded
print self.server.loaded # Alternates value at each new request now.
server = Server(('localhost',5000),Handler)
server.loaded = False
while True:
server.handle_request()
A:
Your problem is that SocketServer.ForkingMixin creates a new process for every request. Therefore, every time a new request comes in all your variables get reset to their default state. So essentially no matter what you assign to self.server.loaded it will get reset at the next request. This is also why globals won't work.
If you need a variable to persist between requests you'd best write that data somewhere more, er, persistent =). Essentially, it sounds like you're trying to solve the problem of keeping session variables. There's a million and one ways to do it and depending on your situation, one way might be more pertinent than another. I highly recommend looking at how other Python-based SocketServer applications do it.
Just do a quick google for similar code to yours: "filetype:py SocketServer ForkingMixIn" (one of the first results is CherryPy which I highly recommend looking at).
| How do I modify variables in the SocketServer server instance from within a RequestHandler handler instance in Python? | Here's the code in question:
class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer):
__slots__ = ("loaded")
class Handler(SocketServer.StreamRequestHandler):
def handle(self):
print self.server.loaded # Prints "False" at every call, why?
self.server.loaded = True
print self.server.loaded # Prints "True" at every call, obvious!
server = Server(('localhost', port), Handler)
server.loaded = False
while True:
server.handle_request()
Every time a new request comes in, the output I get is False followed by True. What I want is False followed by True the first time, and True followed by True henceforth.
Why aren't the modifications I made to the variable in the server instance persisting outside the scope of the handler's handle() function?
UPDATED:
So, I try using global variables to achieve what I want:
loaded = False
class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer):
pass
class Handler(SocketServer.StreamRequestHandler):
def handle(self):
global loaded
print loaded # Prints "False" at every call still, why?
loaded = True
print loaded # Prints "True" at every call, obvious!
def main():
server = Server(('localhost', 4444), Handler)
global loaded
loaded = False
while True:
server.handle_request()
if (__name__ == '__main__'):
main()
And it still doesn't work, i.e. produces the same output as before. Could anyone please tell me where I'm going wrong?
| [
"Forking creates a new process, so you can't modify the server's variables in the original process. Try the ThreadingTCPServer instead:\nimport SocketServer\n\nclass Server(SocketServer.ThreadingTCPServer):\n __slots__ = (\"loaded\")\n\nclass Handler(SocketServer.StreamRequestHandler):\n def handle(self):\n ... | [
4,
2
] | [] | [] | [
"python",
"python_2.7",
"sockets",
"socketserver"
] | stackoverflow_0003868132_python_python_2.7_sockets_socketserver.txt |
Q:
Python: I'm not allowed to raise exception. Are there other elegant python ways?
My work place has imposed a rules for no use of exception (catching is allowed). If I have code like this
def f1()
if bad_thing_happen():
raise Exception('bad stuff')
...
return something
I could change it to
def f1()
if bad_thing_happen():
return [-1, None]
...
return [0, something]
f1 caller would be like this
def f1_caller():
code, result = f1(param1)
if code < 0:
return code
actual_work1()
# call f1 again
code, result = f1(param2)
if code < 0:
return code
actual_work2()
...
Are there more elegant ways than this in Python ?
A:
Exceptions in python are not something to be avoided, and are often a straightforward way to solve problems. Additionally, an exception carries a great deal of information with it that can help quickly locate (via stack trace) and identify problems (via exception class or message).
Whoever has come up with this blanket policy was surely thinking of another language (perhaps C++?) where throwing exceptions is a more expensive operation (and will reduce performance if your code is executing on a 20 year old computer).
To answer your question: the alternative is to return an error code. This means that you are mixing function results with error handling, which raises (ha!) it's own problems. However, returning None is often a perfectly reasonable way to indicate function failure.
A:
Returning None is reasonably common and works well conceptually. If you are expecting a return value, and you get none, that is a good indication that something went wrong.
Another possible approach, if you are expecting to return a list (or dictionary, etc.) is to return an empty list or dict. This can easily be tested for using if, because an empty container evaluates to False in Python, and if you are going to iterate over it, you may not even need to check for it (depending on what you want to do if the function fails).
Of course, these approaches don't tell you why the function failed. So you could return an exception instance, such as return ValueError("invalid index"). Then you can test for particular exceptions (or Exceptions in general) using isinstance() and print them to get decent error messages. (Or you could provide a helper function that tests a return code to see if it's derived from Exception.) You can still create your own Exception subclasses; you would simply be returning them rather than raising them.
Finally, I would work toward getting this ridiculous policy changed, as exceptions are an important part of how Python works, have low overhead, and will be expected by anyone using your functions.
A:
You have to use return codes. Other alternatives would involve mutable global state (think C's errno) or passing in a mutable object (such as a list), but you almost always want to avoid both in Python. Perhaps you could try explaining to them how exceptions let you write better post-conditions instead of adding complication to return values, but are otherwise equivalent.
| Python: I'm not allowed to raise exception. Are there other elegant python ways? | My work place has imposed a rules for no use of exception (catching is allowed). If I have code like this
def f1()
if bad_thing_happen():
raise Exception('bad stuff')
...
return something
I could change it to
def f1()
if bad_thing_happen():
return [-1, None]
...
return [0, something]
f1 caller would be like this
def f1_caller():
code, result = f1(param1)
if code < 0:
return code
actual_work1()
# call f1 again
code, result = f1(param2)
if code < 0:
return code
actual_work2()
...
Are there more elegant ways than this in Python ?
| [
"Exceptions in python are not something to be avoided, and are often a straightforward way to solve problems. Additionally, an exception carries a great deal of information with it that can help quickly locate (via stack trace) and identify problems (via exception class or message).\nWhoever has come up with this b... | [
3,
1,
1
] | [] | [] | [
"exception",
"python",
"raise"
] | stackoverflow_0003869326_exception_python_raise.txt |
Q:
Simple Image Manipulation with Python
What I'm trying to do:
I want to give the user the ability to upload a picture that is any size. This image is then resized if it is over 1024 wide or over 768 high. It then resizes the image to be within those bounds, but keeping proportions. Then it adds a semi-transparent watermark to the lower right corner, and saves the file.
Before it adds the watermark, it will create a copy of the image and resize it down to a thumbnail size (also keeping proportions) and saves it in a separate folder.
The Problems with PIL:
As far as resizing goes, I was hoping it would have a way to do smart resizing (keep proportions). Also, I didn't seem to have much control over the quality level when saving it as a JPEG. I had to save it as a PNG to keep full quality which was pretty heavy.
For the thumbnail, it sounds that it might be pretty difficult, reading through the documentation of PIL, but I could be wrong.
The Question
Are there any other, more advanced image libraries for Python that may be a bit more up to date, or include some features that I am looking for? Are there any public functions that do what I'm looking for that I could use? I don't mind writing this stuff myself, but wanted to check first. Thanks!
A:
As far as resizing goes, I was hoping
it would have a way to do smart
resizing (keep proportions).
Seeing as this is probably one or two lines in Python, I don't see why this needs to be in the interface of the library.
Also, I didn't seem to have much
control over the quality level when
saving it as a JPEG.
Quoting the handbook:
The save method supports the following
options:
quality
The image quality, on a scale from 1
(worst) to 95 (best). The default is
75. Values above 95 should be avoided; 100 completely disables the JPEG
quantization stage.
Did you try that? If so, why didn't it help?
A:
Agree with Jim about proportions. You are talking about such a trivial operation that can easily be inlined wherever, that I wouldn't even look for the feature/option in the API to be honest. The moment you call .resize(factor = 0.8, keepRatio = True ), you're typing the same amount of text of punching in .resize(hFactor = 0.8, vFactor = 0.8).
As for libraries, you could have a look at imageMagick with PythonMagick:
http://www.imagemagick.org/script/index.php
It does resizing (with respectable interpolators) and writes to several formats, offers text overlays out of the box, or simple compositing if you have your own watermark you want to paste in.
Used that and not PIL in the last couple places where I had to deal with the problem, and for the simple stuff i needed I was satisfied, that was through magick++ though, not with the Python bindings, but I doubt the experience would be very different. Completely out of touch with PIL though, so I don't know how it would compare.
A:
In a pinch, convert the Image to a numpy array, modify it as you please, and convert back.
| Simple Image Manipulation with Python | What I'm trying to do:
I want to give the user the ability to upload a picture that is any size. This image is then resized if it is over 1024 wide or over 768 high. It then resizes the image to be within those bounds, but keeping proportions. Then it adds a semi-transparent watermark to the lower right corner, and saves the file.
Before it adds the watermark, it will create a copy of the image and resize it down to a thumbnail size (also keeping proportions) and saves it in a separate folder.
The Problems with PIL:
As far as resizing goes, I was hoping it would have a way to do smart resizing (keep proportions). Also, I didn't seem to have much control over the quality level when saving it as a JPEG. I had to save it as a PNG to keep full quality which was pretty heavy.
For the thumbnail, it sounds that it might be pretty difficult, reading through the documentation of PIL, but I could be wrong.
The Question
Are there any other, more advanced image libraries for Python that may be a bit more up to date, or include some features that I am looking for? Are there any public functions that do what I'm looking for that I could use? I don't mind writing this stuff myself, but wanted to check first. Thanks!
| [
"\nAs far as resizing goes, I was hoping\nit would have a way to do smart\nresizing (keep proportions).\n\nSeeing as this is probably one or two lines in Python, I don't see why this needs to be in the interface of the library.\n\nAlso, I didn't seem to have much\ncontrol over the quality level when\nsaving it as a... | [
4,
1,
0
] | [] | [] | [
"image",
"python",
"python_imaging_library"
] | stackoverflow_0003869517_image_python_python_imaging_library.txt |
Q:
HTTP Proxy Server in Python (with authentication)
I needed a simple HTTP proxy server written in Python so I began googling around and found this page. Not all the proxies were working and so I settled for this or this.
..but neither of them support authentication. Has anyone come across a HTTP Proxy Server written in Python that supports authentication?
Thanks.
A:
Useful for NTLM based authentication
on windows
http://ntlmaps.sourceforge.net/
Sortable comparison of open source
proxies in Python
http://proxies.xhaus.com/python/
| HTTP Proxy Server in Python (with authentication) | I needed a simple HTTP proxy server written in Python so I began googling around and found this page. Not all the proxies were working and so I settled for this or this.
..but neither of them support authentication. Has anyone come across a HTTP Proxy Server written in Python that supports authentication?
Thanks.
| [
"\nUseful for NTLM based authentication\n on windows\n\n\nhttp://ntlmaps.sourceforge.net/\n\n\nSortable comparison of open source\n proxies in Python\n\n\nhttp://proxies.xhaus.com/python/\n\n"
] | [
1
] | [] | [] | [
"http",
"proxy_server",
"python"
] | stackoverflow_0003869839_http_proxy_server_python.txt |
Q:
how do I monitor stdout with subprocess in python?
I have a linux application that runs interactively from commandline using stdin to accept commands. I've written a wrapper using subprocess to access stdin while the application is backgrounded. I can now send commands to it using p.stdin.write(command) but how do I go about monitoring its responses?
A:
Read from p.stdout to access the output of the process.
Depending on what the process does, you may have to be careful to ensure that you do not block on p.stdout while p is in turn blocking on its stdin. If you know for certain that it will output a line every time you write to it, you can simply alternate in a loop like this:
while still_going:
p.stdin.write('blah\n')
print p.stdout.readline()
However, if the output is more sporadic, you might want to look into the select module to alternate between reading and writing in a more flexible fashion.
| how do I monitor stdout with subprocess in python? | I have a linux application that runs interactively from commandline using stdin to accept commands. I've written a wrapper using subprocess to access stdin while the application is backgrounded. I can now send commands to it using p.stdin.write(command) but how do I go about monitoring its responses?
| [
"Read from p.stdout to access the output of the process.\nDepending on what the process does, you may have to be careful to ensure that you do not block on p.stdout while p is in turn blocking on its stdin. If you know for certain that it will output a line every time you write to it, you can simply alternate in a ... | [
1
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003869834_python_subprocess.txt |
Q:
Ruby or Python instead of PHP?
I'm considering learning a new language as an alternative to PHP. I'm considering Python and Ruby. Which one is a better language based on the following four criteria, and any other qualifiers you may have?
Which is more stable?
Which is more scaleable?
Which is more secure?
Which is easier to learn?
EDIT:
Keeping the original question intact, I'd like to add one more pair of questions.
Which is quicker to code with?
Which is quicker to learn? (Based on personal experience only please - to avoid holywars.)
EDIT2:
Sorry for not clarifying - mostly web development, some desktop programming would be a nice bonus.
A:
Both are stable
Both are scalable
both are as secure
Both are easier to learn !!
So what matters?
Your taste. Taste them both and proceed with one that seems more palatable :)
A:
These two languages are so similar that any strong preference will be mostly subjective. They are both the correct answer.
A:
I personally would prefer Ruby, as it goes wonderfully with the Rails framework and is a blast to learn and to work with.
I have only used Python a few times. While I know it is powerful, I have never really fallen in love with it the way I have with Ruby (and specifically the Rails framework)
A:
To get a quick feel for each and see which one "tastes" better I would suggest taking each one for a spin on a selection of problems on ProjectEeuler. PE is more about algorithms and math but some of thee simpler problems are a great way to get going with syntax and some core library features such as file IO etc.
A:
No significant difference on the first four criteria.
No significant difference on coding speed either - you're going to be slow in both at the start, then you'll get faster. Ruby may be slightly better at managing libraries (Ruby Gems) but Python probably has slightly broader library coverage. No big deal either way.
Coming from PHP, I'd guess that Python might be slightly quicker to learn. That might be a reason for choosing Ruby - you might learn a little more.
There are a lot of "mights" and "slightlys" there. That's because the two languages are much more similar to each other than either is to PHP. Neither is particularly hard to learn - I'd suggest spending a little time with both and then going deeper with the one you prefer.
A:
i think you should prefer ruby, while python is assumed easier to learn!
python is so friendly great language but you rarely find servers with python support most are expensive one's, ruby on rails is great framework many frameworks for other languages are drives from , great cake php is a sort of such a thing.
ruby on rails can be found on many servers.
how ever if you have specified applications with special clients you can go to python and it's funny frameworks.
by the way, i had a lecture on ruby i had a article claim that ruby is a bit more efficient and more quick.
A:
http://c2.com/cgi/wiki?PythonVsRuby
http://www.nextdoorhacker.com/2010/02/ruby-vs-python-battle-to-death/
http://blog.peepcode.com/tutorials/2010/what-pythonistas-think-of-ruby
Just at the top of the Google results. I've read most before; good articles all. Fundamentally, they are very similar; there are a couple of important philosophical differences that make it a trollworthy subject.
A:
pyfunc pretty much said it, but I'd like to offer two more thoughts:
1) Ruby will probably end up being a tiny bit more familiar as it a) can often optionally use a more C-like syntax, b) is not structured quite as foreignly as Python coming from PHP
2) They can both scale well, but Python will probably give you the most bang for your buck (CPU wise - and if you use Ruby, you're probably pretty well off using Ruby Enterprise and mod_rails, aka phusion passenger).
That's all - even considering those points, the difference may well be negligible, as the power of the language is all about how you use it, regardless of its inherent pros and cons.
| Ruby or Python instead of PHP? | I'm considering learning a new language as an alternative to PHP. I'm considering Python and Ruby. Which one is a better language based on the following four criteria, and any other qualifiers you may have?
Which is more stable?
Which is more scaleable?
Which is more secure?
Which is easier to learn?
EDIT:
Keeping the original question intact, I'd like to add one more pair of questions.
Which is quicker to code with?
Which is quicker to learn? (Based on personal experience only please - to avoid holywars.)
EDIT2:
Sorry for not clarifying - mostly web development, some desktop programming would be a nice bonus.
| [
"Both are stable \nBoth are scalable \nboth are as secure \nBoth are easier to learn !!\n\nSo what matters?\nYour taste. Taste them both and proceed with one that seems more palatable :)\n",
"These two languages are so similar that any strong preference will be mostly subjective. They are both the correct answer... | [
19,
3,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"php",
"programming_languages",
"python",
"ruby"
] | stackoverflow_0003809981_php_programming_languages_python_ruby.txt |
Q:
how to decode a non unicode character in python?
I have a string say s = 'Chocolate Moelleux-M\xe8re' When i am doing:
In [14]: unicode(s)
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 20: ordinal not in range(128)
Similarly when i am trying to decode this by using s.decode() it returns same error.
In [13]: s.decode()
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 20: ordinal not in range(128)
How to decode such string into unicode.
A:
I have had to face this problem one too many times. The problem that I had contained strings in different encoding schemes. So I wrote a method to decode a string heuristically based on certain features of different encodings.
def decode_heuristically(string, enc = None, denc = sys.getdefaultencoding()):
"""
Try to interpret 'string' using several possible encodings.
@input : string, encode type.
@output: a list [decoded_string, flag_decoded, encoding]
"""
if isinstance(string, unicode): return string, 0, "utf-8"
try:
new_string = unicode(string, "ascii")
return string, 0, "ascii"
except UnicodeError:
encodings = ["utf-8","iso-8859-1","cp1252","iso-8859-15"]
if denc != "ascii": encodings.insert(0, denc)
if enc: encodings.insert(0, enc)
for enc in encodings:
if (enc in ("iso-8859-15", "iso-8859-1") and
re.search(r"[\x80-\x9f]", string) is not None):
continue
if (enc in ("iso-8859-1", "cp1252") and
re.search(r"[\xa4\xa6\xa8\xb4\xb8\xbc-\xbe]", string)\
is not None):
continue
try:
new_string = unicode(string, enc)
except UnicodeError:
pass
else:
if new_string.encode(enc) == string:
return new_string, 0, enc
# If unable to decode,doing force decoding i.e.neglecting those chars.
output = [(unicode(string, enc, "ignore"), enc) for enc in encodings]
output = [(len(new_string[0]), new_string) for new_string in output]
output.sort()
new_string, enc = output[-1][1]
return new_string, 1, enc
To add to this this link gives a good feedback on why encoding etc - Why we need sys.setdefaultencoging in py script
A:
You need to tell s.decode your encoding. In your case s.decode('latin-1') seems fitting.
| how to decode a non unicode character in python? | I have a string say s = 'Chocolate Moelleux-M\xe8re' When i am doing:
In [14]: unicode(s)
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 20: ordinal not in range(128)
Similarly when i am trying to decode this by using s.decode() it returns same error.
In [13]: s.decode()
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 20: ordinal not in range(128)
How to decode such string into unicode.
| [
"I have had to face this problem one too many times. The problem that I had contained strings in different encoding schemes. So I wrote a method to decode a string heuristically based on certain features of different encodings. \ndef decode_heuristically(string, enc = None, denc = sys.getdefaultencoding()):\n \"... | [
11,
4
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0003870084_python_unicode.txt |
Q:
python mechanize javascript submit button problem!
im making some script with mechanize.browser module.
one of problem is all other thing is ok, but when submit() form,it not working,
so i was found some suspicion source part.
in the html source i was found such like following.
im thinking, loginCheck(this) making problem when submit form.
but how to handle this kind of javascript function with mechanize module ,so i can
successfully submit form and can receive result?
following is websource snippet which related with loginCheck(this) javascript function.
function init(){
FRMLOGIN.ID.focus();
}
function loginCheck(f){
if(chkNull(f.ID, "아이디를"))
return false;
if(chkNull(f.PWD, "패스워드를"))
return false;
//f.target = "ifrmLoginHidden";
f.action = (f.SECCHK.checked) ? "https://user.buddybuddy.co.kr/Login/Login.asp" : "http://user.buddybuddy.co.kr/Login/Login.asp";
}
i know mechanize not support javascript, so i want to make progammatically loginCheck()
function with python mechanize code.
anyone would you some help me to make this javascript function to python mechanize
translated code?
so correctly can login with website?
if so much appreciate!
# -*- coding: cp949-*-
import sys,os
import mechanize, urllib
import cookielib
from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag
import datetime, time, socket
import re,sys,os,mechanize,urllib,time
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')]
br.open('http://user.buddybuddy.co.kr/Login/LoginForm.asp?URL=')
html = br.response().read()
print html
br.select_form(name='FRMLOGIN')
print br.viewing_html()
br.form['ID']='psh7943'
br.form['PWD']='qkrthgus'
br.submit()
print br.response().read()
if anyone can help me ..much appreciate!!
A:
You can go through the login process by hand in your browser and check (using e.g. Firebug in firefox, Developer Tools in Chrome etc.) what requests are sent to the site when you hit the OK button. Usually this is a POST request with data taken from the login form. Check what data are sent in this request and execute your own post request with:
mechanize.urlopen(URL, POST_DATA).
You can extract POST_DATA (and post_url) from mechanize's form object using:
form.click_request_data()
but you may need to do some modifications.
Very simple example:
br.select_form(name='form_name')
br.form['login']='login'
br.form['pass']='pass'
post_url, post_data, headers = br.form.click_request_data()
mechanize.urlopen(post_url, post_data)
| python mechanize javascript submit button problem! | im making some script with mechanize.browser module.
one of problem is all other thing is ok, but when submit() form,it not working,
so i was found some suspicion source part.
in the html source i was found such like following.
im thinking, loginCheck(this) making problem when submit form.
but how to handle this kind of javascript function with mechanize module ,so i can
successfully submit form and can receive result?
following is websource snippet which related with loginCheck(this) javascript function.
function init(){
FRMLOGIN.ID.focus();
}
function loginCheck(f){
if(chkNull(f.ID, "아이디를"))
return false;
if(chkNull(f.PWD, "패스워드를"))
return false;
//f.target = "ifrmLoginHidden";
f.action = (f.SECCHK.checked) ? "https://user.buddybuddy.co.kr/Login/Login.asp" : "http://user.buddybuddy.co.kr/Login/Login.asp";
}
i know mechanize not support javascript, so i want to make progammatically loginCheck()
function with python mechanize code.
anyone would you some help me to make this javascript function to python mechanize
translated code?
so correctly can login with website?
if so much appreciate!
# -*- coding: cp949-*-
import sys,os
import mechanize, urllib
import cookielib
from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag
import datetime, time, socket
import re,sys,os,mechanize,urllib,time
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')]
br.open('http://user.buddybuddy.co.kr/Login/LoginForm.asp?URL=')
html = br.response().read()
print html
br.select_form(name='FRMLOGIN')
print br.viewing_html()
br.form['ID']='psh7943'
br.form['PWD']='qkrthgus'
br.submit()
print br.response().read()
if anyone can help me ..much appreciate!!
| [
"You can go through the login process by hand in your browser and check (using e.g. Firebug in firefox, Developer Tools in Chrome etc.) what requests are sent to the site when you hit the OK button. Usually this is a POST request with data taken from the login form. Check what data are sent in this request and exec... | [
4
] | [] | [] | [
"mechanize",
"python",
"urlopen"
] | stackoverflow_0003798550_mechanize_python_urlopen.txt |
Q:
Django on IronPython
I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success?
If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?
A:
Besides the Jeff Hardy blog post on Django + IronPython mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy_install and zlib. The first is Solving the zlib problem which discusses the absence of zlib for IronPython; hence, no easyinstall. Jeff reimplemented zlib based on ComponentAce's zlib.net. And finally, in easy_install on IronPython, Part Deux Jeff discusses some final tweaks that are needed before easy_install can be used with IronPython.
A:
Here's a database provider that runs on .NET & that works with Django
A:
This was demoed at last year's PyCon (the details are also available). More recently, Jeff Hardy has blogged about this, including suggestions.
A:
I don't think Django is yet working on IronPython, but I'm not saying it cannot be done.
Django-ironpython project is a work currently underway to run Django on IronPython. The project has reported 65.7% test pass rate with sqlite on 2nd of May 2010.
| Django on IronPython | I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success?
If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?
| [
"Besides the Jeff Hardy blog post on Django + IronPython mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy_install and zlib. The first is Solving the zlib problem which discusses the absence of zlib for IronPython; hence, no eas... | [
26,
8,
5,
2
] | [] | [] | [
"django",
"ironpython",
"python"
] | stackoverflow_0000425990_django_ironpython_python.txt |
Q:
Python drawing cumulative plot (matplotlib)
I have not used matplotlib, but looks like it is main library for drawing plots. I want to draw CPU usage plot. I have background processes each minute making record (date, min_load, avg_load, max_load). date could be timestamp or nice formatted date.
I want to draw diagram which show min_load, avg_load and max_load on the same plot. On X axis I would like to put minutes, hours, days, week depending on how much data there is.
There are possible gaps. Let's say monitored process crashes and because no one restarts it there might be gaps for several hours.
Example of how I imagine it: http://img714.imageshack.us/img714/2074/infoplot1.png
This does not illustrate gaps, but in this situation on readings go to 0.
I am playing with matplotlib right now I will try sharing my results too. This is how data might look like:
1254152292;0.07;0.08;0.13
1254152352;0.04;0.05;0.10
1254152412;0.09;0.10;0.17
1254152472;0.28;0.29;0.30
1254152532;0.20;0.20;0.21
1254152592;0.09;0.12;0.15
1254152652;0.09;0.12;0.14
1254152923;0.13;0.12;0.30
1254152983;0.13;0.25;0.32
Or it could look something like this:
Wed Oct 06 08:03:55 CEST 2010;0.25;0.30;0.35
Wed Oct 06 08:03:56 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:57 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:58 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:59 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:04:00 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:04:01 CEST 2010;0.25;0.50;0,75
Wed Oct 06 08:04:02 CEST 2010;0.00;0.01;0.02
-david
A:
Try:
from matplotlib.dates import strpdate2num, epoch2num
import numpy as np
from pylab import figure, show, cm
datefmt = "%a %b %d %H:%M:%S CEST %Y"
datafile = "cpu.dat"
def parsedate(x):
global datefmt
try:
res = epoch2num( int(x) )
except:
try:
res = strpdate2num(datefmt)(x)
except:
print("Cannot parse date ('"+x+"')")
exit(1)
return res
# parse data file
t,a,b,c = np.loadtxt(
datafile, delimiter=';',
converters={0:parsedate},
unpack=True)
fig = figure()
ax = fig.add_axes((0.1,0.1,0.7,0.85))
# limit y axis to 0
ax.set_ylim(0);
# colors
colors=['b','g','r']
fill=[(0.5,0.5,1), (0.5,1,0.5), (1,0.5,0.5)]
# plot
for x in [c,b,a]:
ax.plot_date(t, x, '-', lw=2, color=colors.pop())
ax.fill_between(t, x, color=fill.pop())
# legend
ax.legend(['max','avg','min'], loc=(1.03,0.4), frameon=False)
fig.autofmt_xdate()
show()
This parses the lines from "cpu.dat" file. Date is parsed by parsedate function.
Matplotlib should find the best format for the x axis.
Edit: Added legend and fill_between (maybe there is better way to do this).
| Python drawing cumulative plot (matplotlib) | I have not used matplotlib, but looks like it is main library for drawing plots. I want to draw CPU usage plot. I have background processes each minute making record (date, min_load, avg_load, max_load). date could be timestamp or nice formatted date.
I want to draw diagram which show min_load, avg_load and max_load on the same plot. On X axis I would like to put minutes, hours, days, week depending on how much data there is.
There are possible gaps. Let's say monitored process crashes and because no one restarts it there might be gaps for several hours.
Example of how I imagine it: http://img714.imageshack.us/img714/2074/infoplot1.png
This does not illustrate gaps, but in this situation on readings go to 0.
I am playing with matplotlib right now I will try sharing my results too. This is how data might look like:
1254152292;0.07;0.08;0.13
1254152352;0.04;0.05;0.10
1254152412;0.09;0.10;0.17
1254152472;0.28;0.29;0.30
1254152532;0.20;0.20;0.21
1254152592;0.09;0.12;0.15
1254152652;0.09;0.12;0.14
1254152923;0.13;0.12;0.30
1254152983;0.13;0.25;0.32
Or it could look something like this:
Wed Oct 06 08:03:55 CEST 2010;0.25;0.30;0.35
Wed Oct 06 08:03:56 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:57 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:58 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:59 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:04:00 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:04:01 CEST 2010;0.25;0.50;0,75
Wed Oct 06 08:04:02 CEST 2010;0.00;0.01;0.02
-david
| [
"Try:\nfrom matplotlib.dates import strpdate2num, epoch2num\nimport numpy as np\nfrom pylab import figure, show, cm\n\ndatefmt = \"%a %b %d %H:%M:%S CEST %Y\"\ndatafile = \"cpu.dat\"\n\ndef parsedate(x):\n global datefmt\n try:\n res = epoch2num( int(x) )\n except:\n try:\n res = s... | [
2
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0003869866_matplotlib_plot_python.txt |
Q:
I'm looking for an example on how to use select.select() with subprocess to monitor stdout
Basically, I have an application that is loaded using
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
I can send it commands using p.stdin.write() without any trouble, but I need to monitor stdout for server responses. this whole thing is running inside a tcp server, so I need to know if select.select() is going to stop execution when its called. I also can't find any example code using select.select and I find the manual page to be a little confusing. Could someone here offer some advice on this?
A:
A non-None timeout parameter will make sure that select() doesn't block.
| I'm looking for an example on how to use select.select() with subprocess to monitor stdout | Basically, I have an application that is loaded using
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
I can send it commands using p.stdin.write() without any trouble, but I need to monitor stdout for server responses. this whole thing is running inside a tcp server, so I need to know if select.select() is going to stop execution when its called. I also can't find any example code using select.select and I find the manual page to be a little confusing. Could someone here offer some advice on this?
| [
"A non-None timeout parameter will make sure that select() doesn't block.\n"
] | [
0
] | [] | [] | [
"python",
"select",
"subprocess"
] | stackoverflow_0003870453_python_select_subprocess.txt |
Q:
Google App Engine Python: How to display textarea value in mail
I have a html form with <textarea name="message"></textarea> and I get the value by message = self.request.get('message').
Then I do mail api
message = mail.EmailMessage(sender="abc@domain.com", subject="Testing")
message.to = 'bcd@domain.com'
message.html = """The Message: %s """ % (message)
message.send()
The problem is I can only see the "The Message:" in my email without the 'message' value, how do I solve the problem?
A:
You're using the variable name 'message' for both the original text in the textarea, and the email you're sending. Try this:
text = self.request.get('message')
message = mail.EmailMessage(sender="abc@domain.com", subject="Testing")
message.to = 'bcd@domain.com'
message.html = """The Message: %s """ % (text)
message.send()
A:
I'm not familiar with the GAE mail api but you seem to reassign the message variable name to a new item, in this case an object, then you try to make the object the message body. :s
Try something like:
message = self.request.get('message')
mailer = mail.EmailMessage(sender="abc@domain.com", subject="Testing")
mailer.to = 'bcd@domain.com'
mailer.html = """The Message: %s """ % (message)
mailer.send()
In production you would probably also want to do a null check for the message variable's value.
| Google App Engine Python: How to display textarea value in mail | I have a html form with <textarea name="message"></textarea> and I get the value by message = self.request.get('message').
Then I do mail api
message = mail.EmailMessage(sender="abc@domain.com", subject="Testing")
message.to = 'bcd@domain.com'
message.html = """The Message: %s """ % (message)
message.send()
The problem is I can only see the "The Message:" in my email without the 'message' value, how do I solve the problem?
| [
"You're using the variable name 'message' for both the original text in the textarea, and the email you're sending. Try this:\ntext = self.request.get('message')\nmessage = mail.EmailMessage(sender=\"abc@domain.com\", subject=\"Testing\") \nmessage.to = 'bcd@domain.com' \nmessage.html = \"\"\"The Message: %s \"\"\"... | [
4,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003870279_google_app_engine_python.txt |
Q:
How to parse xsd:dateTime format?
Values of type xsd:dateTime can have a variety of forms, as described in RELAX NG.
How can I parse all the forms into either time or datetime objects?
A:
It's actually a pretty restricted format, especially compared to all of ISO 8601. Using a regex is mostly the same as using strptime plus handling the offset yourself (which strptime doesn't do).
import datetime
import re
def parse_timestamp(s):
"""Returns (datetime, tz offset in minutes) or (None, None)."""
m = re.match(""" ^
(?P<year>-?[0-9]{4}) - (?P<month>[0-9]{2}) - (?P<day>[0-9]{2})
T (?P<hour>[0-9]{2}) : (?P<minute>[0-9]{2}) : (?P<second>[0-9]{2})
(?P<microsecond>\.[0-9]{1,6})?
(?P<tz>
Z | (?P<tz_hr>[-+][0-9]{2}) : (?P<tz_min>[0-9]{2})
)?
$ """, s, re.X)
if m is not None:
values = m.groupdict()
if values["tz"] in ("Z", None):
tz = 0
else:
tz = int(values["tz_hr"]) * 60 + int(values["tz_min"])
if values["microsecond"] is None:
values["microsecond"] = 0
else:
values["microsecond"] = values["microsecond"][1:]
values["microsecond"] += "0" * (6 - len(values["microsecond"]))
values = dict((k, int(v)) for k, v in values.iteritems()
if not k.startswith("tz"))
try:
return datetime.datetime(**values), tz
except ValueError:
pass
return None, None
Doesn't handle applying the time zone offset to the datetime, and negative years are a problem with datetime. Both of those problems would be fixed by different timestamp type that handled the full range required by xsd:dateTime.
valid = [
"2001-10-26T21:32:52",
"2001-10-26T21:32:52+02:00",
"2001-10-26T19:32:52Z",
"2001-10-26T19:32:52+00:00",
#"-2001-10-26T21:32:52",
"2001-10-26T21:32:52.12679",
]
for v in valid:
print
print v
r = parse_timestamp(v)
assert all(x is not None for x in r), v
# quick and dirty, and slightly wrong
# (doesn't distinguish +00:00 from Z among other issues)
# but gets through the above cases
tz = ":".join("%02d" % x for x in divmod(r[1], 60)) if r[1] else "Z"
if r[1] > 0: tz = "+" + tz
r = r[0].isoformat() + tz
print r
assert r.startswith(v[:len("CCYY-MM-DDThh:mm:ss")]), v
print "---"
invalid = [
"2001-10-26",
"2001-10-26T21:32",
"2001-10-26T25:32:52+02:00",
"01-10-26T21:32",
]
for v in invalid:
print v
r = parse_timestamp(v)
assert all(x is None for x in r), v
A:
Try the dateutil.parser module from python-dateutil. Or maybe isodate (haven't used the last one yet, but looks interesting (and made specifically only for the purpose of parsing ISO 8601 format).
| How to parse xsd:dateTime format? | Values of type xsd:dateTime can have a variety of forms, as described in RELAX NG.
How can I parse all the forms into either time or datetime objects?
| [
"It's actually a pretty restricted format, especially compared to all of ISO 8601. Using a regex is mostly the same as using strptime plus handling the offset yourself (which strptime doesn't do).\nimport datetime\nimport re\n\ndef parse_timestamp(s):\n \"\"\"Returns (datetime, tz offset in minutes) or (None, Non... | [
2,
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002211362_python_xml.txt |
Q:
Trouble getting code parameter on facebook oauth callback
I'm writing a Django app requesting permission to post on facebook.
I can access authorization and callback, but I can't get the parameter 'code' that facebook needs to continue with oauth.
def connect_fb(request):
return redirect("https://graph.facebook.com/oauth/authorize?"
+"client_id=MY_ID&"
+"redirect_uri=MY_URL"
+"&type=user_agent&display=popup&scope=publish_stream")
def callback_facebook(request):
code=request.REQUEST.get("code")
What's the right way to get 'code' so I can continue the oauth process?
I tried several things but I keep getting None instead of a code.
Thanks
A:
I've used django-facebook-oauth in the past, but if you really want to roll your own solution then I'd suggest just looking through their source.
From just glancing through it, the only thing I can see you doing differently is the
&type=user_agent&display=popup
in the URL. The app I linked you to doesn't appear to do that as far as I can tell.
A:
The problem comes from type=user_agent that is used in javascript authentication, and not here.
Removing it allows to get code as above.
| Trouble getting code parameter on facebook oauth callback | I'm writing a Django app requesting permission to post on facebook.
I can access authorization and callback, but I can't get the parameter 'code' that facebook needs to continue with oauth.
def connect_fb(request):
return redirect("https://graph.facebook.com/oauth/authorize?"
+"client_id=MY_ID&"
+"redirect_uri=MY_URL"
+"&type=user_agent&display=popup&scope=publish_stream")
def callback_facebook(request):
code=request.REQUEST.get("code")
What's the right way to get 'code' so I can continue the oauth process?
I tried several things but I keep getting None instead of a code.
Thanks
| [
"I've used django-facebook-oauth in the past, but if you really want to roll your own solution then I'd suggest just looking through their source.\nFrom just glancing through it, the only thing I can see you doing differently is the\n&type=user_agent&display=popup\n\nin the URL. The app I linked you to doesn't appe... | [
1,
0
] | [] | [] | [
"django",
"facebook",
"oauth",
"python"
] | stackoverflow_0003866263_django_facebook_oauth_python.txt |
Q:
How to handle call to __setattr__ from __init__?
I have written a class that will be used to store parameters in a convenient way for pickling. It overloads __setattr__ for convenient access. It also uses a list to remember the order in which attributes where added, so that the iteration order is predictable and constant. Here it is:
class Parameters(object):
def __init__(self):
self._paramOrder = []
def __setattr__(self, name, value):
self._paramOrder.append(name)
object.__setattr__(self, name, value)
def __delattr__(self, name):
self._paramOrder.remove(name)
object.__delattr__(self, name)
def __iter__(self):
for name in self._paramOrder:
yield self.name
def iteritems(self):
for name in self._paramOrder:
yield name, self.name
The problem is that __init__ calls my overloaded __setattr__ in order to add the _paramOrder to the instance dictionary. Is there a way to handle this without adding a special case to __setattr__?
A:
yes.
have it call super(Parameters, self).__setattr__() instead.
class Parameters(object):
def __init__(self):
super(Parameters, self).__setattr__('paramOrder', [])
# etc.
Or am I missing something?
Another alternative is to just go straight to __dict__
class Parameters(object):
def __init__(self):
self.__dict__['paramOrder'] = []
# etc.
This should work because you are not overriding __getattr__ so you can read it without anything getting in the way.
A:
Use this line in __init__ instead:
object.__setattr__(self, '_paramOrder', [])
| How to handle call to __setattr__ from __init__? | I have written a class that will be used to store parameters in a convenient way for pickling. It overloads __setattr__ for convenient access. It also uses a list to remember the order in which attributes where added, so that the iteration order is predictable and constant. Here it is:
class Parameters(object):
def __init__(self):
self._paramOrder = []
def __setattr__(self, name, value):
self._paramOrder.append(name)
object.__setattr__(self, name, value)
def __delattr__(self, name):
self._paramOrder.remove(name)
object.__delattr__(self, name)
def __iter__(self):
for name in self._paramOrder:
yield self.name
def iteritems(self):
for name in self._paramOrder:
yield name, self.name
The problem is that __init__ calls my overloaded __setattr__ in order to add the _paramOrder to the instance dictionary. Is there a way to handle this without adding a special case to __setattr__?
| [
"yes.\nhave it call super(Parameters, self).__setattr__() instead.\nclass Parameters(object):\n def __init__(self):\n super(Parameters, self).__setattr__('paramOrder', [])\n\n # etc.\n\nOr am I missing something?\nAnother alternative is to just go straight to __dict__\nclass Parameters(object):\n de... | [
12,
4
] | [] | [] | [
"python"
] | stackoverflow_0003870982_python.txt |
Q:
Pylons - Handling GET and POST requests
What's the best way to handle form POST data in my Pylons app? I've tried:
Having a seperate GET method and a POST method with a rest.restrict('post') decorator. Problem -- if there were validation errors then you can't redisplay the form with the data which the user entered because you have to redirect back to the GET method OR you have to render the template directly from the POST method. Unfortunately this looks weird, as the URL has to change to correspond to the POST action.
Having it all in one method, and detecting if the form has been posted via a check on request.method. This works okay, but it seems clumsy to have if request.method == 'post': ... else: ...
A:
Having it all in one method, and detecting if the form has been posted via a check on request.method. This works okay, but it seems clumsy to have if request.method == 'post': ... else: ...
I am not sure why you describe this as clumsy. Switching on request method is a valid idiom in the web app world across languages. For e.g. you'll find Django views having a single view that handles requests differently based on request.method. Similarly in Java, Servlets have doPost() and doGet() methods to provide different behavior for GET and POST requests.
Update
I'd just rather have them separated into different methods, if possible. Many other web frameworks do this
Nothing wrong with this approach either. I was merely pointing out that having the same method handle them is equally valid.
| Pylons - Handling GET and POST requests | What's the best way to handle form POST data in my Pylons app? I've tried:
Having a seperate GET method and a POST method with a rest.restrict('post') decorator. Problem -- if there were validation errors then you can't redisplay the form with the data which the user entered because you have to redirect back to the GET method OR you have to render the template directly from the POST method. Unfortunately this looks weird, as the URL has to change to correspond to the POST action.
Having it all in one method, and detecting if the form has been posted via a check on request.method. This works okay, but it seems clumsy to have if request.method == 'post': ... else: ...
| [
"\nHaving it all in one method, and detecting if the form has been posted via a check on request.method. This works okay, but it seems clumsy to have if request.method == 'post': ... else: ...\n\nI am not sure why you describe this as clumsy. Switching on request method is a valid idiom in the web app world across ... | [
2
] | [] | [] | [
"pylons",
"python",
"validation"
] | stackoverflow_0003871145_pylons_python_validation.txt |
Q:
What security issues need to be addressed when working with Google App Engine?
I've been considering using Google App Engine for a few hobby projects. While they won't be handling any sensitive data, I'd still like to make them relatively secure for a number of reasons, like learning about security, legal, etc.
What security issues need to be addressed when working with Google App Engine?
Are they the same issues that other applications - like applications written in other languages or hosted in other ways - are faced with?
Edit: I did some searching it looks like I need to sanitize input for XSS and Injection. What are other things to consider?
A:
“Sanitising” input is not the way to avoid query-injection and markup-injection problems. Using the correct form of escaping at the output stage is... or, even better, using a higher-level tool that deals with it for you.
So for preventing query-injection against GQL, use the parameter-binding interface of GqlQuery. For preventing markup-injection against HTML (leading to XSS), use the HTML-escaping feature of whatever templating language you're using. For example, for Django templates, |escape... or, better, {% autoescape on %} so you don't accidentally miss one.
| What security issues need to be addressed when working with Google App Engine? | I've been considering using Google App Engine for a few hobby projects. While they won't be handling any sensitive data, I'd still like to make them relatively secure for a number of reasons, like learning about security, legal, etc.
What security issues need to be addressed when working with Google App Engine?
Are they the same issues that other applications - like applications written in other languages or hosted in other ways - are faced with?
Edit: I did some searching it looks like I need to sanitize input for XSS and Injection. What are other things to consider?
| [
"“Sanitising” input is not the way to avoid query-injection and markup-injection problems. Using the correct form of escaping at the output stage is... or, even better, using a higher-level tool that deals with it for you.\nSo for preventing query-injection against GQL, use the parameter-binding interface of GqlQue... | [
7
] | [
"In general there are the same issues. In addition google \"knows\" your code and can in theory monitor anything what the code is doing. Therefore it is very difficult if you want to prevent them from reading your data.\nBut i don't believe they have time and resources to monitor your code and data that close.\n"
] | [
-2
] | [
"google_app_engine",
"python",
"security",
"web_applications"
] | stackoverflow_0003871012_google_app_engine_python_security_web_applications.txt |
Q:
Is there a way to emulate the __prepare__ special method of a Python 3-metaclass in Python 2.5?
In my project I have to stick to Python 2.5 (Google App Engine). Somewhere in the application (actually a framework), I have to keep track which variables are defined and in which order they are defined, in other words I would like to intercept whenever an assignment operator is processed.
Using Python 3, I would define a metaclass M with a __prepare__ method that returns an intelligent dictionary that keeps track of when it is accessed. Then I just have to execute everything inside a class statement with metaclass M.
Is there any way to emulate this in Python 2.5?
EXAMPLE of what I would like to achieve
With the metaclass approach of Python 3, I could implement variables that work like references, for example M could be so that
# y is a callable
class C(metaclass=M):
x = ref(y)
x = 1
would be equivalent (up to the creation of C) with y(1), i.e. the first assignment to a variable in C's dictionary by a black-box ref function creates this variable. Further assignments simply call the parameter of the ref function.
A:
You can wrap the variables you populate your classes with with a wrapper that internally keeps a counter and assigns an increasing value. The wrapper may be subclassed for tagging or to add behaviour to the variables. You would use the variable value to order them and a regular Python 2 metaclass to intercept the class creation.
Django is one of the projects that uses this technique to remember the order in which members are defined on a model class. You can take a look at where the fields are created; it is then used in the implementation of the __cmp__ method to keep the fields in the order of creation.
| Is there a way to emulate the __prepare__ special method of a Python 3-metaclass in Python 2.5? | In my project I have to stick to Python 2.5 (Google App Engine). Somewhere in the application (actually a framework), I have to keep track which variables are defined and in which order they are defined, in other words I would like to intercept whenever an assignment operator is processed.
Using Python 3, I would define a metaclass M with a __prepare__ method that returns an intelligent dictionary that keeps track of when it is accessed. Then I just have to execute everything inside a class statement with metaclass M.
Is there any way to emulate this in Python 2.5?
EXAMPLE of what I would like to achieve
With the metaclass approach of Python 3, I could implement variables that work like references, for example M could be so that
# y is a callable
class C(metaclass=M):
x = ref(y)
x = 1
would be equivalent (up to the creation of C) with y(1), i.e. the first assignment to a variable in C's dictionary by a black-box ref function creates this variable. Further assignments simply call the parameter of the ref function.
| [
"You can wrap the variables you populate your classes with with a wrapper that internally keeps a counter and assigns an increasing value. The wrapper may be subclassed for tagging or to add behaviour to the variables. You would use the variable value to order them and a regular Python 2 metaclass to intercept the ... | [
3
] | [
"One place to start is by looking at PEP-3115 and reading about the \"current\" behavior, e.g. the behavior that was current before Python 3 was implemented.\n"
] | [
-1
] | [
"metaclass",
"python",
"python_3.x"
] | stackoverflow_0003870282_metaclass_python_python_3.x.txt |
Q:
Reading from a file using pickle and for loop in python
I have a file in which I have dumped a huge number of lists.Now I want to load this file into memory and use the data inside it.I tried to load my file using the "load" method of "pickle", However, for some reason it just gives me the first item in the file. actually I noticed that it only load the my first list into memory and If I want to load my whole file(a number of lists) then I have to iterate over my file and use "pickle.load(filename)" in each of the iterations i take.
The problem is that I don't know how to actually implement it with a loop(for or while), because I don't know when I reach the end of my file.
an example would help me a lot.
thanks
A:
How about this:
lists = []
infile = open('yourfilename.pickle', 'r')
while 1:
try:
lists.append(pickle.load(infile))
except (EOFError, UnpicklingError):
break
infile.close()
| Reading from a file using pickle and for loop in python | I have a file in which I have dumped a huge number of lists.Now I want to load this file into memory and use the data inside it.I tried to load my file using the "load" method of "pickle", However, for some reason it just gives me the first item in the file. actually I noticed that it only load the my first list into memory and If I want to load my whole file(a number of lists) then I have to iterate over my file and use "pickle.load(filename)" in each of the iterations i take.
The problem is that I don't know how to actually implement it with a loop(for or while), because I don't know when I reach the end of my file.
an example would help me a lot.
thanks
| [
"How about this:\nlists = []\ninfile = open('yourfilename.pickle', 'r')\nwhile 1:\n try:\n lists.append(pickle.load(infile))\n except (EOFError, UnpicklingError):\n break\ninfile.close()\n\n"
] | [
10
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0003871388_pickle_python.txt |
Q:
Avoid OpenERP audittrail bug
I'd like to manage OpenERP user's activity by installing the audittrail module.
After creating some rules ( define which user, which object and which activity (create, update..) will be monitored). I update a product to see it works.
When I've tried to update a product i got the system error. Seeing the log, I get
[2010-08-31 12:53:35,042] Cursor not closed explicitly
[2010-08-31 12:53:35,043] Cursor was created at /home/pilgrim/working/sources/addons/audittrail/audittrail.py:204
Here the line that causes error
cr = pooler.get_db(db).cursor()
Looking at sql_db.py, I get the comment
def __del__(self):
if not self.__closed:
# Oops. 'self' has not been closed explicitly.
# The cursor will be deleted by the garbage collector,
# but the database connection is not put back into the connection
# pool, preventing some operation on the database like dropping it.
# This can also lead to a server overload.
msg = "Cursor not closed explicitly\n" \
"Cursor was created at %s:%s" % self.__caller
log(msg, netsvc.LOG_WARNING)
self.close()
Since I'm new to Python, I don't know how to overcome this issue?
Any hint to get over this?
Thank
A:
t would be important to see the source code to understand whats going on.
But from what you have posted it looks like the previous cursor was not closed explicitly.
cr = sqldb.db_connect(dbname).cursor()
.........
cr.close()
cr = None
I would suggest that you hack audittrail.py to find where ever you are creating the cursor and where ever you close them. A typical issue arises in incorrect handling of exceptions, causing code to jump over normal closure.
Try placing a try, except and finally clause around the questionable cursor operation. That should help you to get around the problem.
A:
I think I find the answer.
See an example
def a():
try:
print 'before return '
return 1
finally:
print 'in finally'
call a()
before return
in finally
1
It's normal. OK.
Try another example ( code extract from audittrail.py)
def do_something_with_db(db):
// open cusror again
cr = db.cursor()
// do somethign
// close cursor internally
cr.close()
def execute(db)
// 1, open connection and open cursor
cr = db.cursor
try:
//2, do something with db, seeing that this method will open cursor again
return do_something_with_db(db)
finally:
cr.close()
Seeing that the implementation of do_something_with_db trying to open the cursor ( can be called connection) but the current one is not explicitly closed.
So the solution is simple: Pass the current cr around
Before
**do_something_with_db(db)**
after
**do_something_with_db(cr)**
Now the error's gone.
@Don Kirkby: Yes, we should experiment with try...finally
A:
Can you run OpenERP in a debugger like the PyDev plug in for Eclipse? I find that the most effective way to track down problems. I haven't used the audit trail module, but I took a quick look at the source code, and it appears that the cursor is being opened near the beginning of log_fct(). (I would have expected it to report line 207, which version are you running?) Here's what I think is the relevant code:
def log_fct(self, db, uid, passwd, object, method, fct_src, *args):
logged_uids = []
pool = pooler.get_pool(db)
cr = pooler.get_db(db).cursor() # line 207 in version 5.0.12
# ...
if method in ('create'):
# ...
cr.close()
return res_id
# ...
cr.close()
It looks like there are several return statements in the method, but each one seems to call cr.close() first, so I don't see any obvious problems. Try running it in the debugger with a break point in this method. If that's not possible, you can try writing to the log with something like this:
logger = netsvc.Logger()
logger.notifyChannel('audittrail', netsvc.LOG_INFO, 'something happened')
Update:
You commented that this happens under heavy load. Perhaps an exception is being thrown and the cursor is not being closed. You could use a try ... finally statement to make sure that the cursor is always closed. Here's how the sample above would look after converting it:
def log_fct(self, db, uid, passwd, object, method, fct_src, *args):
logged_uids = []
pool = pooler.get_pool(db)
cr = pooler.get_db(db).cursor() # line 207 in version 5.0.12
try:
# ...
if method in ('create'):
# ...
return res_id
# ...
finally:
cr.close()
| Avoid OpenERP audittrail bug | I'd like to manage OpenERP user's activity by installing the audittrail module.
After creating some rules ( define which user, which object and which activity (create, update..) will be monitored). I update a product to see it works.
When I've tried to update a product i got the system error. Seeing the log, I get
[2010-08-31 12:53:35,042] Cursor not closed explicitly
[2010-08-31 12:53:35,043] Cursor was created at /home/pilgrim/working/sources/addons/audittrail/audittrail.py:204
Here the line that causes error
cr = pooler.get_db(db).cursor()
Looking at sql_db.py, I get the comment
def __del__(self):
if not self.__closed:
# Oops. 'self' has not been closed explicitly.
# The cursor will be deleted by the garbage collector,
# but the database connection is not put back into the connection
# pool, preventing some operation on the database like dropping it.
# This can also lead to a server overload.
msg = "Cursor not closed explicitly\n" \
"Cursor was created at %s:%s" % self.__caller
log(msg, netsvc.LOG_WARNING)
self.close()
Since I'm new to Python, I don't know how to overcome this issue?
Any hint to get over this?
Thank
| [
"t would be important to see the source code to understand whats going on.\nBut from what you have posted it looks like the previous cursor was not closed explicitly.\ncr = sqldb.db_connect(dbname).cursor()\n.........\ncr.close()\ncr = None\n\nI would suggest that you hack audittrail.py to find where ever you are c... | [
4,
2,
1
] | [] | [] | [
"audit_trail",
"openerp",
"python"
] | stackoverflow_0003606418_audit_trail_openerp_python.txt |
Q:
HttpLib2 throws error when trying to do a request to couchdb
I'm building an application in Python2.6 that needs to get data from CouchDb. I'm using CouchDB-0.8-py2.6 to connect to the database.
I'm using this code:
import couchdb
server = couchdb.Server(url='http://localhost:5984/', full_commit=True, session=None)
db = server['databaseName']
doc = db['docId']
value = doc['value']
print(value)
On my local machine (OSX) the code runs perfectly, but when I'm trying to run it on a Debian server, I get the following error:
File "/usr/local/lib/python2.6/dist-packages/CouchDB-0.7dev_r199-py2.6.egg/couchdb/client.py", line 165, in __getitem__
db.resource.head() # actually make a request to the database
File "/usr/local/lib/python2.6/dist-packages/CouchDB-0.7dev_r199-py2.6.egg/couchdb/client.py", line 977, in head
return self._request('HEAD', path, headers=headers, **params)
File "/usr/local/lib/python2.6/dist-packages/CouchDB-0.7dev_r199-py2.6.egg/couchdb/client.py", line 1010, in _request
resp, data = _make_request()
File "/usr/local/lib/python2.6/dist-packages/CouchDB-0.7dev_r199-py2.6.egg/couchdb/client.py", line 1005, in _make_request
body=body, headers=headers)
File "/usr/local/lib/python2.6/dist-packages/httplib2-0.6.0-py2.6.egg/httplib2/__init__.py", line 1025, in request
cached_value = self.cache.get(cachekey)
AttributeError: 'bool' object has no attribute 'get'
I've tried to Google this numerous times and no-one seems to have the same error. Does anyone have an idea what I'm doing wrong here?
A:
You're using a different version of CouchDB on the server - CouchDB-0.7dev_r199. CouchDB does not use httplib2 anymore, so if you get your development and server environments roughly the same the problem is quite likely to disappear.
| HttpLib2 throws error when trying to do a request to couchdb | I'm building an application in Python2.6 that needs to get data from CouchDb. I'm using CouchDB-0.8-py2.6 to connect to the database.
I'm using this code:
import couchdb
server = couchdb.Server(url='http://localhost:5984/', full_commit=True, session=None)
db = server['databaseName']
doc = db['docId']
value = doc['value']
print(value)
On my local machine (OSX) the code runs perfectly, but when I'm trying to run it on a Debian server, I get the following error:
File "/usr/local/lib/python2.6/dist-packages/CouchDB-0.7dev_r199-py2.6.egg/couchdb/client.py", line 165, in __getitem__
db.resource.head() # actually make a request to the database
File "/usr/local/lib/python2.6/dist-packages/CouchDB-0.7dev_r199-py2.6.egg/couchdb/client.py", line 977, in head
return self._request('HEAD', path, headers=headers, **params)
File "/usr/local/lib/python2.6/dist-packages/CouchDB-0.7dev_r199-py2.6.egg/couchdb/client.py", line 1010, in _request
resp, data = _make_request()
File "/usr/local/lib/python2.6/dist-packages/CouchDB-0.7dev_r199-py2.6.egg/couchdb/client.py", line 1005, in _make_request
body=body, headers=headers)
File "/usr/local/lib/python2.6/dist-packages/httplib2-0.6.0-py2.6.egg/httplib2/__init__.py", line 1025, in request
cached_value = self.cache.get(cachekey)
AttributeError: 'bool' object has no attribute 'get'
I've tried to Google this numerous times and no-one seems to have the same error. Does anyone have an idea what I'm doing wrong here?
| [
"You're using a different version of CouchDB on the server - CouchDB-0.7dev_r199. CouchDB does not use httplib2 anymore, so if you get your development and server environments roughly the same the problem is quite likely to disappear.\n"
] | [
1
] | [] | [] | [
"couchdb",
"httplib2",
"python"
] | stackoverflow_0003871464_couchdb_httplib2_python.txt |
Q:
Django model inheritance problem. How to solve?
I have an existing app with the following model
class Contact(models.Model):
lastname = models.CharField(max_length=200)
firstname = models.CharField(max_length=200)
...
class Journalist(Contact):
pass
I have a Contact in my database and I would like that it becomes a Journalist.
In raw sql, it seems as simple as insert into app_journalist values (25624);. In this example 25624 is the id of the existing contact. It seems to work ok and the django app seems happy.
However, I would like to make the same thing with the django ORM. I have tried several thinks like forcing the journalist id (Journalist(id=25624)) but it creates a new contact rather than linking to the existing one.
Is it possible do to that with the Django ORM? How?
Thanks in advance for your help
A:
One way to solve this is (without changing your model structure) to set the contact_ptr attribute of the Journalist instance to the appropriate Contact instance. For e.g.
contact = Contact.objects.get(pk = 25624)
journalist = Journalist(contact_ptr = contact)
journalist.save()
This becomes easier to understand if you first look at the table app_journalist. It has but one column, contact_ptr_id. So when you execute insert into app_journalist values (25624) you are setting contact_ptr_id = 25624 at the SQL level. Correspondingly you should set the contact_ptr = <instance of Contact> at the ORM level.
Update
There are other ways to solve the problem but they would require changes to your existing models. As @bugspy.net pointed out you can use a generic relationship. Alternately you can declare an additional type field to specify whether the contact is a journalist, a colleague etc.
Update 2
Also take a look at this demo snippet (and the complete code) that lets you use polymorphic inheritance (SQLAlchemy already does this).
Update 3
As @luc himself pointed out (see comment below)
journalist = Journalist(contact_ptr = contact)
alone will not suffice. This will overwrite the firstname and lastname of the contact to "". To avoid this you have to explicitly assign each field to Journalist.
A:
Django's Contenttypes framework is really handy.
You could use it to represent different contact types:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Contact(models.Model):
lastname = models.CharField(max_length=200)
firstname = models.CharField(max_length=200)
content_object = generic.GenericForeignKey('content_type', 'object_id')
A:
Inheritance at the model level is usually not such a good idea. Most ORM let you do it. Most ORM are even proud to be able to do it. At the model level, the famous "prefer composition over inheritance" is more true than ever.
In your case, instead of saying : "A journalist IS A person", you could instead say : "A person has a job, which in this case is journalist". This would be represented by a Person class composed with a Job class. One of the job could be "journalist".
The composition approach lets you have a person change job, or even have multiple jobs.
Of course, this doesnt directly answer your question, but the other answers are already pretty good !
| Django model inheritance problem. How to solve? | I have an existing app with the following model
class Contact(models.Model):
lastname = models.CharField(max_length=200)
firstname = models.CharField(max_length=200)
...
class Journalist(Contact):
pass
I have a Contact in my database and I would like that it becomes a Journalist.
In raw sql, it seems as simple as insert into app_journalist values (25624);. In this example 25624 is the id of the existing contact. It seems to work ok and the django app seems happy.
However, I would like to make the same thing with the django ORM. I have tried several thinks like forcing the journalist id (Journalist(id=25624)) but it creates a new contact rather than linking to the existing one.
Is it possible do to that with the Django ORM? How?
Thanks in advance for your help
| [
"One way to solve this is (without changing your model structure) to set the contact_ptr attribute of the Journalist instance to the appropriate Contact instance. For e.g.\ncontact = Contact.objects.get(pk = 25624)\njournalist = Journalist(contact_ptr = contact)\njournalist.save()\n\nThis becomes easier to understa... | [
3,
2,
0
] | [] | [] | [
"django",
"django_models",
"django_orm",
"inheritance",
"python"
] | stackoverflow_0003871094_django_django_models_django_orm_inheritance_python.txt |
Q:
Alternate ways of saving a list into a file in Python
I am trying to a save a list into a file in a way that when I load and read the file again I get my lists as they are. In other words,the datatype doesn't change while saving and loading. Because right now, I use "write" to save my list into a file, and when I try to load it back into memory I get strings rather than real lists. is there a way to convert them back to lists after loading? or should I change the way I save my lists into a file.Please note that I don't want to use Pickle.
Thanks
EDIT: my problem with pickle is that I have to add my lists step by step in different part of the code.Thus, I don't have all the lists at once so I can pickle them. This is the problem that I had.It gives me wrong answer, I guess it is because pickle requires all the info in one place and adds them to file at once. (?)
I have only integers in my lists.
A:
If your data is only a list whose items are basic types (e.g. str, unicode, int, float) and lists or dicts whose elements are etc etc, then you can use json; this is portable across languages (is that your problem with pickle?).
Update after question edited """my problem with pickle is that I have to add my lists step by step in different part of the code"""
Have you considered gathering the lists to be pickled as you find them and then pickling all of them at once at the end? Same applies with json etc. All you need is a container to keep your lists in. You can make this look nicer by putting it in a class e.g.
class Preserver(object):
def __init__(self):
self._bottle = []
def add(self, an_object):
self._bottle.append(an_object)
def preserve(self, filepath):
# code using pickle or json to push self._bottle
# out to a file named "filepath"
A:
If you trust the input, use read the file in and use eval:
>>> a_list = [1, 3, 5]
>>> with open('test.txt', 'w') as f:
... f.write(str(a_list))
...
>>> with open('test.txt') as f:
... read_list = eval(f.readlines()[0])
...
>>> read_list
[1, 3, 5]
You could also use ast.literal_eval (python 2.6+) which is safer to use than my eval recommendation.
From the docs:
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.
And for example:
>>> import ast
>>> a_list = [1, 3, 5]
>>> with open('test.txt', 'w') as f:
... f.write(repr(a_list))
...
>>> with open('test.txt') as f:
... read_list = ast.literal_eval(f.readlines()[0])
...
>>> read_list
[1, 3, 5]
A:
You should try pyyaml added bonus it is really human readable text file.
| Alternate ways of saving a list into a file in Python | I am trying to a save a list into a file in a way that when I load and read the file again I get my lists as they are. In other words,the datatype doesn't change while saving and loading. Because right now, I use "write" to save my list into a file, and when I try to load it back into memory I get strings rather than real lists. is there a way to convert them back to lists after loading? or should I change the way I save my lists into a file.Please note that I don't want to use Pickle.
Thanks
EDIT: my problem with pickle is that I have to add my lists step by step in different part of the code.Thus, I don't have all the lists at once so I can pickle them. This is the problem that I had.It gives me wrong answer, I guess it is because pickle requires all the info in one place and adds them to file at once. (?)
I have only integers in my lists.
| [
"If your data is only a list whose items are basic types (e.g. str, unicode, int, float) and lists or dicts whose elements are etc etc, then you can use json; this is portable across languages (is that your problem with pickle?).\nUpdate after question edited \"\"\"my problem with pickle is that I have to add my li... | [
4,
1,
0
] | [] | [] | [
"file",
"list",
"python"
] | stackoverflow_0003868675_file_list_python.txt |
Q:
Python: Check when a cmd command completes its job
When I execute a python script using subprocess.Popen(script, shell=True) in another python script, is it possible to alert python when the script completes running before executing other functions?
On a side note, can I get real-time output of the executed python script?
I can only get output from it doing command>output.txt but that's only after the whole process ends. stdout does not grep any ouput.
A:
When you create a subprocess with Popen, it returns a subprocess.Popen object that has several methods for accessing subprocess status and data:
You can use poll() to determine whether a subprocess has finished. None indicates that the process has ended.
Output from a script while its running can be retrieved with communicate().
You can combine these two to create a script that monitors output from a subprocess and waits until its ready as follows:
import subprocess
p = subprocess.Popen((["python", "script.py"]), stdout=subprocess.PIPE)
while p.poll() is None:
(stdout, stderr) = p.communicate()
print stdout
A:
You want to wait for the Popen to end? have you tried simply this:
popen = subprocess.Popen(script, shell=True)
popen.wait()
Have you considered using the external python script importing it as a module instead of spawning a subprocess?
As for the real-time output: try python -u ...
| Python: Check when a cmd command completes its job | When I execute a python script using subprocess.Popen(script, shell=True) in another python script, is it possible to alert python when the script completes running before executing other functions?
On a side note, can I get real-time output of the executed python script?
I can only get output from it doing command>output.txt but that's only after the whole process ends. stdout does not grep any ouput.
| [
"When you create a subprocess with Popen, it returns a subprocess.Popen object that has several methods for accessing subprocess status and data:\n\nYou can use poll() to determine whether a subprocess has finished. None indicates that the process has ended.\nOutput from a script while its running can be retrieved ... | [
3,
1
] | [] | [] | [
"python",
"real_time"
] | stackoverflow_0003871209_python_real_time.txt |
Q:
Python's StringIO for Clojure
Is there something equivalent to Python's StingIO for Clojure?
I'm trying to write a report generating/literate programming system similar to Sweave and Pweave for Clojure. I'm currently using a temp file, but I'd prefer using something similar to StringIO.
A:
with-out-str is pretty handy.
(let [foo (with-out-str (println "Hello world!"))]
foo)
More documentation here
A:
java.io.StringWriter: http://download.oracle.com/javase/6/docs/api/java/io/StringWriter.html
| Python's StringIO for Clojure | Is there something equivalent to Python's StingIO for Clojure?
I'm trying to write a report generating/literate programming system similar to Sweave and Pweave for Clojure. I'm currently using a temp file, but I'd prefer using something similar to StringIO.
| [
"with-out-str is pretty handy.\n(let [foo (with-out-str (println \"Hello world!\"))] \n foo)\n\nMore documentation here\n",
"java.io.StringWriter: http://download.oracle.com/javase/6/docs/api/java/io/StringWriter.html\n"
] | [
5,
2
] | [] | [] | [
"clojure",
"python",
"stringio"
] | stackoverflow_0003863921_clojure_python_stringio.txt |
Q:
Django admin site: how to create a single page for global settings?
I would like to create a single page in the admin site of django where I can change some global variables of the website (title of the website, items in the navigation menu, etc). At the moment I have them coded as context processors but I would like to make them editable. Something similar to what happens in WordPress.
Is this possible?
I can store the data in the databse, but can I have a link in the admin site that goes straight to the first document record and doesnt allow the creation of multiple records (they wouldnt make sense)
Instead of creating a model in the database, would it be possible to change some context_processor from the admin site (I think this would be best)
A:
django-preferences does exactly what you are looking for. The implementation is a bit hacky (particularly the setting of __module__ on the model class to trick Django into thinking it was loaded from a different app), but it works.
A:
This sounds like what the sites framework is intended to help with.
http://docs.djangoproject.com/en/stable/ref/contrib/sites/
"It’s a hook for associating objects and functionality to particular Web sites, and it’s a holding place for the domain names and “verbose” names of your Django-powered sites."
The docs make it sound like it's only good for multiple sites, but it's a great place to put stuff in a single-site-per-django model too.
A:
There's an app called django-values that allows you storing of specific settings in the database.
| Django admin site: how to create a single page for global settings? | I would like to create a single page in the admin site of django where I can change some global variables of the website (title of the website, items in the navigation menu, etc). At the moment I have them coded as context processors but I would like to make them editable. Something similar to what happens in WordPress.
Is this possible?
I can store the data in the databse, but can I have a link in the admin site that goes straight to the first document record and doesnt allow the creation of multiple records (they wouldnt make sense)
Instead of creating a model in the database, would it be possible to change some context_processor from the admin site (I think this would be best)
| [
"django-preferences does exactly what you are looking for. The implementation is a bit hacky (particularly the setting of __module__ on the model class to trick Django into thinking it was loaded from a different app), but it works.\n",
"This sounds like what the sites framework is intended to help with.\nhttp://... | [
5,
3,
2
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0003868939_django_django_admin_django_forms_python.txt |
Q:
Parsing facebook oauth access_token string
Facebook returns access tokens in the form of a string:
'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375'
Is there a way to parse the access_token without using regex? I'm afraid using regex would be unaccurate since I don't know what FB uses as access tokens
I'm getting the result like this:
result=urlfetch.fetch(url="https://graph.facebook.com/oauth/access_token",payload=payload,method=urlfetch.POST)
result2=result.content
A:
Facebook access_token and expires are returned as key=value pairs. One way to parse them is to use the parse_qs function from the urlparse module.
>>> import urlparse
>>> s = 'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375'
>>> urlparse.parse_qs(s)
{'access_token': ['159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw'], 'expires': ['4375']}
>>>
There is also parse_qsl should you wish to get the values as a list of tuples.
>>> urlparse.parse_qsl(s)
[('access_token', '159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw'), ('expires', '4375')]
>>> dict(urlparse.parse_qsl(s)).get('access_token')
'159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw'
>>>
| Parsing facebook oauth access_token string | Facebook returns access tokens in the form of a string:
'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375'
Is there a way to parse the access_token without using regex? I'm afraid using regex would be unaccurate since I don't know what FB uses as access tokens
I'm getting the result like this:
result=urlfetch.fetch(url="https://graph.facebook.com/oauth/access_token",payload=payload,method=urlfetch.POST)
result2=result.content
| [
"Facebook access_token and expires are returned as key=value pairs. One way to parse them is to use the parse_qs function from the urlparse module. \n>>> import urlparse\n>>> s = 'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375'\n>>> urlpars... | [
2
] | [] | [] | [
"facebook",
"google_app_engine",
"oauth",
"python",
"regex"
] | stackoverflow_0003872648_facebook_google_app_engine_oauth_python_regex.txt |
Q:
How to update status with myspace python api
I'm using myspace python api to post update status, but its return 401, Can't figure it out ,How to deal with that.
A:
HTTP 401 status code suggests that you need some credentials to perform that POST operation.
| How to update status with myspace python api | I'm using myspace python api to post update status, but its return 401, Can't figure it out ,How to deal with that.
| [
"HTTP 401 status code suggests that you need some credentials to perform that POST operation.\n"
] | [
1
] | [] | [] | [
"api",
"myspace",
"python"
] | stackoverflow_0003872894_api_myspace_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.