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:
What's the most pythonic way of normalizing lineends in a string?
Given a text-string of unknown source, how does one best rewrite it to have a known lineend-convention?
I usually do:
lines = text.splitlines()
text = '\n'.join(lines)
... but this doesn't handle "mixed" text-files of utterly confused conventions (Yes, they still exist!).
Edit
The oneliner of what I'm doing is of course:
'\n'.join(text.splitlines())
... that's not what I'm asking about.
The total number of lines should be the same afterwards, so no stripping of empty lines.
Testcases
Splitting
'a\nb\n\nc\nd'
'a\r\nb\r\n\r\nc\r\nd'
'a\rb\r\rc\rd'
'a\rb\n\rc\rd'
'a\rb\r\nc\nd'
'a\nb\r\nc\rd'
.. should all result in 5 lines. In a mixed context, splitlines assumes that '\r\n' is a single logical newline, leading to 4 lines for the last two testcases.
Hm, a mixed context that contains '\r\n' can be detected by comparing the result of splitlines() and split('\n'), and/or split('\r')...
A:
mixed.replace('\r\n', '\n').replace('\r', '\n')
should handle all possible variants.
A:
... but this doesn't handle "mixed" text-files of utterly confused conventions (Yes, they still exist!)
Actually it should work fine:
>>> s = 'hello world\nline 1\r\nline 2'
>>> s.splitlines()
['hello world', 'line 1', 'line 2']
>>> '\n'.join(s.splitlines())
'hello world\nline 1\nline 2'
What version of Python are you using?
EDIT: I still don't see how splitlines() is not working for you:
>>> s = '''\
... First line, with LF\n\
... Second line, with CR\r\
... Third line, with CRLF\r\n\
... Two blank lines with LFs\n\
... \n\
... \n\
... Two blank lines with CRs\r\
... \r\
... \r\
... Two blank lines with CRLFs\r\n\
... \r\n\
... \r\n\
... Three blank lines with a jumble of things:\r\n\
... \r\
... \r\n\
... \n\
... End without a newline.'''
>>> s.splitlines()
['First line, with LF', 'Second line, with CR', 'Third line, with CRLF', 'Two blank lines with LFs', '', '', 'Two blank lines with CRs', '', '', 'Two blank lines with CRLFs', '', '', 'Three blank lines with a jumble of things:', '', '', '', 'End without a newline.']
>>> print '\n'.join(s.splitlines())
First line, with LF
Second line, with CR
Third line, with CRLF
Two blank lines with LFs
Two blank lines with CRs
Two blank lines with CRLFs
Three blank lines with a jumble of things:
End without a newline.
As far as I know splitlines() doesn't split the list twice or anything.
Can you paste a sample of the kind of input that's giving you trouble?
A:
Are there even more convetions than \r\n\ and \n? Simply replacing \r\n is enough if you dont want lines.
only_newlines = mixed.replace('\r\n','\n')
|
What's the most pythonic way of normalizing lineends in a string?
|
Given a text-string of unknown source, how does one best rewrite it to have a known lineend-convention?
I usually do:
lines = text.splitlines()
text = '\n'.join(lines)
... but this doesn't handle "mixed" text-files of utterly confused conventions (Yes, they still exist!).
Edit
The oneliner of what I'm doing is of course:
'\n'.join(text.splitlines())
... that's not what I'm asking about.
The total number of lines should be the same afterwards, so no stripping of empty lines.
Testcases
Splitting
'a\nb\n\nc\nd'
'a\r\nb\r\n\r\nc\r\nd'
'a\rb\r\rc\rd'
'a\rb\n\rc\rd'
'a\rb\r\nc\nd'
'a\nb\r\nc\rd'
.. should all result in 5 lines. In a mixed context, splitlines assumes that '\r\n' is a single logical newline, leading to 4 lines for the last two testcases.
Hm, a mixed context that contains '\r\n' can be detected by comparing the result of splitlines() and split('\n'), and/or split('\r')...
|
[
"mixed.replace('\\r\\n', '\\n').replace('\\r', '\\n')\n\nshould handle all possible variants.\n",
"\n... but this doesn't handle \"mixed\" text-files of utterly confused conventions (Yes, they still exist!)\n\nActually it should work fine:\n>>> s = 'hello world\\nline 1\\r\\nline 2'\n\n>>> s.splitlines()\n['hello world', 'line 1', 'line 2']\n\n>>> '\\n'.join(s.splitlines())\n'hello world\\nline 1\\nline 2'\n\nWhat version of Python are you using?\nEDIT: I still don't see how splitlines() is not working for you:\n>>> s = '''\\\n... First line, with LF\\n\\\n... Second line, with CR\\r\\\n... Third line, with CRLF\\r\\n\\\n... Two blank lines with LFs\\n\\\n... \\n\\\n... \\n\\\n... Two blank lines with CRs\\r\\\n... \\r\\\n... \\r\\\n... Two blank lines with CRLFs\\r\\n\\\n... \\r\\n\\\n... \\r\\n\\\n... Three blank lines with a jumble of things:\\r\\n\\\n... \\r\\\n... \\r\\n\\\n... \\n\\\n... End without a newline.'''\n\n>>> s.splitlines()\n['First line, with LF', 'Second line, with CR', 'Third line, with CRLF', 'Two blank lines with LFs', '', '', 'Two blank lines with CRs', '', '', 'Two blank lines with CRLFs', '', '', 'Three blank lines with a jumble of things:', '', '', '', 'End without a newline.']\n\n>>> print '\\n'.join(s.splitlines())\nFirst line, with LF\nSecond line, with CR\nThird line, with CRLF\nTwo blank lines with LFs\n\n\nTwo blank lines with CRs\n\n\nTwo blank lines with CRLFs\n\n\nThree blank lines with a jumble of things:\n\n\n\nEnd without a newline.\n\nAs far as I know splitlines() doesn't split the list twice or anything.\nCan you paste a sample of the kind of input that's giving you trouble?\n",
"Are there even more convetions than \\r\\n\\ and \\n? Simply replacing \\r\\n is enough if you dont want lines. \nonly_newlines = mixed.replace('\\r\\n','\\n')\n\n"
] |
[
17,
7,
0
] |
[] |
[] |
[
"line_breaks",
"newline",
"python"
] |
stackoverflow_0001749466_line_breaks_newline_python.txt
|
Q:
replace or remove one null (python)
I would like to remove one null byte in a string, and sometime replace it with another char.
Like that :
string = "41 00 36 00 36 00 00 00 57 00 46 00 42 00 41 00 61 00 62 00 73 00 20 00 36 00"
i was thinking about using random and replace, but replace always start by the first one:
replace("00","B",1)
So it's not random.
Any help will be appreciated !
EDIT: i meant null by 00, and i made a mistake:
string = "41 00 36 00 36 00 00 00 57 00 46 00 42 00 41 00 61 00 62 00 73 00 20 00 36 00"
Thanks
A:
Not only that, but 00 isn't "a null" by any stretch of the imagination -- it's a 2-characters string. You appear to silently assume that your string is made up of substrings each of two hex digits, and any string operation you perform will have no idea about this little private convention of yours -- if you do manage to "replace a random 00" it might well be one made up of the second digit of, say, "F0", followed by the first digit of, say, "03": not what you probably mean!
A logically cleaner approach is to first split your string into the 2-digits pieces, thus making your unspoken assumption clear and explicit instead:
>>> string = "4100360036000000570046004200410061006200730020003600"
>>> pieces = [string[i:i+2] for i in range(0, len(string), 2)]
>>> pieces
['41', '00', '36', '00', '36', '00', '00', '00', '57', '00', '46', '00', '42', '00', '41', '00', '61', '00', '62', '00', '73', '00', '20', '00', '36', '00']
>>>
Yes, this can be made much more concise, but I'm striving for clarity and conceptual sharpness here!-).
Now locate all the '00' digits:
>>> where0s = [i for i in range(len(pieces)) if pieces[i] == '00']
>>> where0s
[1, 3, 5, 6, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]
(again, easy to make compact, but this is the clearest way;-).
Now get a random choice out of the where0s and either remove it, or replace it with, for example, 'BA', then rejoin the string:
>>> import random
>>> pickone = random.choice(where0s)
>>> pickone
25
>>> # if replacing:
...
>>> pieces[pickone] = 'BA'
>>> ''.join(pieces)
'41003600360000005700460042004100610062007300200036BA'
>>> # if removing:
...
>>> del pieces[pickone]
>>> ''.join(pieces)
'41003600360000005700460042004100610062007300200036'
>>>
If this is indeed the exact operation you want to perform, but you want more conciseness and speed rather than this totally-spelled-out clarity, we can of course keep developing the idea!
A:
Ugly code tested in Python 3.1.1
import random
s = "a00b00c00d00e00f00g"
s1 = s.split("00")
i = random.randint(1,s.count("00"))
s2 = "00".join(s1[:i])
s3 = "00".join(s1[i:])
print (s2+"EE"+s3)
A:
This solution grabs all possible locations of "00" for even values of the string and chooses one at random. It should solve your problem:
from random import choice
string = "4100360036000000570046004200410061006200730020003600"
zeroes = []
for i, s in enumerate(string):
if i % 2 == 0 and i < len(string) - 1 and string[i:i + 2] == "00":
zeroes.append(i)
c = choice(zeroes)
string = string[:c] + '0B' + string[c + 2:]
print string
A:
You cannot replace bytes in a string. Instead, you want to use an array for this.
import array
s = "4100360036000000570046004200410061006200730020003600"
a = array.array('c',s)
b = array.array('c',"B") # make a one character array containing B
print a
a[6] = b[0]
print b
Of course, if you intended these to be the hex codes for characters then you would need to use the hex() and chr() functions to convert between integers and strings of hex characters.
|
replace or remove one null (python)
|
I would like to remove one null byte in a string, and sometime replace it with another char.
Like that :
string = "41 00 36 00 36 00 00 00 57 00 46 00 42 00 41 00 61 00 62 00 73 00 20 00 36 00"
i was thinking about using random and replace, but replace always start by the first one:
replace("00","B",1)
So it's not random.
Any help will be appreciated !
EDIT: i meant null by 00, and i made a mistake:
string = "41 00 36 00 36 00 00 00 57 00 46 00 42 00 41 00 61 00 62 00 73 00 20 00 36 00"
Thanks
|
[
"Not only that, but 00 isn't \"a null\" by any stretch of the imagination -- it's a 2-characters string. You appear to silently assume that your string is made up of substrings each of two hex digits, and any string operation you perform will have no idea about this little private convention of yours -- if you do manage to \"replace a random 00\" it might well be one made up of the second digit of, say, \"F0\", followed by the first digit of, say, \"03\": not what you probably mean!\nA logically cleaner approach is to first split your string into the 2-digits pieces, thus making your unspoken assumption clear and explicit instead:\n>>> string = \"4100360036000000570046004200410061006200730020003600\"\n>>> pieces = [string[i:i+2] for i in range(0, len(string), 2)]\n>>> pieces\n['41', '00', '36', '00', '36', '00', '00', '00', '57', '00', '46', '00', '42', '00', '41', '00', '61', '00', '62', '00', '73', '00', '20', '00', '36', '00']\n>>> \n\nYes, this can be made much more concise, but I'm striving for clarity and conceptual sharpness here!-).\nNow locate all the '00' digits:\n>>> where0s = [i for i in range(len(pieces)) if pieces[i] == '00']\n>>> where0s\n[1, 3, 5, 6, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]\n\n(again, easy to make compact, but this is the clearest way;-).\nNow get a random choice out of the where0s and either remove it, or replace it with, for example, 'BA', then rejoin the string:\n>>> import random\n>>> pickone = random.choice(where0s)\n>>> pickone\n25\n>>> # if replacing:\n... \n>>> pieces[pickone] = 'BA'\n>>> ''.join(pieces)\n'41003600360000005700460042004100610062007300200036BA'\n>>> # if removing:\n... \n>>> del pieces[pickone]\n>>> ''.join(pieces)\n'41003600360000005700460042004100610062007300200036'\n>>> \n\nIf this is indeed the exact operation you want to perform, but you want more conciseness and speed rather than this totally-spelled-out clarity, we can of course keep developing the idea!\n",
"Ugly code tested in Python 3.1.1\nimport random\ns = \"a00b00c00d00e00f00g\"\ns1 = s.split(\"00\")\ni = random.randint(1,s.count(\"00\"))\ns2 = \"00\".join(s1[:i])\ns3 = \"00\".join(s1[i:])\nprint (s2+\"EE\"+s3)\n\n",
"This solution grabs all possible locations of \"00\" for even values of the string and chooses one at random. It should solve your problem:\nfrom random import choice\n\nstring = \"4100360036000000570046004200410061006200730020003600\"\n\nzeroes = []\n\nfor i, s in enumerate(string):\n if i % 2 == 0 and i < len(string) - 1 and string[i:i + 2] == \"00\":\n zeroes.append(i)\n\nc = choice(zeroes)\nstring = string[:c] + '0B' + string[c + 2:]\nprint string\n\n",
"You cannot replace bytes in a string. Instead, you want to use an array for this.\nimport array\ns = \"4100360036000000570046004200410061006200730020003600\"\na = array.array('c',s)\nb = array.array('c',\"B\") # make a one character array containing B\nprint a\na[6] = b[0]\nprint b\n\nOf course, if you intended these to be the hex codes for characters then you would need to use the hex() and chr() functions to convert between integers and strings of hex characters.\n"
] |
[
7,
1,
0,
0
] |
[] |
[] |
[
"python",
"random",
"replace"
] |
stackoverflow_0001749827_python_random_replace.txt
|
Q:
use random functions (python)
I wonder if we can do that in python, let's suppose we have 3 differents functions to processing datas
like this:
def main():
def process(data):
.....
def process1(data):
.....
def process2(data):
.....
def run():
test = choice([process,process1,process2])
test(data)
run()
main()
Can we choice one random function to process the data ?
If yes, is this a good way to do so ?
Thanks !
A:
Excellent approach (net of some oversimplification in your skeleton code). Since you ask for an example:
import random
def main():
def process(data):
return data + [0]
def process1(data):
return data + [9]
def process2(data):
return data + [7]
def run(data):
test = random.choice([process,process1,process2])
print test(data)
for i in range(7):
run([1, 2, 3])
main()
I've made it loop 7 times just to show that each choice is indeed random, i.e., a typical output might be something like:
[1, 2, 3, 7]
[1, 2, 3, 0]
[1, 2, 3, 0]
[1, 2, 3, 7]
[1, 2, 3, 0]
[1, 2, 3, 9]
[1, 2, 3, 9]
(changing randomly each and every time, of course;-).
A:
Sure is!
That the nice thing in Python, functions are first class objects and can be referenced in such an easy fashion.
The implication is that all three methods have the same expectation with regards to arguments passed to them. (This probably goes without saying).
A:
Just use the random number module in python.
random.choice(seq)
This will give you a random item from the sequence.
http://docs.python.org/library/random.html
A:
Your code will work just like you wrote it, if you add this to the top:
from random import choice
Or, I think it would be slightly better to rewrite your code like so:
import random
def main():
def process(data):
.....
def process1(data):
.....
def process2(data):
.....
def run():
test = random.choice([process,process1,process2])
test(data)
run()
main()
Seeing random.choice() in your code makes it quite clear what is going on!
|
use random functions (python)
|
I wonder if we can do that in python, let's suppose we have 3 differents functions to processing datas
like this:
def main():
def process(data):
.....
def process1(data):
.....
def process2(data):
.....
def run():
test = choice([process,process1,process2])
test(data)
run()
main()
Can we choice one random function to process the data ?
If yes, is this a good way to do so ?
Thanks !
|
[
"Excellent approach (net of some oversimplification in your skeleton code). Since you ask for an example:\nimport random\n\ndef main():\n def process(data):\n return data + [0]\n def process1(data):\n return data + [9]\n def process2(data):\n return data + [7]\n def run(data):\n test = random.choice([process,process1,process2])\n print test(data)\n for i in range(7):\n run([1, 2, 3])\n\nmain()\n\nI've made it loop 7 times just to show that each choice is indeed random, i.e., a typical output might be something like:\n[1, 2, 3, 7]\n[1, 2, 3, 0]\n[1, 2, 3, 0]\n[1, 2, 3, 7]\n[1, 2, 3, 0]\n[1, 2, 3, 9]\n[1, 2, 3, 9]\n\n(changing randomly each and every time, of course;-).\n",
"Sure is!\nThat the nice thing in Python, functions are first class objects and can be referenced in such an easy fashion.\nThe implication is that all three methods have the same expectation with regards to arguments passed to them. (This probably goes without saying).\n",
"Just use the random number module in python.\nrandom.choice(seq)\n\nThis will give you a random item from the sequence.\nhttp://docs.python.org/library/random.html\n",
"Your code will work just like you wrote it, if you add this to the top:\nfrom random import choice\n\nOr, I think it would be slightly better to rewrite your code like so:\nimport random\n\ndef main():\n def process(data):\n .....\n def process1(data):\n .....\n def process2(data):\n .....\n def run():\n test = random.choice([process,process1,process2])\n test(data)\n run()\n\nmain()\n\nSeeing random.choice() in your code makes it quite clear what is going on!\n"
] |
[
4,
3,
1,
0
] |
[] |
[] |
[
"function",
"python",
"random"
] |
stackoverflow_0001750480_function_python_random.txt
|
Q:
Jython 2.1 __getattr__
I am trying to implement a wrapper/proxy class for a java object (baseClient) in jython v2.1. Everything seems to be working ok except when the following statement is encountered:
if __client != None # __client is an instance of the ClientProxy class
raise AttributeError(attr) is called in __getattr__(), because self.__baseClient doesn't have __ne__ attribute.
It's important to mention that I cannot upgrade because jython is a part of a system. Is there a way to get around this issue?
class ClientProxy:
def __init__(self, baseClient):
self.__baseClient = baseClient
self.__initialised = 1
def __getattr__(self, attr):
if not self.__dict__.has_key('_ClientProxy__initialised'):
raise AttributeError(attr)
else:
if hasattr(self.__baseClient, attr):
return getattr(self.__baseClient, attr)
else:
raise AttributeError(attr)
def __setattr__(self, attr, val):
if not self.__dict__.has_key('_ClientProxy__initialised'):
self.__dict__[attr] = val
return
if hasattr(self.__baseClient, attr):
self.__baseClient.__setattr__(attr, val)
else:
self.__dict__[attr] = val
Thanks a lot!
A:
if __client != None:
For testing against specific instances such as None, it's idiomatic to use the identity operator:
if __client is not None:
This will avoid the problem of calling comparators.
However, the fact that __getattr__ raises AttributeError should not be a problem. The comparator should call getattr speculatively for __cmp__ (__ne__ first on newer Pythons), and if it gets an AttributeError it is supposed to silently swallow it and fall back to identity comparison instead. Why does the AttributeError cause a problem in your case?
|
Jython 2.1 __getattr__
|
I am trying to implement a wrapper/proxy class for a java object (baseClient) in jython v2.1. Everything seems to be working ok except when the following statement is encountered:
if __client != None # __client is an instance of the ClientProxy class
raise AttributeError(attr) is called in __getattr__(), because self.__baseClient doesn't have __ne__ attribute.
It's important to mention that I cannot upgrade because jython is a part of a system. Is there a way to get around this issue?
class ClientProxy:
def __init__(self, baseClient):
self.__baseClient = baseClient
self.__initialised = 1
def __getattr__(self, attr):
if not self.__dict__.has_key('_ClientProxy__initialised'):
raise AttributeError(attr)
else:
if hasattr(self.__baseClient, attr):
return getattr(self.__baseClient, attr)
else:
raise AttributeError(attr)
def __setattr__(self, attr, val):
if not self.__dict__.has_key('_ClientProxy__initialised'):
self.__dict__[attr] = val
return
if hasattr(self.__baseClient, attr):
self.__baseClient.__setattr__(attr, val)
else:
self.__dict__[attr] = val
Thanks a lot!
|
[
"if __client != None:\n\nFor testing against specific instances such as None, it's idiomatic to use the identity operator:\nif __client is not None:\n\nThis will avoid the problem of calling comparators.\nHowever, the fact that __getattr__ raises AttributeError should not be a problem. The comparator should call getattr speculatively for __cmp__ (__ne__ first on newer Pythons), and if it gets an AttributeError it is supposed to silently swallow it and fall back to identity comparison instead. Why does the AttributeError cause a problem in your case?\n"
] |
[
0
] |
[] |
[] |
[
"getattr",
"jython",
"python",
"setattr",
"word_wrap"
] |
stackoverflow_0001750392_getattr_jython_python_setattr_word_wrap.txt
|
Q:
PyQt: No such slot
I am starting to learn Qt4 and Python, following along some tutorial i found on the interwebs. I have the following two files:
lcdrange.py:
from PyQt4 import QtGui, QtCore
class LCDRange(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
lcd = QtGui.QLCDNumber(2)
self.slider = QtGui.QSlider()
self.slider.setRange(0,99)
self.slider.setValue(0)
self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'),
lcd, QtCore.SLOT('display(int)'))
self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'),
self, QtCore.SIGNAL('valueChanged(int)'))
layout = QtGui.QVBoxLayout()
layout.addWidget(lcd)
layout.addWidget(self.slider)
self.setLayout(layout)
def value(self):
self.slider.value()
def setValue(self,value):
self.slider.setValue(value)
main.py:
import sys
from PyQt4 import QtGui, QtCore
from lcdrange import LCDRange
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
quit = QtGui.QPushButton('Quit')
quit.setFont(QtGui.QFont('Times', 18, QtGui.QFont.Bold))
self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()'))
grid = QtGui.QGridLayout()
previousRange = None
for row in range(0,3):
for column in range(0,3):
lcdRange = LCDRange()
grid.addWidget(lcdRange, row, column)
if not previousRange == None:
self.connect(lcdRange, QtCore.SIGNAL('valueChanged(int)'),
previousRange, QtCore.SLOT('setValue(int)'))
previousRange = lcdRange
layout = QtGui.QVBoxLayout()
layout.addWidget(quit)
layout.addLayout(grid)
self.setLayout(layout)
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
When i run this i get the following errors:
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
I've read that PyQt slots are nothing more than methods, which i have defined, so what am i doing wrong?
I am also learning Qt4 with Ruby which is where this code originates from, i translated it from Ruby to Python. In the Ruby version the LCDRange class is defined as this:
class LCDRange < Qt::Widget
signals 'valueChanged(int)'
slots 'setValue(int)'
def initialize(parent = nil)
...
So my guess was that i have to somehow declare the existence of the custom slot?
A:
Try this:
self.connect(lcdRange, QtCore.SIGNAL('valueChanged'), previousRange.setValue)
What's the difference?
The PyQt documentation has a section about SIGNALS/SLOTS in PyQt, they work a little differently.
SIGNAL
SIGNAL('valueChanged') is something called a short-circuit signal. They work only for Python-to-Python methods, but they are faster and easier to implement.
SLOT
If you have a python slot, you can specify it just by tipping the method: previousRange.setValue. This works for all methods accessible by Python.
If your slots should be accessible like C++ Qt slots, as you tried in your code, you have to use a special syntax. You can find information about pyqtSignature decorator on the PyQt website.
A:
you forgot to put
@Qt.pyqtSlot()
above method you are using as slot.
For example your code should look like this
@Qt.pyqtSlot('const QPoint&')
def setValue(self,value):
self.slider.setValue(value)
Here is one good page about pyqt slot decorator:
click :-)
Bye
A:
NOTE
The "text" within the SIGNAL must match the c++ API documentation.
# This will work - its IDENTICAL to the documentation
QtCore.SIGNAL('customContextMenuRequested(const QPoint&)')
# this wont
QtCore.SIGNAL('customContextMenuRequested(QPoint&)')
# and this wont
QtCore.SIGNAL('customContextMenuRequested(const QPoint)')
# Spot the bug
QtCore.SIGNAL('selectionChanged(const QItemSelection,const QItemSelection&)')
^ < missing &
|
PyQt: No such slot
|
I am starting to learn Qt4 and Python, following along some tutorial i found on the interwebs. I have the following two files:
lcdrange.py:
from PyQt4 import QtGui, QtCore
class LCDRange(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
lcd = QtGui.QLCDNumber(2)
self.slider = QtGui.QSlider()
self.slider.setRange(0,99)
self.slider.setValue(0)
self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'),
lcd, QtCore.SLOT('display(int)'))
self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'),
self, QtCore.SIGNAL('valueChanged(int)'))
layout = QtGui.QVBoxLayout()
layout.addWidget(lcd)
layout.addWidget(self.slider)
self.setLayout(layout)
def value(self):
self.slider.value()
def setValue(self,value):
self.slider.setValue(value)
main.py:
import sys
from PyQt4 import QtGui, QtCore
from lcdrange import LCDRange
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
quit = QtGui.QPushButton('Quit')
quit.setFont(QtGui.QFont('Times', 18, QtGui.QFont.Bold))
self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()'))
grid = QtGui.QGridLayout()
previousRange = None
for row in range(0,3):
for column in range(0,3):
lcdRange = LCDRange()
grid.addWidget(lcdRange, row, column)
if not previousRange == None:
self.connect(lcdRange, QtCore.SIGNAL('valueChanged(int)'),
previousRange, QtCore.SLOT('setValue(int)'))
previousRange = lcdRange
layout = QtGui.QVBoxLayout()
layout.addWidget(quit)
layout.addLayout(grid)
self.setLayout(layout)
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
When i run this i get the following errors:
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
I've read that PyQt slots are nothing more than methods, which i have defined, so what am i doing wrong?
I am also learning Qt4 with Ruby which is where this code originates from, i translated it from Ruby to Python. In the Ruby version the LCDRange class is defined as this:
class LCDRange < Qt::Widget
signals 'valueChanged(int)'
slots 'setValue(int)'
def initialize(parent = nil)
...
So my guess was that i have to somehow declare the existence of the custom slot?
|
[
"Try this:\nself.connect(lcdRange, QtCore.SIGNAL('valueChanged'), previousRange.setValue)\n\nWhat's the difference?\nThe PyQt documentation has a section about SIGNALS/SLOTS in PyQt, they work a little differently.\nSIGNAL\nSIGNAL('valueChanged') is something called a short-circuit signal. They work only for Python-to-Python methods, but they are faster and easier to implement.\nSLOT\nIf you have a python slot, you can specify it just by tipping the method: previousRange.setValue. This works for all methods accessible by Python.\nIf your slots should be accessible like C++ Qt slots, as you tried in your code, you have to use a special syntax. You can find information about pyqtSignature decorator on the PyQt website.\n",
"you forgot to put \n\n@Qt.pyqtSlot()\n\nabove method you are using as slot. \nFor example your code should look like this\n\n@Qt.pyqtSlot('const QPoint&')\ndef setValue(self,value):\n self.slider.setValue(value)\n\nHere is one good page about pyqt slot decorator:\nclick :-)\nBye\n",
"NOTE\nThe \"text\" within the SIGNAL must match the c++ API documentation. \n# This will work - its IDENTICAL to the documentation \nQtCore.SIGNAL('customContextMenuRequested(const QPoint&)')\n\n# this wont\nQtCore.SIGNAL('customContextMenuRequested(QPoint&)')\n\n# and this wont\nQtCore.SIGNAL('customContextMenuRequested(const QPoint)')\n\n# Spot the bug \nQtCore.SIGNAL('selectionChanged(const QItemSelection,const QItemSelection&)')\n ^ < missing &\n\n"
] |
[
7,
1,
0
] |
[] |
[] |
[
"pyqt",
"python",
"qt4",
"ruby"
] |
stackoverflow_0000577824_pyqt_python_qt4_ruby.txt
|
Q:
Making Python Use Code in My Directory (not that in /usr/...)
I am trying to work on a Python library that is already installed on my (Ubuntu) system. I checked out that library, edited some files, and wrote a small script to test my changes. Even though I put my script in the same folder as that of the library, it seems Python is using the installed version instead (the one in /usr/share/pyshared/...).
This is my directory structure:
src
+ my_package
- my_script.py
+ library_package
- lots_of_code
How can I tell Python to use the code in my directory, not the installed one?
A:
You can dictate where python searches for modules using the PYTHONPATH environment variable:
When a module named spam is imported,
the interpreter searches for a file
named spam.py in the current
directory, and then in the list of
directories specified by the
environment variable PYTHONPATH. This
has the same syntax as the shell
variable PATH, that is, a list of
directory names. When PYTHONPATH is
not set, or when the file is not found
there, the search continues in an
installation-dependent default path;
on Unix, this is usually
.:/usr/local/lib/python.
from http://docs.python.org/tutorial/modules.html#the-module-search-path
A:
Lets consider a more general issue. In the /usr/share/pyshared/ there are lots of modules. You wish to override just one of the modules. Say the module name is xyz.py. And it happens to use other modules in /usr/shared/pyshared also.
Say we create $HOME/mylibs and add $HOME to Python's sys.path.
Now wherever we have to use xyz, we do something like
from mylibs import xyz
If we wish to revert back to the original xyz, we try:
import xyz # picks up from /usr/shared/pyshared
I wonder if this kind of approach would be more general. You mask only those modules which you are overriding and keep others in use as usual.
A:
import sys
from os.path import join, dirname, pardir
sys.path.insert(0, join(dirname(__file__), pardir))
This will check the src directory for any python modules, and will look there first.
So even if you have a module with the same name installed elsewhere, this will cause python to load the local one.
sys.path documentation.
A:
Check the complete path that Python uses through sys.path. You should be able to add to the path (in front for precedence).
Of course, you can also use PYTHONPATH environment variable or work-around using .pth files.
A:
It might work if you set the PYTHONPATH environment variable to include that directory, e.g.:
$ cd src
$ export PYTHONPATH=./library_package
$ python my_package/my_script.py
|
Making Python Use Code in My Directory (not that in /usr/...)
|
I am trying to work on a Python library that is already installed on my (Ubuntu) system. I checked out that library, edited some files, and wrote a small script to test my changes. Even though I put my script in the same folder as that of the library, it seems Python is using the installed version instead (the one in /usr/share/pyshared/...).
This is my directory structure:
src
+ my_package
- my_script.py
+ library_package
- lots_of_code
How can I tell Python to use the code in my directory, not the installed one?
|
[
"You can dictate where python searches for modules using the PYTHONPATH environment variable:\n\nWhen a module named spam is imported,\n the interpreter searches for a file\n named spam.py in the current\n directory, and then in the list of\n directories specified by the\n environment variable PYTHONPATH. This\n has the same syntax as the shell\n variable PATH, that is, a list of\n directory names. When PYTHONPATH is\n not set, or when the file is not found\n there, the search continues in an\n installation-dependent default path;\n on Unix, this is usually\n .:/usr/local/lib/python.\n\nfrom http://docs.python.org/tutorial/modules.html#the-module-search-path\n",
"Lets consider a more general issue. In the /usr/share/pyshared/ there are lots of modules. You wish to override just one of the modules. Say the module name is xyz.py. And it happens to use other modules in /usr/shared/pyshared also. \nSay we create $HOME/mylibs and add $HOME to Python's sys.path.\nNow wherever we have to use xyz, we do something like\nfrom mylibs import xyz\n\nIf we wish to revert back to the original xyz, we try:\nimport xyz # picks up from /usr/shared/pyshared \n\nI wonder if this kind of approach would be more general. You mask only those modules which you are overriding and keep others in use as usual. \n",
"import sys\nfrom os.path import join, dirname, pardir\n\nsys.path.insert(0, join(dirname(__file__), pardir))\n\nThis will check the src directory for any python modules, and will look there first.\nSo even if you have a module with the same name installed elsewhere, this will cause python to load the local one. \nsys.path documentation.\n",
"Check the complete path that Python uses through sys.path. You should be able to add to the path (in front for precedence).\nOf course, you can also use PYTHONPATH environment variable or work-around using .pth files.\n",
"It might work if you set the PYTHONPATH environment variable to include that directory, e.g.:\n$ cd src\n$ export PYTHONPATH=./library_package\n$ python my_package/my_script.py\n\n"
] |
[
3,
3,
3,
1,
0
] |
[] |
[] |
[
"path",
"python"
] |
stackoverflow_0001749452_path_python.txt
|
Q:
How do I get something like repeat customers in Django
My models look something like this:
class Customer(models.Model):
name = models.CharField(max_length=100)
class Order(models.Model):
customer = models.ForeignKey(Customer)
date = models.DateField()
total = models.DecimalField(max_digits=5, decimal_places=2)
I then have a queryset of orders:
from datetime import datetime
start_date = datetime(year=2009, month=6, day=1)
end_date = datetime(year=2009, month=11, day=1)
orders = Order.objects.filter(date__lte=end_date).filter(date__gte=start_date)
Now, I want to find out which customers made multiple orders between those times, how many orders they made, and what their average total is. I get the feeling that I should be using Django 1.1's new aggregation features, but I can't really wrap my head around it.
A:
Always base your query around the object in which you are primarily interested in:
repeat_customers = Customer.objects.annotate(order_count=Count('order'))\
.filter(order_count__gt=1)
Then if you want to annotate with their totals (you could alternatively do this in the annotation above, I'm just separating the code for readability):
repeat_customers = repeat_customers.annotate(avg_total=Avg('order__total'))
A:
This would be a good use for Django 1.1's annotate() functionality, which is part of aggregateion. Specifically, you'll probably want to use the values() function.
|
How do I get something like repeat customers in Django
|
My models look something like this:
class Customer(models.Model):
name = models.CharField(max_length=100)
class Order(models.Model):
customer = models.ForeignKey(Customer)
date = models.DateField()
total = models.DecimalField(max_digits=5, decimal_places=2)
I then have a queryset of orders:
from datetime import datetime
start_date = datetime(year=2009, month=6, day=1)
end_date = datetime(year=2009, month=11, day=1)
orders = Order.objects.filter(date__lte=end_date).filter(date__gte=start_date)
Now, I want to find out which customers made multiple orders between those times, how many orders they made, and what their average total is. I get the feeling that I should be using Django 1.1's new aggregation features, but I can't really wrap my head around it.
|
[
"Always base your query around the object in which you are primarily interested in:\nrepeat_customers = Customer.objects.annotate(order_count=Count('order'))\\\n .filter(order_count__gt=1)\n\nThen if you want to annotate with their totals (you could alternatively do this in the annotation above, I'm just separating the code for readability):\nrepeat_customers = repeat_customers.annotate(avg_total=Avg('order__total'))\n\n",
"This would be a good use for Django 1.1's annotate() functionality, which is part of aggregateion. Specifically, you'll probably want to use the values() function.\n"
] |
[
2,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001750806_django_python.txt
|
Q:
mongodb, pymongo querying
I've been browsing through the documentation, but I can't seem to figure out a way to perform a find on my mongodb collection using only a key.
For example, let's suppose this is what's inside my collection
{ 'res1': 10 }
{ 'res2: 20 }
How can I query the collection using only the key 'res1', in order to get 10 ?
A:
Not sure exaclty what you want, so... This is if you want all documents that have key res1 set:
db.collection.find({'res1': { $exists : true }})
And this is if you want all the documents that have key res1 set to 10:
db.collection.find({'res1': 10})
A:
Ah, I guess I'm structuring my data all wrong, I should have something like this:
{ 'name': 'res1',
'value': 10 }
Right?
A:
> db.collection.find({'res1': 10}) # Returns a cursor.
In your case, find_one method will do the needful.
> db.collection.find_one({'res1': 10}) # Returns a document whose value is 10
|
mongodb, pymongo querying
|
I've been browsing through the documentation, but I can't seem to figure out a way to perform a find on my mongodb collection using only a key.
For example, let's suppose this is what's inside my collection
{ 'res1': 10 }
{ 'res2: 20 }
How can I query the collection using only the key 'res1', in order to get 10 ?
|
[
"Not sure exaclty what you want, so... This is if you want all documents that have key res1 set:\ndb.collection.find({'res1': { $exists : true }})\nAnd this is if you want all the documents that have key res1 set to 10:\ndb.collection.find({'res1': 10})\n",
"Ah, I guess I'm structuring my data all wrong, I should have something like this:\n{ 'name': 'res1',\n 'value': 10 }\n\nRight?\n",
"> db.collection.find({'res1': 10}) # Returns a cursor.\n\nIn your case, find_one method will do the needful.\n> db.collection.find_one({'res1': 10}) # Returns a document whose value is 10\n\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"mongodb",
"python"
] |
stackoverflow_0001741379_mongodb_python.txt
|
Q:
Python SOAP server / client
I have a problem with Python and SOAP. I need to create a web service based on SOAP in Python. I read that I can use libraries like soaplib, suds and ZSI. I created a Hello World web service with soaplib, like in documentation (http://trac.optio.webfactional.com/wiki/HelloWorld). The problem is that I cannot make a client for the web service which uses other than soaplib library. I wanted to do the client app using for example suds library in Python.
Did you managed to do an application in Python (for example with suds library) consuming the SOAP web service created with soaplib in Python?
A:
How are you serving the service? soaplib produces a WSGI object, which needs to be served by a webserver. If you are following the helloworld example you link to then you are using CherryPy (a pure python web server) to host the service on your own machine. In the example the port is 7789 (but you can use anything you like). So if you use the example you should first start the script which runs cherrypy - this should stay running and not return to the prompt. When that is running you should be able to access your service at http://localhost:7789/wsdl - you can put that address in a web browser to see if it is working. Soaplib returns the wsdl as long as the url ends in wsdl - so in fact you can do http://localhost:7789/anythingherewsdl.
A:
Are you asking whether it's possible to use (consume) a SOAP web service built with something other than soaplib? That would of course be possible. Suds is good idea for this.
|
Python SOAP server / client
|
I have a problem with Python and SOAP. I need to create a web service based on SOAP in Python. I read that I can use libraries like soaplib, suds and ZSI. I created a Hello World web service with soaplib, like in documentation (http://trac.optio.webfactional.com/wiki/HelloWorld). The problem is that I cannot make a client for the web service which uses other than soaplib library. I wanted to do the client app using for example suds library in Python.
Did you managed to do an application in Python (for example with suds library) consuming the SOAP web service created with soaplib in Python?
|
[
"How are you serving the service? soaplib produces a WSGI object, which needs to be served by a webserver. If you are following the helloworld example you link to then you are using CherryPy (a pure python web server) to host the service on your own machine. In the example the port is 7789 (but you can use anything you like). So if you use the example you should first start the script which runs cherrypy - this should stay running and not return to the prompt. When that is running you should be able to access your service at http://localhost:7789/wsdl - you can put that address in a web browser to see if it is working. Soaplib returns the wsdl as long as the url ends in wsdl - so in fact you can do http://localhost:7789/anythingherewsdl.\n",
"Are you asking whether it's possible to use (consume) a SOAP web service built with something other than soaplib? That would of course be possible. Suds is good idea for this.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"soap",
"web_services"
] |
stackoverflow_0001751027_python_soap_web_services.txt
|
Q:
How to run multiple Tornado processes/threads/frontends?
In the tornado documentation they show how they can have a very large through-put from 4 frontends. I'd like to run an app in the same way, and would like to have the frontends running as daemon processes managed with an init.d script*.
I'm fairly new to Python so don't really know where to start. Currently I'm starting the Tornado server manually in the terminal, passing in a new port number each time.
I've tried using the python-daemon package in conjunction with the lockfile package but the lockfiles that are created don't have the process ids in them and I can't see how to then kill the processes gracefully later on.
I don't really know where to go from here, and the Tornado docs leave a large chunk out regarding deployment.
* If there's a better way to manage the processes so that they can be monitored and managed as a group then please let me know.
A:
Try Supervisor. It's great for managing multiple daemon processes. You configure your applications in the supervisord.conf file and supervisord itself is launched from an init.d script.
A:
I can vouch for Supervisor too. We have been using tornado in production with 4 instances using supervisor and it is working uber smooth
|
How to run multiple Tornado processes/threads/frontends?
|
In the tornado documentation they show how they can have a very large through-put from 4 frontends. I'd like to run an app in the same way, and would like to have the frontends running as daemon processes managed with an init.d script*.
I'm fairly new to Python so don't really know where to start. Currently I'm starting the Tornado server manually in the terminal, passing in a new port number each time.
I've tried using the python-daemon package in conjunction with the lockfile package but the lockfiles that are created don't have the process ids in them and I can't see how to then kill the processes gracefully later on.
I don't really know where to go from here, and the Tornado docs leave a large chunk out regarding deployment.
* If there's a better way to manage the processes so that they can be monitored and managed as a group then please let me know.
|
[
"Try Supervisor. It's great for managing multiple daemon processes. You configure your applications in the supervisord.conf file and supervisord itself is launched from an init.d script.\n",
"I can vouch for Supervisor too. We have been using tornado in production with 4 instances using supervisor and it is working uber smooth\n"
] |
[
6,
1
] |
[] |
[] |
[
"deployment",
"python",
"tornado"
] |
stackoverflow_0001506463_deployment_python_tornado.txt
|
Q:
Basic Comet in Python using just std lib
I'm developing a web interface for an already existing desktop application. I've been looking for a way to allow the server to push content to the browser and ended up reaching Comet.
Navigating through the internet, and most of the questions here, I got answers like twisted, orbited, tornado and most of them even point to java applications like Jetty or StreamHub.
Without going too much deeper in this, I'd like to know is there's a chance to implement Comet-like communication using just standard lib modules like BaseHTTPServer and keep things as simple as possible as I don't need so much power and efficiency.
Note: Jython is a possibility, but I'd like to keep it with as less requirements as possible.
A:
As gs said, just keep the connection open.
Here's an example WSGI app that sends the current time to the client every second:
import time
def application(environ, start_response):
start_response('200 OK', [('content-type', 'text/plain')])
while True:
time.sleep(1.0)
yield time.ctime() + '\n'
if __name__ == '__main__':
from wsgiref.simple_server import make_server
print "Serving on http://localhost:4000..."
make_server('localhost', 4000, application).serve_forever()
If I go to the URL in my browser, I see this:
Mon Oct 05 12:21:26 2009
Mon Oct 05 12:21:27 2009
Mon Oct 05 12:21:28 2009
Mon Oct 05 12:21:29 2009
Mon Oct 05 12:21:30 2009
(...a new line appears every second...)
The problem with this approach is that you can't keep very many connections like this open at the same time. In fact, the wsgiref server is single-threaded, so you can only have one connection open at any time. If this is a problem then you must use a multithreaded (e.g. CherryPy) or non-blocking server (e.g. Twisted, Tornado, etc.).
A:
This is possible. Just don't close the connection to the client.
A:
Extending what lost-theory has said, if you want to use comet for a passing messages between clients then you need to implement something like pubsub.
Using something like tornado for the pubsub is much simpler than with the single threaded wsgiref servers.
|
Basic Comet in Python using just std lib
|
I'm developing a web interface for an already existing desktop application. I've been looking for a way to allow the server to push content to the browser and ended up reaching Comet.
Navigating through the internet, and most of the questions here, I got answers like twisted, orbited, tornado and most of them even point to java applications like Jetty or StreamHub.
Without going too much deeper in this, I'd like to know is there's a chance to implement Comet-like communication using just standard lib modules like BaseHTTPServer and keep things as simple as possible as I don't need so much power and efficiency.
Note: Jython is a possibility, but I'd like to keep it with as less requirements as possible.
|
[
"As gs said, just keep the connection open.\nHere's an example WSGI app that sends the current time to the client every second:\nimport time\n\ndef application(environ, start_response):\n start_response('200 OK', [('content-type', 'text/plain')])\n while True:\n time.sleep(1.0)\n yield time.ctime() + '\\n'\n\nif __name__ == '__main__':\n from wsgiref.simple_server import make_server\n print \"Serving on http://localhost:4000...\"\n make_server('localhost', 4000, application).serve_forever()\n\nIf I go to the URL in my browser, I see this:\nMon Oct 05 12:21:26 2009\nMon Oct 05 12:21:27 2009\nMon Oct 05 12:21:28 2009\nMon Oct 05 12:21:29 2009\nMon Oct 05 12:21:30 2009\n(...a new line appears every second...)\n\nThe problem with this approach is that you can't keep very many connections like this open at the same time. In fact, the wsgiref server is single-threaded, so you can only have one connection open at any time. If this is a problem then you must use a multithreaded (e.g. CherryPy) or non-blocking server (e.g. Twisted, Tornado, etc.).\n",
"This is possible. Just don't close the connection to the client.\n",
"Extending what lost-theory has said, if you want to use comet for a passing messages between clients then you need to implement something like pubsub.\nUsing something like tornado for the pubsub is much simpler than with the single threaded wsgiref servers.\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"comet",
"python"
] |
stackoverflow_0001520953_comet_python.txt
|
Q:
Stuck on a loop!
I am creating an app which will be used to upload images to a specified server. I have created my GUI in Qt Designer, everything works fine I just am stuck on something that I know is simple. Cant seem to wrap my head around it.
The idea is for the script to go through and see how many text fields are filed in with paths of images - from there get each path and in order upload each one to server. I can make it work with just one box just fine but when i try to create a loop for this process it falls apart. I basically need to return 'fullname' with each different path. This is just a snippit but you get the idea..
The concept seems simple enough and I have rewritten this as many ways and I could find and think of. Any help would be awesome. Should I be using lists to do this instead or something?
# count how many images there are going to be
if not self.imgOnePathLabel.text().isEmpty():
totalImages = 1
# gets the path from IMAGE 1 box
image1 = self.imgOnePathLabel.text()
fullname = '%s' % image1
if not self.imgTwoPathLabel.text().isEmpty():
totalImages = 2
image2 = self.img2PathLabel.text()
fullname = '%s' % image2
if not self.imgThreePathLabel.text().isEmpty():
totalImages = 3
imageThreePath = self.imgThreePathLabel.text()
fullname = '%s' % imageThreePath
try:
for x in range(1,totalImages,1):
# split end file from the file path
name = os.path.split(fullname)[1]
f = open(fullname, "rb")
# store our selected file
ftp.storbinary('STOR ' + name, f)
msg = "Sent <font color=green>" + name + "</font>"
self.logBrowser.append(msg)
f.close()
finally:
msg = "<font color=green>" "Ok" "</font>"
self.logBrowser.append(msg)
A:
The issue you have is that you are assigning to the variable fullname three times overwriting it each time. So by the time you get to the for loop only have the last file name available if the last field has been set otherwise you get nothing at all. Your statement that you need a list of full names rather than one variable is correct. You need something like below:
fullnames = []
imageLabels = [self.imgOnePathLabel, self.imgTwoPathLabel,
self.imgThreePathLabel]
for imageLabel in imageLabels:
if imageLabel.text():
image = self.imgOnePathLabel.text()
fullnames.append('%s' % image)
try:
for fullname in fullnames:
# split end file from the file path
name = os.path.split(fullname)[1]
f = open(fullname, "rb")
# store our selected file
ftp.storbinary('STOR ' + name, f)
msg = "Sent <font color=green>" + name + "</font>"
self.logBrowser.append(msg)
f.close()
finally:
msg = "<font color=green>" "Ok" "</font>"
self.logBrowser.append(msg)
A:
Aside from the issue of the range needing to be +1 as so to reach to #3 (cf Remark by Vincent R),
(one of) the problem(s) is that the fullname variable is overwritten with each of the new case of non empty label.
It's hard to comment about the code to just fix it, i.e. I'd like to suggest and reorganize it a bit. For example by introducing a function to extract the name / path of a given image, given the UI object; this would avoid some of the repetition. Such a function, or the the caller of it, would then add each new fullname to a list thereof, which can then be used by the upload loop.
See Tendayi Mawushe's solution, which is respectful of the original structure but introduces a list as suggested. BTW this list then can be iterated over as the basis of the loop, instead of relying on the range() function, and this is much more pythonic (and this removes the need of fixing the problem with missing #3 with the range). While being handy on occasion, with Python, these numeric range driven loops are often an invitation to revisit the design.
A:
Another issue with your original code is that if labels 1 and 3 are not blank, but label 2 is, totalImages would be set to 3 even though you only have two paths.
Also, a typo in this code ("Two" vs "2"):
if not self.imgTwoPathLabel.text().isEmpty():
image2 = self.img2PathLabel.text()
And I believe you don't need the string substitution '%s' % image.
You could condense your code a little (and fix your issues) like this:
# this is a list of references to your PyQt4 label objects
imagePathLabels = [self.imgOnePathLabel,
self.imgTwoPathLabel,
self.imgThreePathLabel]
try:
for label in imagePathLabels:
if not label.text().isEmpty():
image_path = label.text()
image_name = os.path.split(image_path)[1]
f = open(image_path, "rb")
ftp.storbinary('STOR ' + image_name, f)
msg = "Sent <font color=green>" + name + "</font>"
self.logBrowser.append(msg)
f.close()
finally:
msg = "<font color=green>" "Ok" "</font>"
self.logBrowser.append(msg)
|
Stuck on a loop!
|
I am creating an app which will be used to upload images to a specified server. I have created my GUI in Qt Designer, everything works fine I just am stuck on something that I know is simple. Cant seem to wrap my head around it.
The idea is for the script to go through and see how many text fields are filed in with paths of images - from there get each path and in order upload each one to server. I can make it work with just one box just fine but when i try to create a loop for this process it falls apart. I basically need to return 'fullname' with each different path. This is just a snippit but you get the idea..
The concept seems simple enough and I have rewritten this as many ways and I could find and think of. Any help would be awesome. Should I be using lists to do this instead or something?
# count how many images there are going to be
if not self.imgOnePathLabel.text().isEmpty():
totalImages = 1
# gets the path from IMAGE 1 box
image1 = self.imgOnePathLabel.text()
fullname = '%s' % image1
if not self.imgTwoPathLabel.text().isEmpty():
totalImages = 2
image2 = self.img2PathLabel.text()
fullname = '%s' % image2
if not self.imgThreePathLabel.text().isEmpty():
totalImages = 3
imageThreePath = self.imgThreePathLabel.text()
fullname = '%s' % imageThreePath
try:
for x in range(1,totalImages,1):
# split end file from the file path
name = os.path.split(fullname)[1]
f = open(fullname, "rb")
# store our selected file
ftp.storbinary('STOR ' + name, f)
msg = "Sent <font color=green>" + name + "</font>"
self.logBrowser.append(msg)
f.close()
finally:
msg = "<font color=green>" "Ok" "</font>"
self.logBrowser.append(msg)
|
[
"The issue you have is that you are assigning to the variable fullname three times overwriting it each time. So by the time you get to the for loop only have the last file name available if the last field has been set otherwise you get nothing at all. Your statement that you need a list of full names rather than one variable is correct. You need something like below:\n fullnames = []\n imageLabels = [self.imgOnePathLabel, self.imgTwoPathLabel,\n self.imgThreePathLabel]\n for imageLabel in imageLabels:\n if imageLabel.text():\n image = self.imgOnePathLabel.text()\n fullnames.append('%s' % image)\n try:\n for fullname in fullnames:\n # split end file from the file path\n name = os.path.split(fullname)[1]\n f = open(fullname, \"rb\")\n # store our selected file\n ftp.storbinary('STOR ' + name, f)\n msg = \"Sent <font color=green>\" + name + \"</font>\"\n self.logBrowser.append(msg)\n f.close()\n finally:\n msg = \"<font color=green>\" \"Ok\" \"</font>\"\n self.logBrowser.append(msg)\n\n",
"Aside from the issue of the range needing to be +1 as so to reach to #3 (cf Remark by Vincent R),\n(one of) the problem(s) is that the fullname variable is overwritten with each of the new case of non empty label.\nIt's hard to comment about the code to just fix it, i.e. I'd like to suggest and reorganize it a bit. For example by introducing a function to extract the name / path of a given image, given the UI object; this would avoid some of the repetition. Such a function, or the the caller of it, would then add each new fullname to a list thereof, which can then be used by the upload loop.\nSee Tendayi Mawushe's solution, which is respectful of the original structure but introduces a list as suggested. BTW this list then can be iterated over as the basis of the loop, instead of relying on the range() function, and this is much more pythonic (and this removes the need of fixing the problem with missing #3 with the range). While being handy on occasion, with Python, these numeric range driven loops are often an invitation to revisit the design.\n",
"Another issue with your original code is that if labels 1 and 3 are not blank, but label 2 is, totalImages would be set to 3 even though you only have two paths.\nAlso, a typo in this code (\"Two\" vs \"2\"):\nif not self.imgTwoPathLabel.text().isEmpty():\n image2 = self.img2PathLabel.text()\n\nAnd I believe you don't need the string substitution '%s' % image.\nYou could condense your code a little (and fix your issues) like this:\n# this is a list of references to your PyQt4 label objects\nimagePathLabels = [self.imgOnePathLabel, \n self.imgTwoPathLabel, \n self.imgThreePathLabel]\n\ntry:\n for label in imagePathLabels:\n if not label.text().isEmpty():\n image_path = label.text()\n image_name = os.path.split(image_path)[1]\n f = open(image_path, \"rb\")\n ftp.storbinary('STOR ' + image_name, f)\n msg = \"Sent <font color=green>\" + name + \"</font>\"\n self.logBrowser.append(msg)\n f.close()\nfinally:\n msg = \"<font color=green>\" \"Ok\" \"</font>\"\n self.logBrowser.append(msg)\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"ftp",
"image",
"python",
"qt_designer",
"range"
] |
stackoverflow_0001751359_ftp_image_python_qt_designer_range.txt
|
Q:
What's the best python soap stack for consuming Amazon Web Services WSDL?
Python has a number of soap stacks; as near as I can tell, all have substantial defects.
Has anyone had luck consuming and using WSDL for S3, EC2, and SQS in python?
My experience is that suds fails when constructing a Client object; after some wrangling, ZSI generates client code that doesn't work; etc.
Finally, I'm aware of boto but as it is a hand-rolled wrapper around AWS, it is (1) incomplete and (2) never up-to-date with the latest AWS WSDL.
A:
The REST or "Query" APIs are definitely easier to use than SOAP, but unfortunately at least once service (EC2) doesn't provide any alternatives to SOAP. As you've already discovered, Python's existing SOAP implementations are woefully inadequate for most purposes; one workaround approach is to just generate the XML for the SOAP envelope/body directly, instead of going through an intermediate SOAP layer. If you're somewhat familiar with XML / SOAP, this isn't too hard to do in most cases, and allows you to work around any particular idiosyncrasies with the SOAP implementation on the other end; this can be quite important, as just about every SOAP stack out there has its own flavour of bugginess / weirdness to contend with.
A:
if i'm not mistaken, you can consume Amazon Web Services via REST as well as SOAP. using REST with python would be much easier.
A:
Check out http://boto.googlecode.com. This is the best way to use AWS in Python.
A:
FWIW, I get this Amazon WSDL to parse with Suds 0.3.8:
url = 'http://s3.amazonaws.com/ec2-downloads/2009-04-04.ec2.wsdl'
c = Client(url)
print c
-- snip --
Ports (1):
(AmazonEC2Port)
Methods (43):
--- Much more removed for brevity ---
-Matt
|
What's the best python soap stack for consuming Amazon Web Services WSDL?
|
Python has a number of soap stacks; as near as I can tell, all have substantial defects.
Has anyone had luck consuming and using WSDL for S3, EC2, and SQS in python?
My experience is that suds fails when constructing a Client object; after some wrangling, ZSI generates client code that doesn't work; etc.
Finally, I'm aware of boto but as it is a hand-rolled wrapper around AWS, it is (1) incomplete and (2) never up-to-date with the latest AWS WSDL.
|
[
"The REST or \"Query\" APIs are definitely easier to use than SOAP, but unfortunately at least once service (EC2) doesn't provide any alternatives to SOAP. As you've already discovered, Python's existing SOAP implementations are woefully inadequate for most purposes; one workaround approach is to just generate the XML for the SOAP envelope/body directly, instead of going through an intermediate SOAP layer. If you're somewhat familiar with XML / SOAP, this isn't too hard to do in most cases, and allows you to work around any particular idiosyncrasies with the SOAP implementation on the other end; this can be quite important, as just about every SOAP stack out there has its own flavour of bugginess / weirdness to contend with.\n",
"if i'm not mistaken, you can consume Amazon Web Services via REST as well as SOAP. using REST with python would be much easier. \n",
"Check out http://boto.googlecode.com. This is the best way to use AWS in Python.\n",
"FWIW, I get this Amazon WSDL to parse with Suds 0.3.8:\nurl = 'http://s3.amazonaws.com/ec2-downloads/2009-04-04.ec2.wsdl' \nc = Client(url) \nprint c \n-- snip -- \n Ports (1):\n (AmazonEC2Port)\n Methods (43):\n--- Much more removed for brevity ---\n-Matt\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"amazon",
"amazon_web_services",
"python",
"soap",
"wsdl"
] |
stackoverflow_0000231924_amazon_amazon_web_services_python_soap_wsdl.txt
|
Q:
Is there any way to read the header codes without downloading the file at all?
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
print res.status
I am currently using this to get the HTTP header code of a file.
However, it seems like this code DOWNLOADS the file, and then gets the code.
However, some files are actually video files...and it would be inefficient for my program to download them.
Is there any way to read the header codes without downloading the file at all?
A:
Unfortunately the HEAD HTTP Method like all other HTTP method is just a directive to the server. The HTTP spec says that the server must not return the body in case, but if the server is not implemented or configured correctly then it may return the entire contents of the URL.
There are other factors that may be at play here a proxy server either on your end or on the server end could be caching the content (especially if since it is video) and returning it from a cache. Since the data is coming from a cache full respect of the HTTP specification may be missing.
A:
The purpose of the HTTP HEAD command is to return the header information, identical to what you would receive with a GET command, but without the response body (e.g. the video itself). If you are issuing the HEAD command and receiving the full body of the response anyway, that sounds like a problem with the server you're connecting to.
A:
As the others have said, if you're getting more than the headers back with the HEAD command, the target server is misconfigured.
However, a pragmatic solution to your problem is to simply ask for the first N bytes of the file, and then parse those as a header. Alternatively, stream the connection, periodically parsing for a complete header, and then cancel the download once you've got the header information you need.
A:
Use urllib2.open() and get the headers already parsed for you, along with a file-handle ready to read the rest of the data stream. At that point you close the file and don't fetch anything more.
>>> import urllib2
>>> f = urllib2.urlopen("http://stackoverflow.com/")
>>> for k,v in f.headers.items():
... print repr(k), "=", repr(v)
...
'content-length' = '113782'
'expires' = 'Tue, 17 Nov 2009 22:12:33 GMT'
'server' = 'Microsoft-IIS/7.0'
'connection' = 'close'
'cache-control' = 'private'
'date' = 'Tue, 17 Nov 2009 22:12:33 GMT'
'content-type' = 'text/html; charset=utf-8'
>>> f.read(20)
'\r\n\r\n<!DOCTYPE HTML P'
>>>
There should be no reason to generate a HEAD request here.
|
Is there any way to read the header codes without downloading the file at all?
|
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
print res.status
I am currently using this to get the HTTP header code of a file.
However, it seems like this code DOWNLOADS the file, and then gets the code.
However, some files are actually video files...and it would be inefficient for my program to download them.
Is there any way to read the header codes without downloading the file at all?
|
[
"Unfortunately the HEAD HTTP Method like all other HTTP method is just a directive to the server. The HTTP spec says that the server must not return the body in case, but if the server is not implemented or configured correctly then it may return the entire contents of the URL.\nThere are other factors that may be at play here a proxy server either on your end or on the server end could be caching the content (especially if since it is video) and returning it from a cache. Since the data is coming from a cache full respect of the HTTP specification may be missing.\n",
"The purpose of the HTTP HEAD command is to return the header information, identical to what you would receive with a GET command, but without the response body (e.g. the video itself). If you are issuing the HEAD command and receiving the full body of the response anyway, that sounds like a problem with the server you're connecting to.\n",
"As the others have said, if you're getting more than the headers back with the HEAD command, the target server is misconfigured.\nHowever, a pragmatic solution to your problem is to simply ask for the first N bytes of the file, and then parse those as a header. Alternatively, stream the connection, periodically parsing for a complete header, and then cancel the download once you've got the header information you need.\n",
"Use urllib2.open() and get the headers already parsed for you, along with a file-handle ready to read the rest of the data stream. At that point you close the file and don't fetch anything more.\n>>> import urllib2\n>>> f = urllib2.urlopen(\"http://stackoverflow.com/\")\n>>> for k,v in f.headers.items():\n... print repr(k), \"=\", repr(v)\n... \n'content-length' = '113782'\n'expires' = 'Tue, 17 Nov 2009 22:12:33 GMT'\n'server' = 'Microsoft-IIS/7.0'\n'connection' = 'close'\n'cache-control' = 'private'\n'date' = 'Tue, 17 Nov 2009 22:12:33 GMT'\n'content-type' = 'text/html; charset=utf-8'\n>>> f.read(20)\n'\\r\\n\\r\\n<!DOCTYPE HTML P'\n>>> \n\nThere should be no reason to generate a HEAD request here.\n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"header",
"http",
"python"
] |
stackoverflow_0001751253_header_http_python.txt
|
Q:
How to loop until EOF in Python?
I need to loop until I hit the end of a file-like object, but I'm not finding an "obvious way to do it", which makes me suspect I'm overlooking something, well, obvious. :-)
I have a stream (in this case, it's a StringIO object, but I'm curious about the general case as well) which stores an unknown number of records in "<length><data>" format, e.g.:
data = StringIO("\x07\x00\x00\x00foobar\x00\x04\x00\x00\x00baz\x00")
Now, the only clear way I can imagine to read this is using (what I think of as) an initialized loop, which seems a little un-Pythonic:
len_name = data.read(4)
while len_name != "":
len_name = struct.unpack("<I", len_name)[0]
names.append(data.read(len_name))
len_name = data.read(4)
In a C-like language, I'd just stick the read(4) in the while's test clause, but of course that won't work for Python. Any thoughts on a better way to accomplish this?
A:
You can combine iteration through iter() with a sentinel:
for block in iter(lambda: file_obj.read(4), ""):
use(block)
A:
Have you seen how to iterate over lines in a text file?
for line in file_obj:
use(line)
You can do the same thing with your own generator:
def read_blocks(file_obj, size):
while True:
data = file_obj.read(size)
if not data:
break
yield data
for block in read_blocks(file_obj, 4):
use(block)
See also:
file.read
A:
I prefer the already mentioned iterator-based solution to turn this into a for-loop. Another solution written directly is Knuth's "loop-and-a-half"
while 1:
len_name = data.read(4)
if not len_name:
break
names.append(data.read(len_name))
You can see by comparison how that's easily hoisted into its own generator and used as a for-loop.
A:
I see, as predicted, that the typical and most popular answer are using very specialized generators to "read 4 bytes at a time". Sometimes generality isn't any harder (and much more rewarding;-), so, I've suggested instead the following very general solution:
import operator
def funlooper(afun, *a, **k):
wearedone = k.pop('wearedone', operator.not_)
while True:
data = afun(*a, **k)
if wearedone(data): break
yield data
Now your desired loop header is just: for len_name in funlooper(data.read, 4):.
Edit: made much more general by the wearedone idiom since a comment accused my slightly less general previous version (hardcoding the exit test as if not data:) of having "a hidden dependency", of all things!-)
The usual swiss army knife of looping, itertools, is fine too, of course, as usual:
import itertools as it
for len_name in it.takewhile(bool, it.imap(data.read, it.repeat(4))): ...
or, quite equivalently:
import itertools as it
def loop(pred, fun, *args):
return it.takewhile(pred, it.starmap(fun, it.repeat(args)))
for len_name in loop(bool, data.read, 4): ...
A:
The EOF marker in python is an empty string so what you have is pretty close to the best you are going to get without writing a function to wrap this up in an iterator. I could be written in a little more pythonic way by changing the while like:
while len_name:
len_name = struct.unpack("<I", len_name)[0]
names.append(data.read(len_name))
len_name = data.read(4)
A:
I'd go with Tendayi's suggestion re function and iterator for readability:
def read4():
len_name = data.read(4)
if len_name:
len_name = struct.unpack("<I", len_name)[0]
return data.read(len_name)
else:
raise StopIteration
for d in iter(read4, ''):
names.append(d)
|
How to loop until EOF in Python?
|
I need to loop until I hit the end of a file-like object, but I'm not finding an "obvious way to do it", which makes me suspect I'm overlooking something, well, obvious. :-)
I have a stream (in this case, it's a StringIO object, but I'm curious about the general case as well) which stores an unknown number of records in "<length><data>" format, e.g.:
data = StringIO("\x07\x00\x00\x00foobar\x00\x04\x00\x00\x00baz\x00")
Now, the only clear way I can imagine to read this is using (what I think of as) an initialized loop, which seems a little un-Pythonic:
len_name = data.read(4)
while len_name != "":
len_name = struct.unpack("<I", len_name)[0]
names.append(data.read(len_name))
len_name = data.read(4)
In a C-like language, I'd just stick the read(4) in the while's test clause, but of course that won't work for Python. Any thoughts on a better way to accomplish this?
|
[
"You can combine iteration through iter() with a sentinel:\nfor block in iter(lambda: file_obj.read(4), \"\"):\n use(block)\n\n",
"Have you seen how to iterate over lines in a text file?\nfor line in file_obj:\n use(line)\n\nYou can do the same thing with your own generator:\ndef read_blocks(file_obj, size):\n while True:\n data = file_obj.read(size)\n if not data:\n break\n yield data\n\nfor block in read_blocks(file_obj, 4):\n use(block)\n\nSee also:\n\nfile.read\n\n",
"I prefer the already mentioned iterator-based solution to turn this into a for-loop. Another solution written directly is Knuth's \"loop-and-a-half\"\nwhile 1:\n len_name = data.read(4)\n if not len_name:\n break\n names.append(data.read(len_name))\n\nYou can see by comparison how that's easily hoisted into its own generator and used as a for-loop.\n",
"I see, as predicted, that the typical and most popular answer are using very specialized generators to \"read 4 bytes at a time\". Sometimes generality isn't any harder (and much more rewarding;-), so, I've suggested instead the following very general solution:\nimport operator\ndef funlooper(afun, *a, **k):\n wearedone = k.pop('wearedone', operator.not_)\n while True:\n data = afun(*a, **k)\n if wearedone(data): break\n yield data\n\nNow your desired loop header is just: for len_name in funlooper(data.read, 4):.\nEdit: made much more general by the wearedone idiom since a comment accused my slightly less general previous version (hardcoding the exit test as if not data:) of having \"a hidden dependency\", of all things!-)\nThe usual swiss army knife of looping, itertools, is fine too, of course, as usual:\nimport itertools as it\n\nfor len_name in it.takewhile(bool, it.imap(data.read, it.repeat(4))): ...\n\nor, quite equivalently:\nimport itertools as it\n\ndef loop(pred, fun, *args):\n return it.takewhile(pred, it.starmap(fun, it.repeat(args)))\n\nfor len_name in loop(bool, data.read, 4): ...\n\n",
"The EOF marker in python is an empty string so what you have is pretty close to the best you are going to get without writing a function to wrap this up in an iterator. I could be written in a little more pythonic way by changing the while like:\nwhile len_name:\n len_name = struct.unpack(\"<I\", len_name)[0]\n names.append(data.read(len_name))\n len_name = data.read(4)\n\n",
"I'd go with Tendayi's suggestion re function and iterator for readability:\ndef read4():\n len_name = data.read(4)\n if len_name:\n len_name = struct.unpack(\"<I\", len_name)[0]\n return data.read(len_name)\n else:\n raise StopIteration\n\nfor d in iter(read4, ''):\n names.append(d)\n\n"
] |
[
27,
10,
5,
3,
1,
0
] |
[] |
[] |
[
"eof",
"python",
"stringio"
] |
stackoverflow_0001752107_eof_python_stringio.txt
|
Q:
In Python, what does getresponse() return?
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
I can get the res.status , which is the http status code.
What other elements can I get?
Why is it that when I do print res, it won't print the dictionary? I just want to see the keys that are in that dictionary...
A:
You can always inspect an object using dir; that will show you which attributes it has.
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.nl")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> dir(res)
['__doc__', '__init__', '__module__', '_check_close', '_method', '_read_chunked', '_read_status', '_safe_read', 'begin', 'chunk_left', 'chunked', 'close', 'debuglevel', 'fp', 'getheader', 'getheaders', 'isclosed', 'length', 'msg', 'read', 'reason', 'status', 'strict', 'version', 'will_close']
Likewise, you can invoke help, which will show an object's documentation, if it has a __doc__ attribute. As you can see, this is the case for res, so try:
>>> help(res)
Other than that, the documentation states that getresponse returns an HTTPResponse object. Thus, as you can read there (and in help(res)), the following properties and methods are defined on HTTPResponse objects:
HTTPResponse.read([amt]):
Reads and returns the response body, or up to the next amt bytes.
HTTPResponse.getheader(name[, default]):
Get the contents of the header name, or default if there is no matching header.
HTTPResponse.getheaders():
Return a list of (header, value) tuples.
(New in version 2.4.)
HTTPResponse.msg:
A mimetools.Message instance containing the response headers.
HTTPResponse.version:
HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.
HTTPResponse.status:
Status code returned by server.
HTTPResponse.reason:
Reason phrase returned by server.
|
In Python, what does getresponse() return?
|
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
I can get the res.status , which is the http status code.
What other elements can I get?
Why is it that when I do print res, it won't print the dictionary? I just want to see the keys that are in that dictionary...
|
[
"You can always inspect an object using dir; that will show you which attributes it has.\n>>> import httplib\n>>> conn = httplib.HTTPConnection(\"www.google.nl\")\n>>> conn.request(\"HEAD\", \"/index.html\")\n>>> res = conn.getresponse()\n>>> dir(res)\n['__doc__', '__init__', '__module__', '_check_close', '_method', '_read_chunked', '_read_status', '_safe_read', 'begin', 'chunk_left', 'chunked', 'close', 'debuglevel', 'fp', 'getheader', 'getheaders', 'isclosed', 'length', 'msg', 'read', 'reason', 'status', 'strict', 'version', 'will_close']\n\nLikewise, you can invoke help, which will show an object's documentation, if it has a __doc__ attribute. As you can see, this is the case for res, so try:\n>>> help(res)\n\nOther than that, the documentation states that getresponse returns an HTTPResponse object. Thus, as you can read there (and in help(res)), the following properties and methods are defined on HTTPResponse objects:\n\nHTTPResponse.read([amt]):\nReads and returns the response body, or up to the next amt bytes.\nHTTPResponse.getheader(name[, default]):\nGet the contents of the header name, or default if there is no matching header.\nHTTPResponse.getheaders():\nReturn a list of (header, value) tuples.\n(New in version 2.4.)\nHTTPResponse.msg:\nA mimetools.Message instance containing the response headers.\nHTTPResponse.version:\nHTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.\nHTTPResponse.status:\nStatus code returned by server.\nHTTPResponse.reason:\nReason phrase returned by server.\n\n"
] |
[
26
] |
[] |
[] |
[
"http",
"linux",
"python",
"unix"
] |
stackoverflow_0001752283_http_linux_python_unix.txt
|
Q:
How to get the true URL of a file on the web. (Python)
I notice that sometimes audio files on the internet have a "fake" URL.
http://garagaeband.com/3252243
And this will 302 to the real URL:
http://garageband.com/michael_jackson4.mp3
My question is...when supplied with the fake URL, how can you get the REAL URL from headers?
Currently, this is my code for reading the headers of a file. I don't know if this code will get me what I want to accomplish. How do I parse out the "real" URL From the response headers?
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
This has a 302 redirect:
http://www.garageband.com/mp3cat/.UZCMYiqF7Kum/01_No_pierdas_la_fuente_del_gozo.mp3
A:
Use urllib.getUrl()
edit:
Sorry, I haven't done this in a while:
import urllib
urllib.urlopen(url).geturl()
For example:
>>> f = urllib2.urlopen("http://tinyurl.com/oex2e")
>>> f.geturl()
'http://www.amazon.com/All-Creatures-Great-Small-Collection/dp/B00006G8FI'
>>>
A:
Mark Pilgrim advises to use httplib2 in "Dive Into Python3" as it handles many things (including redirects) in a smarter way.
>>> import httplib2
>>> h = httplib2.Http()
>>> response, content = h.request("http://garagaeband.com/3252243")
>>> response["content-location"]
"http://garageband.com/michael_jackson4.mp3"
A:
You have to read the response, realize that you got a 302 (FOUND), and parse out the real URL from the response headers, then fetch the resource using the new URI.
A:
I solved the answer.
import urllib2
req = urllib2.Request('http://' + theurl)
opener = urllib2.build_opener()
f = opener.open(req)
print 'the real url is......' + f .url
|
How to get the true URL of a file on the web. (Python)
|
I notice that sometimes audio files on the internet have a "fake" URL.
http://garagaeband.com/3252243
And this will 302 to the real URL:
http://garageband.com/michael_jackson4.mp3
My question is...when supplied with the fake URL, how can you get the REAL URL from headers?
Currently, this is my code for reading the headers of a file. I don't know if this code will get me what I want to accomplish. How do I parse out the "real" URL From the response headers?
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
This has a 302 redirect:
http://www.garageband.com/mp3cat/.UZCMYiqF7Kum/01_No_pierdas_la_fuente_del_gozo.mp3
|
[
"Use urllib.getUrl()\nedit:\nSorry, I haven't done this in a while: \nimport urllib\nurllib.urlopen(url).geturl()\n\nFor example:\n>>> f = urllib2.urlopen(\"http://tinyurl.com/oex2e\")\n>>> f.geturl()\n'http://www.amazon.com/All-Creatures-Great-Small-Collection/dp/B00006G8FI'\n>>> \n\n",
"Mark Pilgrim advises to use httplib2 in \"Dive Into Python3\" as it handles many things (including redirects) in a smarter way.\n>>> import httplib2\n>>> h = httplib2.Http()\n>>> response, content = h.request(\"http://garagaeband.com/3252243\")\n>>> response[\"content-location\"]\n \"http://garageband.com/michael_jackson4.mp3\"\n\n",
"You have to read the response, realize that you got a 302 (FOUND), and parse out the real URL from the response headers, then fetch the resource using the new URI.\n",
"I solved the answer.\n import urllib2\n req = urllib2.Request('http://' + theurl)\n opener = urllib2.build_opener()\n f = opener.open(req)\n print 'the real url is......' + f .url\n\n"
] |
[
9,
2,
0,
0
] |
[] |
[] |
[
"http",
"http_headers",
"linux",
"python",
"unix"
] |
stackoverflow_0001752317_http_http_headers_linux_python_unix.txt
|
Q:
A dictionary with values that are dictionaries: trying to sum across those keys in python
Data structure is a dictionary, each value is another dictionary, like:
>>> from lib import schedule
>>> schedule = schedule.Schedule()
>>> game = schedule.games[0]
>>> game.home
<lib.schedule.Team instance at 0x9d97c6c>
>>> game.home.lineup
{'guerv001': {'HR': 392, '1B': 1297}, 'kendh001': {'HR': 12, '1B': 201}, 'andeg001': {'HR': 272, '1B': 1572}, 'mattg002': {'HR': 104, '1B': 632}, 'figgc001': {'HR': 26, '1B': 672}, 'iztum001': {'HR': 16, '1B': 253}, 'huntt001': {'HR': 213, '1B': 834}, 'quinr002': {'HR': 23, '1B': 200}, 'napom001': {'HR': 46, '1B': 96}}
Would like Team to have a method getTotals(self, category) where if you called:
game.home.getTotals('HR')
The method would, in this case, yield:
1104
Essentially you can see what I'm trying to do. Any ideas?
update: I have this working with two list comprehensions but would like to winnow it down to one:
def getTotals(self, category):
cats = [x for x in self.lineup.values()]
return sum([x[category] for x in cats])
another update: Based on inspectorg4dget's helpful feedback below I've gotten it. Thanks!
def getTotals(self, category):
return sum(self.lineup[man][category] for man in self.lineup.keys())
final update: Based on Nadia's feedback, here's another approach:
def getTotals(self, category):
return sum(value.get(category, 0) for value in self.lineup.values())
A:
You can use a generator expression:
def total(category):
return sum(value.get(category, 0) for value in game.home.lineup.values())
>>> total('HR')
1104
I used dict.get to make the default 0 if the category is missing from any dictionary.
The self version:
def total(self, category):
return sum(value.get(category, 0) for value in self.lineup.values())
A:
def total(category):
return sum([ghl[man][category] for man in game.home.lineup.keys()])
A:
def myGetTotals(self, team):
count = 0
for aKey in self.lineup:
if team in self.lineup[aKey]:
count = count + self.lineup[aKey][team]
return count
Kind of verbose, but meh. Do pay attention to the first parameter which is the instance. Now, if you want it to be part of all team objects, you'd need to modify the class:
lib.schedule.Team.getTotals = myGetTotals
That should add said object to the class definition and make existing objects capable of using it from there on forth. It's been a few months since I coded some Python, but it should work.
|
A dictionary with values that are dictionaries: trying to sum across those keys in python
|
Data structure is a dictionary, each value is another dictionary, like:
>>> from lib import schedule
>>> schedule = schedule.Schedule()
>>> game = schedule.games[0]
>>> game.home
<lib.schedule.Team instance at 0x9d97c6c>
>>> game.home.lineup
{'guerv001': {'HR': 392, '1B': 1297}, 'kendh001': {'HR': 12, '1B': 201}, 'andeg001': {'HR': 272, '1B': 1572}, 'mattg002': {'HR': 104, '1B': 632}, 'figgc001': {'HR': 26, '1B': 672}, 'iztum001': {'HR': 16, '1B': 253}, 'huntt001': {'HR': 213, '1B': 834}, 'quinr002': {'HR': 23, '1B': 200}, 'napom001': {'HR': 46, '1B': 96}}
Would like Team to have a method getTotals(self, category) where if you called:
game.home.getTotals('HR')
The method would, in this case, yield:
1104
Essentially you can see what I'm trying to do. Any ideas?
update: I have this working with two list comprehensions but would like to winnow it down to one:
def getTotals(self, category):
cats = [x for x in self.lineup.values()]
return sum([x[category] for x in cats])
another update: Based on inspectorg4dget's helpful feedback below I've gotten it. Thanks!
def getTotals(self, category):
return sum(self.lineup[man][category] for man in self.lineup.keys())
final update: Based on Nadia's feedback, here's another approach:
def getTotals(self, category):
return sum(value.get(category, 0) for value in self.lineup.values())
|
[
"You can use a generator expression:\ndef total(category):\n return sum(value.get(category, 0) for value in game.home.lineup.values())\n\n>>> total('HR')\n1104\n\nI used dict.get to make the default 0 if the category is missing from any dictionary.\nThe self version:\ndef total(self, category):\n return sum(value.get(category, 0) for value in self.lineup.values())\n\n",
"def total(category):\n return sum([ghl[man][category] for man in game.home.lineup.keys()])\n\n",
"def myGetTotals(self, team):\n count = 0\n for aKey in self.lineup:\n if team in self.lineup[aKey]:\n count = count + self.lineup[aKey][team]\n return count\n\nKind of verbose, but meh. Do pay attention to the first parameter which is the instance. Now, if you want it to be part of all team objects, you'd need to modify the class:\nlib.schedule.Team.getTotals = myGetTotals\n\nThat should add said object to the class definition and make existing objects capable of using it from there on forth. It's been a few months since I coded some Python, but it should work.\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"dictionary",
"hash",
"python"
] |
stackoverflow_0001752730_dictionary_hash_python.txt
|
Q:
python paste using global egg instead of local one
I'm using Paste to run a Pylons application. Is there a way to specify in my paste config file to use the egg from the current directory (the same dir as the config file) instead of looking in global site-packages?
For example, right now the config file has:
[app:main]
use = egg:example
This definitely looks to site-packages. This wouldn't be a problem, except I'm running two versions of the same egg on the same server in a deployable, programmatic way, so I need to be able to deploy them from somewhere besides site-packages.
Thanks.
A:
Read this similar question, at least one of the answers should help you: Making Python Use Code in My Directory (not that in /usr/...)
UPDATE: You could rename the local module to something slightly different, like example_local.
A:
One way to use several versions of python package on the same system is virtualenv. It works by creating sandboxed environments. All global packages are "visible" from sandboxed environment, but you can install new packages inside the sandbox environment that won't affect rest of the system. I've successfully used this approach to host development and production version of a Pylons webapp on single server.
|
python paste using global egg instead of local one
|
I'm using Paste to run a Pylons application. Is there a way to specify in my paste config file to use the egg from the current directory (the same dir as the config file) instead of looking in global site-packages?
For example, right now the config file has:
[app:main]
use = egg:example
This definitely looks to site-packages. This wouldn't be a problem, except I'm running two versions of the same egg on the same server in a deployable, programmatic way, so I need to be able to deploy them from somewhere besides site-packages.
Thanks.
|
[
"Read this similar question, at least one of the answers should help you: Making Python Use Code in My Directory (not that in /usr/...)\nUPDATE: You could rename the local module to something slightly different, like example_local.\n",
"One way to use several versions of python package on the same system is virtualenv. It works by creating sandboxed environments. All global packages are \"visible\" from sandboxed environment, but you can install new packages inside the sandbox environment that won't affect rest of the system. I've successfully used this approach to host development and production version of a Pylons webapp on single server.\n"
] |
[
1,
1
] |
[] |
[] |
[
"paste",
"paster",
"pylons",
"python"
] |
stackoverflow_0001751959_paste_paster_pylons_python.txt
|
Q:
BeautifulSoup - easy way to to obtain HTML-free contents
I'm using this code to find all interesting links in a page:
soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))
And it does its job pretty well. Unfortunately inside that a tag there are a lot of nested tags, like font, b and different things... I'd like to get just the text content, without any other html tag.
Example of link:
<A HREF="notizia.php?idn=1134" OnMouseOver="verde();" OnMouseOut="blu();"><FONT CLASS="v12"><B>03-11-2009: <font color=green>CCS Ingegneria Elettronica-Sportello studenti ed orientamento</B></FONT></A>
Of course it's ugly (and the markup is not always the same!) and I'd like to get:
03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento
In the documentation it says to use text=True in findAll method, but it will ignore my regex. Why? How can I solve that?
A:
I've used this:
def textOf(soup):
return u''.join(soup.findAll(text=True))
So...
texts = [textOf(n) for n in soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))]
A:
Interested in a pyparsing take on the problem?
from pyparsing import makeHTMLTags, SkipTo, anyOpenTag, anyCloseTag, ParseException
htmlsrc = """<A HREF="notizia.php?idn=1134" OnMouseOver="verde();" OnMouseOut="blu();"><FONT CLASS="v12"><B>03-11-2009: <font color=green>CCS Ingegneria Elettronica-Sportello studenti ed orientamento</B></FONT></A>"""
# create pattern to find interesting <A> tags
aStart,aEnd = makeHTMLTags("A")
def matchInterestingHrefsOnly(t):
if not t.href.startswith("notizia.php?"):
raise ParseException("not interested...")
aStart.setParseAction(matchInterestingHrefsOnly)
patt = aStart + SkipTo(aEnd)("body") + aEnd
# create pattern to strip HTML tags, and convert HTML entities
stripper = anyOpenTag.suppress() | anyCloseTag.suppress()
def stripTags(s):
s = stripper.transformString(s)
s = s.replace(" "," ")
return s
for match in patt.searchString(htmlsrc):
print stripTags(match.body)
Prints:
03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento
This is actually pretty impervious to HTML vagaries, as it factors in presence/absence of attributes, upper/lower case, and so on.
|
BeautifulSoup - easy way to to obtain HTML-free contents
|
I'm using this code to find all interesting links in a page:
soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))
And it does its job pretty well. Unfortunately inside that a tag there are a lot of nested tags, like font, b and different things... I'd like to get just the text content, without any other html tag.
Example of link:
<A HREF="notizia.php?idn=1134" OnMouseOver="verde();" OnMouseOut="blu();"><FONT CLASS="v12"><B>03-11-2009: <font color=green>CCS Ingegneria Elettronica-Sportello studenti ed orientamento</B></FONT></A>
Of course it's ugly (and the markup is not always the same!) and I'd like to get:
03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento
In the documentation it says to use text=True in findAll method, but it will ignore my regex. Why? How can I solve that?
|
[
"I've used this:\ndef textOf(soup):\n return u''.join(soup.findAll(text=True))\n\nSo...\ntexts = [textOf(n) for n in soup.findAll('a', href=re.compile('^notizia.php\\?idn=\\d+'))]\n\n",
"Interested in a pyparsing take on the problem?\nfrom pyparsing import makeHTMLTags, SkipTo, anyOpenTag, anyCloseTag, ParseException\n\nhtmlsrc = \"\"\"<A HREF=\"notizia.php?idn=1134\" OnMouseOver=\"verde();\" OnMouseOut=\"blu();\"><FONT CLASS=\"v12\"><B>03-11-2009: <font color=green>CCS Ingegneria Elettronica-Sportello studenti ed orientamento</B></FONT></A>\"\"\"\n\n# create pattern to find interesting <A> tags\naStart,aEnd = makeHTMLTags(\"A\")\ndef matchInterestingHrefsOnly(t):\n if not t.href.startswith(\"notizia.php?\"):\n raise ParseException(\"not interested...\")\naStart.setParseAction(matchInterestingHrefsOnly)\npatt = aStart + SkipTo(aEnd)(\"body\") + aEnd\n\n# create pattern to strip HTML tags, and convert HTML entities\nstripper = anyOpenTag.suppress() | anyCloseTag.suppress()\ndef stripTags(s):\n s = stripper.transformString(s)\n s = s.replace(\" \",\" \")\n return s\n\n\nfor match in patt.searchString(htmlsrc):\n print stripTags(match.body)\n\nPrints:\n03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento\n\nThis is actually pretty impervious to HTML vagaries, as it factors in presence/absence of attributes, upper/lower case, and so on.\n"
] |
[
13,
2
] |
[] |
[] |
[
"beautifulsoup",
"html_content_extraction",
"html_parsing",
"python"
] |
stackoverflow_0001752662_beautifulsoup_html_content_extraction_html_parsing_python.txt
|
Q:
Is there a better way to get a named series of constants (enumeration) in Python?
Just looking at ways of getting named constants in python.
class constant_list:
(A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3)
Then of course you can refer to it like so:
constant_list.A_CONSTANT
I suppose you could use a dictionary, using strings:
constant_dic = {
"A_CONSTANT" : 1,
"B_CONSTANT" : 2,
"C_CONSTANT" : 3,}
and refer to it like this:
constant_dic["A_CONSTANT"]
My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?
Thanks in advance.
A:
For 2.3 or after:
class Enumerate(object):
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)
To use:
codes = Enumerate('FOO BAR BAZ')
codes.BAZ will be 2 and so on.
If you only have 2.2, precede this with:
from __future__ import generators
def enumerate(iterable):
number = 0
for name in iterable:
yield number, name
number += 1
(This was taken from here)
A:
I find the enumeration class recipe (Active State, Python Cookbook) to be very effective.
Plus it has a lookup function which is nice.
Pev
A:
An alternative construction for constant_dic:
constants = ["A_CONSTANT", "B_CONSTANT", "C_CONSTANT"]
constant_dic = dict([(c,i) for i, c in enumerate(constants)])
A:
The following acts like a classisc "written in stone" C enum -- once defined, you can't change it, you can only read its values. Neither can you instantiate it. All you have to do is "import enum.py" and derive from class Enum.
# this is enum.py
class EnumException( Exception ):
pass
class Enum( object ):
class __metaclass__( type ):
def __setattr__( cls, name, value ):
raise EnumException("Can't set Enum class attribute!")
def __delattr__( cls, name ):
raise EnumException("Can't delete Enum class attribute!")
def __init__( self ):
raise EnumException("Enum cannot be instantiated!")
This is the test code:
# this is testenum.py
from enum import *
class ExampleEnum( Enum ):
A=1
B=22
C=333
if __name__ == '__main__' :
print "ExampleEnum.A |%s|" % ExampleEnum.A
print "ExampleEnum.B |%s|" % ExampleEnum.B
print "ExampleEnum.C |%s|" % ExampleEnum.C
z = ExampleEnum.A
if z == ExampleEnum.A:
print "z is A"
try:
ExampleEnum.A = 4
print "ExampleEnum.A |%s| FAIL!" % ExampleEnum.A
except EnumException:
print "Can't change Enum.A (pass...)"
try:
del ExampleEnum.A
except EnumException:
print "Can't delete Enum.A (pass...)"
try:
bad = ExampleEnum()
except EnumException:
print "Can't instantiate Enum (pass...)"
A:
This is the best one I have seen: "First Class Enums in Python"
http://code.activestate.com/recipes/413486/
It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer by mistake so overall I think it is a win.) Each enum is a unique object. You can print enums, you can iterate over them, you can test that an enum value is "in" the enum. It's pretty complete and slick.
A:
In Python, strings are immutable and so they are better for constants than numbers. The best approach, in my opinion, is to make an object that keeps constants as strings:
class Enumeration(object):
def __init__(self, possibilities):
self.possibilities = set(possibilities.split())
def all(self):
return sorted(self.possibilities)
def __getattr__(self, name):
if name in self.possibilities:
return name
raise AttributeError("Invalid constant: %s" % name)
You could then use it like this:
>>> enum = Enumeration("FOO BAR")
>>> print enum.all()
['BAR', 'FOO']
>>> print enum.FOO
FOO
>>> print enum.FOOBAR
Traceback (most recent call last):
File "enum.py", line 17, in <module>
print enum.FOOBAR
File "enum.py", line 11, in __getattr__
raise AttributeError("Invalid constant: %s" % name)
AttributeError: Invalid constant: FOOBAR
|
Is there a better way to get a named series of constants (enumeration) in Python?
|
Just looking at ways of getting named constants in python.
class constant_list:
(A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3)
Then of course you can refer to it like so:
constant_list.A_CONSTANT
I suppose you could use a dictionary, using strings:
constant_dic = {
"A_CONSTANT" : 1,
"B_CONSTANT" : 2,
"C_CONSTANT" : 3,}
and refer to it like this:
constant_dic["A_CONSTANT"]
My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?
Thanks in advance.
|
[
"For 2.3 or after:\nclass Enumerate(object):\n def __init__(self, names):\n for number, name in enumerate(names.split()):\n setattr(self, name, number)\n\nTo use:\n codes = Enumerate('FOO BAR BAZ')\n\ncodes.BAZ will be 2 and so on. \nIf you only have 2.2, precede this with:\n from __future__ import generators\n\n def enumerate(iterable):\n number = 0\n for name in iterable:\n yield number, name\n number += 1\n\n(This was taken from here)\n",
"I find the enumeration class recipe (Active State, Python Cookbook) to be very effective. \nPlus it has a lookup function which is nice.\nPev\n",
"An alternative construction for constant_dic:\nconstants = [\"A_CONSTANT\", \"B_CONSTANT\", \"C_CONSTANT\"]\nconstant_dic = dict([(c,i) for i, c in enumerate(constants)])\n\n",
"The following acts like a classisc \"written in stone\" C enum -- once defined, you can't change it, you can only read its values. Neither can you instantiate it. All you have to do is \"import enum.py\" and derive from class Enum.\n# this is enum.py\nclass EnumException( Exception ):\n pass\n\nclass Enum( object ):\n class __metaclass__( type ):\n def __setattr__( cls, name, value ):\n raise EnumException(\"Can't set Enum class attribute!\")\n def __delattr__( cls, name ):\n raise EnumException(\"Can't delete Enum class attribute!\")\n\n def __init__( self ):\n raise EnumException(\"Enum cannot be instantiated!\")\n\nThis is the test code:\n# this is testenum.py\nfrom enum import *\n\nclass ExampleEnum( Enum ):\n A=1\n B=22\n C=333\n\nif __name__ == '__main__' :\n\n print \"ExampleEnum.A |%s|\" % ExampleEnum.A\n print \"ExampleEnum.B |%s|\" % ExampleEnum.B\n print \"ExampleEnum.C |%s|\" % ExampleEnum.C\n z = ExampleEnum.A\n if z == ExampleEnum.A:\n print \"z is A\"\n\n try:\n ExampleEnum.A = 4 \n print \"ExampleEnum.A |%s| FAIL!\" % ExampleEnum.A\n except EnumException:\n print \"Can't change Enum.A (pass...)\"\n\n try:\n del ExampleEnum.A\n except EnumException:\n print \"Can't delete Enum.A (pass...)\"\n\n try:\n bad = ExampleEnum()\n except EnumException:\n print \"Can't instantiate Enum (pass...)\"\n\n",
"This is the best one I have seen: \"First Class Enums in Python\"\nhttp://code.activestate.com/recipes/413486/\nIt gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer by mistake so overall I think it is a win.) Each enum is a unique object. You can print enums, you can iterate over them, you can test that an enum value is \"in\" the enum. It's pretty complete and slick.\n",
"In Python, strings are immutable and so they are better for constants than numbers. The best approach, in my opinion, is to make an object that keeps constants as strings:\nclass Enumeration(object):\n def __init__(self, possibilities):\n self.possibilities = set(possibilities.split())\n\n def all(self):\n return sorted(self.possibilities)\n\n def __getattr__(self, name):\n if name in self.possibilities:\n return name\n raise AttributeError(\"Invalid constant: %s\" % name)\n\nYou could then use it like this:\n>>> enum = Enumeration(\"FOO BAR\")\n>>> print enum.all()\n['BAR', 'FOO']\n>>> print enum.FOO\nFOO\n>>> print enum.FOOBAR\nTraceback (most recent call last):\n File \"enum.py\", line 17, in <module>\n print enum.FOOBAR\n File \"enum.py\", line 11, in __getattr__\n raise AttributeError(\"Invalid constant: %s\" % name)\nAttributeError: Invalid constant: FOOBAR\n\n"
] |
[
19,
2,
2,
2,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000196876_python.txt
|
Q:
How do I make a simple DNS server listening two ports simultaneously in python
I'm trying to build a DNS server in python. It must listen two ports (8007 - client, 8008 - admin). The client only send an URL and receives the respective IP. The admin has permissions to change the DNS table (add, remove,.. doesn't matter to this right now).
So my question is: how do I implement the server listening continuously on the two ports for any eventual request (we can have several clients at the same time but only one admin when he is operating)
my Server with one listening port:
from SocketServer import *
from threading import *
from string import *
import socket
class Server(ForkingMixIn, TCPServer): pass #fork for each client
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print 'Got connection from', addr
data=(self.request.recv(1024)).strip()
if data not in dic: #dic -> dictionary with URL:IP
self.wfile.write('0.0.0.0')
else:
self.wfile.write(dic.get(data))
server = Server(('', 8007), Handler)
server.serve_forever()
A:
No need to use threads.
Use twisted.
TwistedNames has support out of the box for a dns server. You can customize it as needed or read its source as base when you build yours.
A:
You can use non-blocking sockets, and use the select call to read from the socket. This Sockets Programming HOWTO for Python article has a section on non-blocking sockets in Python that will help.
See also:
select (Python) | select (UNIX)
socket (Python) | socket (UNIX)
|
How do I make a simple DNS server listening two ports simultaneously in python
|
I'm trying to build a DNS server in python. It must listen two ports (8007 - client, 8008 - admin). The client only send an URL and receives the respective IP. The admin has permissions to change the DNS table (add, remove,.. doesn't matter to this right now).
So my question is: how do I implement the server listening continuously on the two ports for any eventual request (we can have several clients at the same time but only one admin when he is operating)
my Server with one listening port:
from SocketServer import *
from threading import *
from string import *
import socket
class Server(ForkingMixIn, TCPServer): pass #fork for each client
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print 'Got connection from', addr
data=(self.request.recv(1024)).strip()
if data not in dic: #dic -> dictionary with URL:IP
self.wfile.write('0.0.0.0')
else:
self.wfile.write(dic.get(data))
server = Server(('', 8007), Handler)
server.serve_forever()
|
[
"No need to use threads.\nUse twisted.\nTwistedNames has support out of the box for a dns server. You can customize it as needed or read its source as base when you build yours.\n",
"You can use non-blocking sockets, and use the select call to read from the socket. This Sockets Programming HOWTO for Python article has a section on non-blocking sockets in Python that will help.\nSee also:\n\nselect (Python) | select (UNIX) \nsocket (Python) | socket (UNIX)\n\n"
] |
[
5,
0
] |
[] |
[] |
[
"dns",
"listen",
"ports",
"python"
] |
stackoverflow_0001752902_dns_listen_ports_python.txt
|
Q:
Import C++ classes in python?
so.. let's say i have this C function:
PyObject* Foo(PyObject* pSelf, PyObject* pArgs)
{
MessageBox(NULL, "Foo was called!", "Info", MB_OK);
return PyInt_FromLong(0);
}
and then, I have to do this:
static PyMethodDef Methods[] =
{
{"Foo", Foo, METH_NOARGS, "Dummy function"},
{NULL, NULL, 0, NULL}
};
Py_InitModule("bar", Methods);
and I execute my python script..
but C functions are a little annoying, it's C++ and I use classes for almost everything.
So, is there any way to import member functions from a class to my python script?
oh btw, the python script looks something like this:
import bar
from bar import *
Foo()
A:
boost.python enables you to do that very effectively.
A:
SWIG would work pretty well, too.
A:
Take a look at boost python page. Search for 'free function'.
A:
Cython has the best C++ wrapping I have found, even though it is a bit more verbose than SWIG and it is a bit of a mindset to get into. It's easier to write mappings than SWIG -- because it uses Python types -- but you have to write them all by hand. It's also a very active project with a very friendly mailing list. It also has good buffer support for NumPy.
|
Import C++ classes in python?
|
so.. let's say i have this C function:
PyObject* Foo(PyObject* pSelf, PyObject* pArgs)
{
MessageBox(NULL, "Foo was called!", "Info", MB_OK);
return PyInt_FromLong(0);
}
and then, I have to do this:
static PyMethodDef Methods[] =
{
{"Foo", Foo, METH_NOARGS, "Dummy function"},
{NULL, NULL, 0, NULL}
};
Py_InitModule("bar", Methods);
and I execute my python script..
but C functions are a little annoying, it's C++ and I use classes for almost everything.
So, is there any way to import member functions from a class to my python script?
oh btw, the python script looks something like this:
import bar
from bar import *
Foo()
|
[
"boost.python enables you to do that very effectively.\n",
"SWIG would work pretty well, too.\n",
"Take a look at boost python page. Search for 'free function'.\n",
"Cython has the best C++ wrapping I have found, even though it is a bit more verbose than SWIG and it is a bit of a mindset to get into. It's easier to write mappings than SWIG -- because it uses Python types -- but you have to write them all by hand. It's also a very active project with a very friendly mailing list. It also has good buffer support for NumPy.\n"
] |
[
5,
2,
1,
0
] |
[] |
[] |
[
"c++",
"python"
] |
stackoverflow_0001750517_c++_python.txt
|
Q:
Python optparse Values Instance
How can I take the opt result of
opt, args = parser.parse_args()
and place it in a dict? Python calls opt a "Values Instance" and I can't find any way to turn a Values Instance into a list or dict. One can't copy items from opt in this way,
for i in opt:
myDict[i] = opt[i]
instead, its a clumsy,
myDict[parm1] = opt.parm1
myDict[parm2] = opt.parm2
which implies that every time I add an option, I have to update this code as well; there should be a way to let this take care of itself.
A:
options, args = parser.parse_args()
option_dict = vars(options)
(Source is this python-ideas post.)
|
Python optparse Values Instance
|
How can I take the opt result of
opt, args = parser.parse_args()
and place it in a dict? Python calls opt a "Values Instance" and I can't find any way to turn a Values Instance into a list or dict. One can't copy items from opt in this way,
for i in opt:
myDict[i] = opt[i]
instead, its a clumsy,
myDict[parm1] = opt.parm1
myDict[parm2] = opt.parm2
which implies that every time I add an option, I have to update this code as well; there should be a way to let this take care of itself.
|
[
"options, args = parser.parse_args()\noption_dict = vars(options)\n\n(Source is this python-ideas post.)\n"
] |
[
93
] |
[] |
[] |
[
"dictionary",
"optparse",
"python"
] |
stackoverflow_0001753460_dictionary_optparse_python.txt
|
Q:
Python functions can be given new attributes from outside the scope?
I didn't know you could do this:
def tom():
print "tom's locals: ", locals()
def dick(z):
print "z.__name__ = ", z.__name__
z.guest = "Harry"
print "z.guest = ", z.guest
print "dick's locals: ", locals()
tom() #>>> tom's locals: {}
#print tom.guest #AttributeError: 'function' object has no attribute 'guest'
print "tom's dir:", dir(tom) # no 'guest' entry
dick( tom) #>>> z.__name__ = tom
#>>> z.guest = Harry
#>>> dick's locals: {'z': <function tom at 0x02819F30>}
tom() #>>> tom's locals: {}
#print dick.guest #AttributeError: 'function' object has no attribute 'guest'
print tom.guest #>>> Harry
print "tom's dir:", dir(tom) # 'guest' entry appears
Function tom() has no locals. Function dick() knows where tom() lives and puts up Harry as 'guest' over at tom()'s place. harry doesn't appear as a local at tom()'s place, but if you ask for tom's guest, harry answers. harry is a new attribute at tom().
UPDATE: From outside tom(), you can say "print dir(tom)" and see the the tom-object's dictionary. (You can do it from inside tom(), too. So tom could find out he had a new lodger, harry, going under the name of 'guest'.)
So, attributes can be added to a function's namespace from outside the function? Is that often done? Is it acceptable practice? Is it recommended in some situations? Is it actually vital at times? (Is it Pythonic?)
UPDATE: Title now says 'attributes'; it used to say 'variables'. Here's a PEP about Function Attributes.
A:
I think you might be conflating the concepts of local variables and function attributes. For more information on Python function attributes, see the SO question Python function attributes - uses and abuses.
A:
@behindthefall, the motivation to give function objects generic assignable attributes (they didn't use to have them) was that, absent such possibilities, real and popular frameworks were abusing what few assignable attributes existed (typically __doc__) to record information about each given function object. So there was clearly a "pent-up demand" for this functionality, so Guido decided to address it directly (adding an optional dict to each function object to record its attributes isn't a big deal -- most function objects don't need it, and it is optional, so the cost is just 4 bytes for a null pointer;-).
Assigning such attributes in arbitrary places would be very bad practice, making the code harder to understand for no real benefit, but they're very useful when used in a controlled way -- for example, a decorator could usefully record all kinds of things about the function being decorated, and the context in which the decoration occurred, as attributes of the wrapper function, allowing trivially-easy introspection of such metadata to occur later at any time, as needed.
As other answers already pointed out, local variables (which are per-instance, not per-function object!) are a completely disjoint namespace from a function object's attributes held in its __dict__.
A:
In python, a namespace is just a dictionary object, mapping variable name as a string (in this case, 'guest') to a value (in this case, 'Harry'). So as long as you have access to an object, and it's mutable, you can change anything about its namespace.
On small projects, it's not a huge problem, and lets you hack things together faster, but incredibly confusing on larger projects, where your data could be modified from anywhere.
There are ways of making attributes of classes "more private", such as Name Mangling.
A:
tom.guest is just a property on the tom function object, it has nothing to do with the scope or locals() inside that function, and nothing to do with that fact that tom is a function, it would work on any object.
A:
I have used this in the past to make a self-contained function with "enums" that go along with it.
Suppose I were implementing a seek() function. The built-in Python one (on file objects) takes an integer to tell it how to operate; yuck, give me an enum please.
def seek(f, offset, whence=0):
return f.seek(offset, whence)
seek.START = 0
seek.RELATIVE = 1
seek.END = 2
f = open(filename)
seek(f, 0, seek.START) # seek to start of file
seek(f, 0, seek.END) # seek to end of file
What do you think, too tricky and weird? I do like how it keeps the "enum" values bundled together with the function; if you import the function from a module, you get its "enum" values as well, automatically.
A:
Python functions are lexically scoped so there is no way to add variables to the function outside of its defined scope.
However, the function still will have access to all parent scopes, if you really wanted to design the system like that (generally considered bad practice though):
>>> def foo():
>>> def bar():
>>> print x
>>> x = 1
>>> bar()
1
Mutating function variables is mostly a bad idea, since functions are assumed to be immutable. The most pythonic way of implementing this behavior is using classes and methods instead.
A:
Python API documentation generation tools, such as pydoc and epydoc, use introspection to determine a function's name and docstring (available as the __name__ and __doc__ attributes). Well-behaved function decorators are expected to preserve these attributes, so such tools continue to work as expected (i.e. decorating a function should preserve the decorated function's documentation). You do this by copying these attributes from the decorated function to the decorator. Take a look at update_wrapper in the functools module:
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
...
"""
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
...
So, that's at least one example where modifying function attributes is useful and accepted.
It some situations, it can be useful to "annotate" a function by setting an attribute; Django uses this in a few places:
You can set alters_data to True
on model methods that change the
database, preventing them from being
called in templates.
You can set
allow_tags on model methods that
will be displayed in the admin, to
signify that the method returns HTML
content, which shouldn't be
automatically escaped.
As always, use your judgement. If modifying attributes is accepted practice (for example, when writing a decorator), then by all means go ahead. If it's going to be part of a well documented API, it's probably fine too.
|
Python functions can be given new attributes from outside the scope?
|
I didn't know you could do this:
def tom():
print "tom's locals: ", locals()
def dick(z):
print "z.__name__ = ", z.__name__
z.guest = "Harry"
print "z.guest = ", z.guest
print "dick's locals: ", locals()
tom() #>>> tom's locals: {}
#print tom.guest #AttributeError: 'function' object has no attribute 'guest'
print "tom's dir:", dir(tom) # no 'guest' entry
dick( tom) #>>> z.__name__ = tom
#>>> z.guest = Harry
#>>> dick's locals: {'z': <function tom at 0x02819F30>}
tom() #>>> tom's locals: {}
#print dick.guest #AttributeError: 'function' object has no attribute 'guest'
print tom.guest #>>> Harry
print "tom's dir:", dir(tom) # 'guest' entry appears
Function tom() has no locals. Function dick() knows where tom() lives and puts up Harry as 'guest' over at tom()'s place. harry doesn't appear as a local at tom()'s place, but if you ask for tom's guest, harry answers. harry is a new attribute at tom().
UPDATE: From outside tom(), you can say "print dir(tom)" and see the the tom-object's dictionary. (You can do it from inside tom(), too. So tom could find out he had a new lodger, harry, going under the name of 'guest'.)
So, attributes can be added to a function's namespace from outside the function? Is that often done? Is it acceptable practice? Is it recommended in some situations? Is it actually vital at times? (Is it Pythonic?)
UPDATE: Title now says 'attributes'; it used to say 'variables'. Here's a PEP about Function Attributes.
|
[
"I think you might be conflating the concepts of local variables and function attributes. For more information on Python function attributes, see the SO question Python function attributes - uses and abuses.\n",
"@behindthefall, the motivation to give function objects generic assignable attributes (they didn't use to have them) was that, absent such possibilities, real and popular frameworks were abusing what few assignable attributes existed (typically __doc__) to record information about each given function object. So there was clearly a \"pent-up demand\" for this functionality, so Guido decided to address it directly (adding an optional dict to each function object to record its attributes isn't a big deal -- most function objects don't need it, and it is optional, so the cost is just 4 bytes for a null pointer;-).\nAssigning such attributes in arbitrary places would be very bad practice, making the code harder to understand for no real benefit, but they're very useful when used in a controlled way -- for example, a decorator could usefully record all kinds of things about the function being decorated, and the context in which the decoration occurred, as attributes of the wrapper function, allowing trivially-easy introspection of such metadata to occur later at any time, as needed.\nAs other answers already pointed out, local variables (which are per-instance, not per-function object!) are a completely disjoint namespace from a function object's attributes held in its __dict__.\n",
"In python, a namespace is just a dictionary object, mapping variable name as a string (in this case, 'guest') to a value (in this case, 'Harry'). So as long as you have access to an object, and it's mutable, you can change anything about its namespace.\nOn small projects, it's not a huge problem, and lets you hack things together faster, but incredibly confusing on larger projects, where your data could be modified from anywhere.\nThere are ways of making attributes of classes \"more private\", such as Name Mangling.\n",
"tom.guest is just a property on the tom function object, it has nothing to do with the scope or locals() inside that function, and nothing to do with that fact that tom is a function, it would work on any object.\n",
"I have used this in the past to make a self-contained function with \"enums\" that go along with it.\nSuppose I were implementing a seek() function. The built-in Python one (on file objects) takes an integer to tell it how to operate; yuck, give me an enum please.\ndef seek(f, offset, whence=0):\n return f.seek(offset, whence)\n\nseek.START = 0\nseek.RELATIVE = 1\nseek.END = 2\n\nf = open(filename)\n\nseek(f, 0, seek.START) # seek to start of file\nseek(f, 0, seek.END) # seek to end of file\n\nWhat do you think, too tricky and weird? I do like how it keeps the \"enum\" values bundled together with the function; if you import the function from a module, you get its \"enum\" values as well, automatically.\n",
"Python functions are lexically scoped so there is no way to add variables to the function outside of its defined scope.\nHowever, the function still will have access to all parent scopes, if you really wanted to design the system like that (generally considered bad practice though):\n>>> def foo():\n>>> def bar():\n>>> print x\n>>> x = 1\n>>> bar()\n1\n\nMutating function variables is mostly a bad idea, since functions are assumed to be immutable. The most pythonic way of implementing this behavior is using classes and methods instead.\n",
"Python API documentation generation tools, such as pydoc and epydoc, use introspection to determine a function's name and docstring (available as the __name__ and __doc__ attributes). Well-behaved function decorators are expected to preserve these attributes, so such tools continue to work as expected (i.e. decorating a function should preserve the decorated function's documentation). You do this by copying these attributes from the decorated function to the decorator. Take a look at update_wrapper in the functools module:\nWRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')\nWRAPPER_UPDATES = ('__dict__',)\n\ndef update_wrapper(wrapper,\n wrapped,\n assigned = WRAPPER_ASSIGNMENTS,\n updated = WRAPPER_UPDATES):\n \"\"\"Update a wrapper function to look like the wrapped function\n\n wrapper is the function to be updated\n wrapped is the original function\n ...\n \"\"\"\n for attr in assigned:\n setattr(wrapper, attr, getattr(wrapped, attr))\n for attr in updated:\n getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n ...\n\nSo, that's at least one example where modifying function attributes is useful and accepted.\nIt some situations, it can be useful to \"annotate\" a function by setting an attribute; Django uses this in a few places: \n\nYou can set alters_data to True\non model methods that change the\ndatabase, preventing them from being\ncalled in templates. \nYou can set\nallow_tags on model methods that\nwill be displayed in the admin, to\nsignify that the method returns HTML\ncontent, which shouldn't be\nautomatically escaped.\n\nAs always, use your judgement. If modifying attributes is accepted practice (for example, when writing a decorator), then by all means go ahead. If it's going to be part of a well documented API, it's probably fine too.\n"
] |
[
4,
4,
3,
1,
1,
0,
0
] |
[] |
[] |
[
"attributes",
"namespaces",
"python",
"scope"
] |
stackoverflow_0001753232_attributes_namespaces_python_scope.txt
|
Q:
Can this breadth-first search be made faster?
I have a data set which is a large unweighted cyclic graph The cycles occur in loops of about 5-6 paths. It consists of about 8000 nodes and each node has from 1-6 (usually about 4-5) connections. I'm doing single pair shortest path calculations and have implemented the following code to do a breadth-first search.
from Queue import Queue
q = Queue()
parent = {}
fromNode = 'E1123'
toNode = 'A3455'
# path finding
q.put(fromNode)
parent[fromNode] = 'Root'
while not q.empty():
# get the next node and add its neighbours to queue
current = q.get()
for i in getNeighbours(current):
# note parent and only continue if not already visited
if i[0] not in parent:
parent[i[0]] = current
q.put(i[0])
# check if destination
if current == toNode:
print 'arrived at', toNode
break
The above code uses the Python 2.6 Queue module and getNeighbours() is simply a subroutine that makes a single MySQL call and returns the neighbours as a list of tuples e.g. (('foo',),('bar',)). The SQL call is quick.
The code works ok however testing to down to depths of about 7 layers takes about 20 seconds to run (2.5GHz Intel 4GB RAM OS X 10.6)
I'd welcome any comments about how to improve the run time of this code.
A:
Well, given the upvotes on the comment, I'll make it an answer now.
The SQL in the tight loop is definitely slowing you down. I don't care how fast the call is. Think about it -- you're asking for a query to be parsed, a lookup to be run -- as fast as that is, it's still in a tight loop. What does your data set look like? Can you just SELECT the entire data set into memory, or at least work with it outside of MySQL?
If you work with that data in memory, you will see a significant performance gain.
A:
Something like this:
#!/usr/bin/env python
from Queue import Queue
def traverse_path(fromNode, toNode, nodes):
def getNeighbours(current, nodes):
return nodes[current] if current in nodes else []
def make_path(toNode, graph):
result = []
while 'Root' != toNode:
result.append(toNode)
toNode = graph[toNode]
result.reverse()
return result
q = Queue()
q.put(fromNode)
graph = {fromNode: 'Root'}
while not q.empty():
# get the next node and add its neighbours to queue
current = q.get()
for neighbor in getNeighbours(current, nodes):
# use neighbor only continue if not already visited
if neighbor not in graph:
graph[neighbor] = current
q.put(neighbor)
# check if destination
if current == toNode:
return make_path(toNode, graph)
return []
if __name__ == '__main__':
nodes = {
'E1123': ['D111', 'D222', 'D333', 'D444'],
'D111': ['C01', 'C02', 'C04'],
'D222': ['C11', 'C03', 'C05'],
'D333': ['C01'],
'C02': ['B1'],
'B1': ['A3455']
}
result = traverse_path('E1123', 'A3455', nodes)
print result
['E1123', 'D111', 'C02', 'B1', 'A3455']
If you replace your SQL queries with a dictionary of lists (and that would be the tricky part), you will get this performance.
A:
I'll bet that machine has more than one core, doesn't it? Run it in parallel.
Python Threading
A:
Hmm, doesn't BFS involve marking nodes you've already seen so you don't visit them again?
|
Can this breadth-first search be made faster?
|
I have a data set which is a large unweighted cyclic graph The cycles occur in loops of about 5-6 paths. It consists of about 8000 nodes and each node has from 1-6 (usually about 4-5) connections. I'm doing single pair shortest path calculations and have implemented the following code to do a breadth-first search.
from Queue import Queue
q = Queue()
parent = {}
fromNode = 'E1123'
toNode = 'A3455'
# path finding
q.put(fromNode)
parent[fromNode] = 'Root'
while not q.empty():
# get the next node and add its neighbours to queue
current = q.get()
for i in getNeighbours(current):
# note parent and only continue if not already visited
if i[0] not in parent:
parent[i[0]] = current
q.put(i[0])
# check if destination
if current == toNode:
print 'arrived at', toNode
break
The above code uses the Python 2.6 Queue module and getNeighbours() is simply a subroutine that makes a single MySQL call and returns the neighbours as a list of tuples e.g. (('foo',),('bar',)). The SQL call is quick.
The code works ok however testing to down to depths of about 7 layers takes about 20 seconds to run (2.5GHz Intel 4GB RAM OS X 10.6)
I'd welcome any comments about how to improve the run time of this code.
|
[
"Well, given the upvotes on the comment, I'll make it an answer now.\nThe SQL in the tight loop is definitely slowing you down. I don't care how fast the call is. Think about it -- you're asking for a query to be parsed, a lookup to be run -- as fast as that is, it's still in a tight loop. What does your data set look like? Can you just SELECT the entire data set into memory, or at least work with it outside of MySQL?\nIf you work with that data in memory, you will see a significant performance gain.\n",
"Something like this:\n#!/usr/bin/env python\n\nfrom Queue import Queue\n\ndef traverse_path(fromNode, toNode, nodes):\n def getNeighbours(current, nodes):\n return nodes[current] if current in nodes else []\n\n def make_path(toNode, graph):\n result = []\n while 'Root' != toNode:\n result.append(toNode)\n toNode = graph[toNode]\n result.reverse()\n return result\n\n q = Queue()\n q.put(fromNode)\n graph = {fromNode: 'Root'}\n\n while not q.empty():\n # get the next node and add its neighbours to queue\n current = q.get()\n for neighbor in getNeighbours(current, nodes):\n # use neighbor only continue if not already visited\n if neighbor not in graph:\n graph[neighbor] = current\n q.put(neighbor)\n\n # check if destination\n if current == toNode:\n return make_path(toNode, graph)\n return []\n\nif __name__ == '__main__':\n nodes = {\n 'E1123': ['D111', 'D222', 'D333', 'D444'],\n 'D111': ['C01', 'C02', 'C04'],\n 'D222': ['C11', 'C03', 'C05'],\n 'D333': ['C01'],\n 'C02': ['B1'],\n 'B1': ['A3455']\n }\n result = traverse_path('E1123', 'A3455', nodes)\n print result\n\n['E1123', 'D111', 'C02', 'B1', 'A3455']\n\nIf you replace your SQL queries with a dictionary of lists (and that would be the tricky part), you will get this performance.\n",
"I'll bet that machine has more than one core, doesn't it? Run it in parallel. \nPython Threading\n",
"Hmm, doesn't BFS involve marking nodes you've already seen so you don't visit them again?\n"
] |
[
11,
1,
0,
0
] |
[] |
[] |
[
"algorithm",
"breadth_first_search",
"computer_science",
"python"
] |
stackoverflow_0001753257_algorithm_breadth_first_search_computer_science_python.txt
|
Q:
How can I append data to a text file with a line break using Python?
I've just been asked to come up with a script to find files with a certain filename length. I've decided to try out Python for the first time for this task as I've always wanted to learn it.
I've got the script to find the files and append them to a text file but it does not write a line break for each new entry. Is there a way to do this as the current output is almost unreadable?
A:
You just need to explicitly append a '\n' each time you want a line break -- if you're appending to the output file in text mode, this will expand to the proper line separation where needed (e.g. Windows). (You could use os.linesep instead, if you had to output in binary mode for some reason, but that's a pretty unusual use case -- normally, text mode and \n are much better).
A:
I am wondering why you don't have a line break when you print. an example.
>>> import os
>>> for files in os.listdir("."):
... if os.path.isfile(files):
... print "file: ",files," length: ",len(files)
...
file: test1 length: 5
file: shell.sh length: 8
file: test.txt length: 8
|
How can I append data to a text file with a line break using Python?
|
I've just been asked to come up with a script to find files with a certain filename length. I've decided to try out Python for the first time for this task as I've always wanted to learn it.
I've got the script to find the files and append them to a text file but it does not write a line break for each new entry. Is there a way to do this as the current output is almost unreadable?
|
[
"You just need to explicitly append a '\\n' each time you want a line break -- if you're appending to the output file in text mode, this will expand to the proper line separation where needed (e.g. Windows). (You could use os.linesep instead, if you had to output in binary mode for some reason, but that's a pretty unusual use case -- normally, text mode and \\n are much better).\n",
"I am wondering why you don't have a line break when you print. an example.\n>>> import os\n>>> for files in os.listdir(\".\"):\n... if os.path.isfile(files):\n... print \"file: \",files,\" length: \",len(files)\n...\nfile: test1 length: 5\nfile: shell.sh length: 8\nfile: test.txt length: 8 \n\n"
] |
[
10,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001752019_python.txt
|
Q:
What conditions cause Tokyo Cabinet to block
I'm using Tokyo Cabinet with the tc module in python. I store my data in the TDB format. I expected the table to block only for the duration of a write. Unfortunately, I see that when the file is open with in the "writer mode", other processes cannot read from it. Is that a standard behaviour, wrappers problem, or am I doing something wrong? Or maybe there are other cases when the operations are blocked?
A:
According to specification:
Tokyo Cabinet provides two modes to
connect to a database: "reader" and
"writer". A reader can perform
retrieving but neither storing nor
deleting. A writer can perform all
access methods. Exclusion control
between processes is performed when
connecting to a database by file
locking. While a writer is connected
to a database, neither readers nor
writers can be connected. While a
reader is connected to a database,
other readers can be connect, but
writers can not. According to this
mechanism, data consistency is
guaranteed with simultaneous
connections in multitasking
environment.
You have either create and close writer for each write operation or use Tokyo Tyrant to provide concurrent access.
|
What conditions cause Tokyo Cabinet to block
|
I'm using Tokyo Cabinet with the tc module in python. I store my data in the TDB format. I expected the table to block only for the duration of a write. Unfortunately, I see that when the file is open with in the "writer mode", other processes cannot read from it. Is that a standard behaviour, wrappers problem, or am I doing something wrong? Or maybe there are other cases when the operations are blocked?
|
[
"According to specification:\n\nTokyo Cabinet provides two modes to\n connect to a database: \"reader\" and\n \"writer\". A reader can perform\n retrieving but neither storing nor\n deleting. A writer can perform all\n access methods. Exclusion control\n between processes is performed when\n connecting to a database by file\n locking. While a writer is connected\n to a database, neither readers nor\n writers can be connected. While a\n reader is connected to a database,\n other readers can be connect, but\n writers can not. According to this\n mechanism, data consistency is\n guaranteed with simultaneous\n connections in multitasking\n environment.\n\nYou have either create and close writer for each write operation or use Tokyo Tyrant to provide concurrent access.\n"
] |
[
5
] |
[] |
[] |
[
"blocking",
"python",
"tokyo_cabinet"
] |
stackoverflow_0001752454_blocking_python_tokyo_cabinet.txt
|
Q:
DOM related question and problem
these day im making python script related with DOM.
problem is these day many website structure is very complicate .
what is best method to check DOM structure and path..
i mean...following is some example.
what is best method to check can extract such like following info quickly?
before i was spent much time to extract such info .
and yes im also new to python and DOM.
IE.Document.Frames(1).Document.forms('comment').value = 'hello'
if i use DOM inspector, can i extract such info quickly ? if so would you show me some sample?
here is some site . i want to extract some dom info.
today i was spent all day long to extract what is dom info. but failed
http://www.segye.com/Articles/News/Politics/Article.asp?aid=20091118001261&ctg1=06&ctg2=00&subctg1=06&subctg2=00&cid=0101010600000
at the end of this page,can find some comment input box.
i want to know what kind of dom element should have to use, such like
IE.Document.Frames(1).Document.forms('comment').value = 'hello'
anyhelp much appreciate thanks
A:
I would hope that you've read Python's implementation of the DOM and here's a good tutorial. Alternatively, if you know javascript jQuery makes it incredibly easy to DOM parse and manipulate the DOM, as seen here. Now if you're just trying to get someone to parse it for you, good luck.
|
DOM related question and problem
|
these day im making python script related with DOM.
problem is these day many website structure is very complicate .
what is best method to check DOM structure and path..
i mean...following is some example.
what is best method to check can extract such like following info quickly?
before i was spent much time to extract such info .
and yes im also new to python and DOM.
IE.Document.Frames(1).Document.forms('comment').value = 'hello'
if i use DOM inspector, can i extract such info quickly ? if so would you show me some sample?
here is some site . i want to extract some dom info.
today i was spent all day long to extract what is dom info. but failed
http://www.segye.com/Articles/News/Politics/Article.asp?aid=20091118001261&ctg1=06&ctg2=00&subctg1=06&subctg2=00&cid=0101010600000
at the end of this page,can find some comment input box.
i want to know what kind of dom element should have to use, such like
IE.Document.Frames(1).Document.forms('comment').value = 'hello'
anyhelp much appreciate thanks
|
[
"I would hope that you've read Python's implementation of the DOM and here's a good tutorial. Alternatively, if you know javascript jQuery makes it incredibly easy to DOM parse and manipulate the DOM, as seen here. Now if you're just trying to get someone to parse it for you, good luck. \n"
] |
[
2
] |
[] |
[] |
[
"dom",
"python"
] |
stackoverflow_0001754675_dom_python.txt
|
Q:
Get Intervals Between Two Times
A User will specify a time interval of n secs/mins/hours and then two times (start / stop).
I need to be able to take this interval, and then step through the start and stop times, in order to get a list of these times. Then after this, I will perform a database look up via a table.objects.filter, in order to retrieve the data corresponding to each time.
I'm making some ridiculously long algorithms at the moment and I'm positive there could be an easier way to do this. That is, a more pythonic way. Thoughts?
A:
Are you looking for something like this? (pseudo code)
t = start
while t != stop:
t += interval
table.objects.filter(t)
A:
it fits nicely as a generator, too:
def timeseq(start,stop,interval):
while start <= stop:
yield start
start += interval
used as:
for t in timeseq(start,stop,interval):
table.objects.filter(t)
or:
data = [table.objects.filter(t) for t in timeseq(start,stop,interval)]
A:
What about ...
result = RelevantModel.objects.filter(relavant_field__in=[
start + interval * i
for i in xrange((start - end).seconds / interval.seconds)
])
... ?
I can't imagine this is very different from what you're already doing, but perhaps it's more compact (particularly if you weren't using foo__in=[bar] or a list comprehension). Of course start and end would be datetime.datetime objects and interval would be a datetime.timedelta object.
|
Get Intervals Between Two Times
|
A User will specify a time interval of n secs/mins/hours and then two times (start / stop).
I need to be able to take this interval, and then step through the start and stop times, in order to get a list of these times. Then after this, I will perform a database look up via a table.objects.filter, in order to retrieve the data corresponding to each time.
I'm making some ridiculously long algorithms at the moment and I'm positive there could be an easier way to do this. That is, a more pythonic way. Thoughts?
|
[
"Are you looking for something like this? (pseudo code)\nt = start \nwhile t != stop: \n t += interval \n table.objects.filter(t) \n\n",
"it fits nicely as a generator, too:\ndef timeseq(start,stop,interval):\n while start <= stop:\n yield start\n start += interval\n\nused as:\nfor t in timeseq(start,stop,interval):\n table.objects.filter(t)\n\nor:\ndata = [table.objects.filter(t) for t in timeseq(start,stop,interval)]\n\n",
"What about ...\nresult = RelevantModel.objects.filter(relavant_field__in=[\n start + interval * i \n for i in xrange((start - end).seconds / interval.seconds)\n]) \n\n... ?\nI can't imagine this is very different from what you're already doing, but perhaps it's more compact (particularly if you weren't using foo__in=[bar] or a list comprehension). Of course start and end would be datetime.datetime objects and interval would be a datetime.timedelta object.\n"
] |
[
4,
4,
1
] |
[] |
[] |
[
"datetime",
"django",
"python"
] |
stackoverflow_0001754781_datetime_django_python.txt
|
Q:
How to kill headless X server started via Python?
I want to get screenshots of a webpage in Python. For this I am using http://github.com/AdamN/python-webkit2png/ .
newArgs = ["xvfb-run", "--server-args=-screen 0, 640x480x24", sys.argv[0]]
for i in range(1, len(sys.argv)):
if sys.argv[i] not in ["-x", "--xvfb"]:
newArgs.append(sys.argv[i])
logging.debug("Executing %s" % " ".join(newArgs))
os.execvp(newArgs[0], newArgs)
Basically calls xvfb-run with the correct args. But man xvfb says:
Note that the demo X clients used in the above examples will not exit on their own, so they will have to be killed before xvfb-run will exit.
So that means that this script will <????> if this whole thing is in a loop, (To get multiple screenshots) unless the X server is killed. How can I do that?
A:
The documentation for os.execvp states:
These functions all execute a new
program, replacing the current
process; they do not return. [..]
So after calling os.execvp no other statement in the program will be executed. You may want to use subprocess.Popen instead:
The subprocess module allows you to
spawn new processes, connect to their
input/output/error pipes, and obtain
their return codes. This module
intends to replace several other,
older modules and functions, such as:
Using subprocess.Popen, the code to run xlogo in the virtual framebuffer X server becomes:
import subprocess
xvfb_args = ['xvfb-run', '--server-args=-screen 0, 640x480x24', 'xlogo']
process = subprocess.Popen(xvfb_args)
Now the problem is that xvfb-run launches Xvfb in a background process. Calling process.kill() will not kill Xvfb (at least not on my machine...). I have been fiddling around with this a bit, and so far the only thing that works for me is:
import os
import signal
import subprocess
SERVER_NUM = 99 # 99 is the default used by xvfb-run; you can leave this out.
xvfb_args = ['xvfb-run', '--server-num=%d' % SERVER_NUM,
'--server-args=-screen 0, 640x480x24', 'xlogo']
subprocess.Popen(xvfb_args)
# ... do whatever you want to do here...
pid = int(open('/tmp/.X%s-lock' % SERVER_NUM).read().strip())
os.kill(pid, signal.SIGINT)
So this code reads the process ID of Xvfb from /tmp/.X99-lock and sends the process an interrupt. It works, but does yield an error message every now and then (I suppose you can ignore it, though). Hopefully somebody else can provide a more elegant solution. Cheers.
|
How to kill headless X server started via Python?
|
I want to get screenshots of a webpage in Python. For this I am using http://github.com/AdamN/python-webkit2png/ .
newArgs = ["xvfb-run", "--server-args=-screen 0, 640x480x24", sys.argv[0]]
for i in range(1, len(sys.argv)):
if sys.argv[i] not in ["-x", "--xvfb"]:
newArgs.append(sys.argv[i])
logging.debug("Executing %s" % " ".join(newArgs))
os.execvp(newArgs[0], newArgs)
Basically calls xvfb-run with the correct args. But man xvfb says:
Note that the demo X clients used in the above examples will not exit on their own, so they will have to be killed before xvfb-run will exit.
So that means that this script will <????> if this whole thing is in a loop, (To get multiple screenshots) unless the X server is killed. How can I do that?
|
[
"The documentation for os.execvp states:\n\nThese functions all execute a new\n program, replacing the current\n process; they do not return. [..]\n\nSo after calling os.execvp no other statement in the program will be executed. You may want to use subprocess.Popen instead:\n\nThe subprocess module allows you to\n spawn new processes, connect to their\n input/output/error pipes, and obtain\n their return codes. This module\n intends to replace several other,\n older modules and functions, such as:\n\nUsing subprocess.Popen, the code to run xlogo in the virtual framebuffer X server becomes:\nimport subprocess\nxvfb_args = ['xvfb-run', '--server-args=-screen 0, 640x480x24', 'xlogo']\nprocess = subprocess.Popen(xvfb_args)\n\nNow the problem is that xvfb-run launches Xvfb in a background process. Calling process.kill() will not kill Xvfb (at least not on my machine...). I have been fiddling around with this a bit, and so far the only thing that works for me is:\nimport os\nimport signal\nimport subprocess\n\nSERVER_NUM = 99 # 99 is the default used by xvfb-run; you can leave this out.\n\nxvfb_args = ['xvfb-run', '--server-num=%d' % SERVER_NUM,\n '--server-args=-screen 0, 640x480x24', 'xlogo']\nsubprocess.Popen(xvfb_args)\n\n# ... do whatever you want to do here...\n\npid = int(open('/tmp/.X%s-lock' % SERVER_NUM).read().strip())\nos.kill(pid, signal.SIGINT)\n\nSo this code reads the process ID of Xvfb from /tmp/.X99-lock and sends the process an interrupt. It works, but does yield an error message every now and then (I suppose you can ignore it, though). Hopefully somebody else can provide a more elegant solution. Cheers.\n"
] |
[
5
] |
[] |
[] |
[
"python",
"screenshot",
"xserver"
] |
stackoverflow_0001747022_python_screenshot_xserver.txt
|
Q:
How do I get stdout from tcl into a python string variable when using tkinter?
I have the following python code...
import Tkinter
root = Tkinter.Tk()
root.tk.eval('puts {printed by tcl}')
It prints "printed by tcl" to the screen. How can I capture what the tcl interpreter prints to the screen into a python string.
This is a simplified example of what I am doing. I have an automation system written in python but a new piece of equipment that is controlled by a tcl api. Each tcl command prints things like "connected" or "connection failed", I need to be able to capture these into python strings, so the automation system can tell what is going on, so for example if the device does not connect the automation system can retry the connection command.
Cheers
From Nick
A:
If the code you are running prints to screen and you're calling it with root.tk.eval() you can't capture that. However, You can redefine what "puts" does in the tcl code and have it do whatever you want. This is part of the beauty of Tcl -- there are no reserved words.
Simply create a proc named "puts" in the tcl interpreter, though make sure it has the exact same interface (ie: respects "-nonewline", can write to files, etc). When the puts normally prints to the screen you can instead have it do whatever you want, such as write to a socket or merely return the string it's supposed to print.
Roughly (untested, and ignoring the case with -nonewline):
root.tk.eval('''
rename puts original_puts
proc puts {args} {
if {[llength $args] == 1} {
return "=> [lindex $args 0]"
} else {
eval original_puts $args
}
}
''')
foo = root.tk.eval('puts "hello, world"')
print foo
=> hello, world
It will require a little diligence to make sure you don't break the tcl code which expects a standard "puts" statement, but it's not that hard to do. Just make sure you have special cases for one argument, the first argument of "-nonewline", and where there are two arguments (file descriptor and string).
It might get complicated if you call eval and it does two puts statements, or does a puts and then some other code, since the result of the eval is the result of the last statement. However, you can work around that by having puts buffer its output to a global variable and then return the result of that variable each time you do an eval.
So, think outside the box a little and you can find a solution. Tcl is very flexible.
|
How do I get stdout from tcl into a python string variable when using tkinter?
|
I have the following python code...
import Tkinter
root = Tkinter.Tk()
root.tk.eval('puts {printed by tcl}')
It prints "printed by tcl" to the screen. How can I capture what the tcl interpreter prints to the screen into a python string.
This is a simplified example of what I am doing. I have an automation system written in python but a new piece of equipment that is controlled by a tcl api. Each tcl command prints things like "connected" or "connection failed", I need to be able to capture these into python strings, so the automation system can tell what is going on, so for example if the device does not connect the automation system can retry the connection command.
Cheers
From Nick
|
[
"If the code you are running prints to screen and you're calling it with root.tk.eval() you can't capture that. However, You can redefine what \"puts\" does in the tcl code and have it do whatever you want. This is part of the beauty of Tcl -- there are no reserved words. \nSimply create a proc named \"puts\" in the tcl interpreter, though make sure it has the exact same interface (ie: respects \"-nonewline\", can write to files, etc). When the puts normally prints to the screen you can instead have it do whatever you want, such as write to a socket or merely return the string it's supposed to print.\nRoughly (untested, and ignoring the case with -nonewline):\nroot.tk.eval('''\nrename puts original_puts \nproc puts {args} {\n if {[llength $args] == 1} {\n return \"=> [lindex $args 0]\"\n } else {\n eval original_puts $args\n }\n}\n''')\n\nfoo = root.tk.eval('puts \"hello, world\"')\nprint foo\n=> hello, world\n\nIt will require a little diligence to make sure you don't break the tcl code which expects a standard \"puts\" statement, but it's not that hard to do. Just make sure you have special cases for one argument, the first argument of \"-nonewline\", and where there are two arguments (file descriptor and string).\nIt might get complicated if you call eval and it does two puts statements, or does a puts and then some other code, since the result of the eval is the result of the last statement. However, you can work around that by having puts buffer its output to a global variable and then return the result of that variable each time you do an eval. \nSo, think outside the box a little and you can find a solution. Tcl is very flexible.\n"
] |
[
5
] |
[] |
[] |
[
"python",
"tcl",
"tkinter"
] |
stackoverflow_0001755415_python_tcl_tkinter.txt
|
Q:
Converting RE code from PHP to Python
I have done a simple program in PHP, now need to convert this into Python:
$string="Google 1600 Amphitheatre Parkway Mountain View, CA 94043 phone";
preg_match_all('/[0-9]+.{10,25}[^0-9]*[0-9]{5,6}+\s/',$string,$matches);
print_r($matches);
A:
import re
for x in re.findall('[0-9]+.{10,25}[^0-9]*[0-9]{5,6}\s',STRING):print x
will be ok for you?
A:
In python, you must use the "re" module to do that. Unlike in PHP, you don't need to place delimitors, so strip the "/" you have at the begining and the end of the pattern.
The Python idiom would then be :
import re
string="Input values"
for match in re.findall('[0-9]+.{10,25}[^0-9]*[0-9]{5,6}\s',string) :
print match
We rarely use some pretty print tools such as "print_r" in Python because most of the time, iterators and str() do the trick. So here, a simple for loop will do the job.
|
Converting RE code from PHP to Python
|
I have done a simple program in PHP, now need to convert this into Python:
$string="Google 1600 Amphitheatre Parkway Mountain View, CA 94043 phone";
preg_match_all('/[0-9]+.{10,25}[^0-9]*[0-9]{5,6}+\s/',$string,$matches);
print_r($matches);
|
[
"import re\nfor x in re.findall('[0-9]+.{10,25}[^0-9]*[0-9]{5,6}\\s',STRING):print x\n\nwill be ok for you?\n",
"In python, you must use the \"re\" module to do that. Unlike in PHP, you don't need to place delimitors, so strip the \"/\" you have at the begining and the end of the pattern.\nThe Python idiom would then be :\nimport re\nstring=\"Input values\"\nfor match in re.findall('[0-9]+.{10,25}[^0-9]*[0-9]{5,6}\\s',string) : \n print match\n\nWe rarely use some pretty print tools such as \"print_r\" in Python because most of the time, iterators and str() do the trick. So here, a simple for loop will do the job.\n"
] |
[
1,
0
] |
[
"import re\nstring = \"Input values\"\nmatch = re.match('/[0-9]+.{10,25}[^0-9]*[0-9]{5,6}\\s/', s)\nprint match\n\nthis should be what you're looking for, if the RegEx is right.\n"
] |
[
-1
] |
[
"php",
"python",
"regex"
] |
stackoverflow_0001755706_php_python_regex.txt
|
Q:
lazy load or early load for python?
We've got the following code sample:
big_static_data = {
"key1" : {
"subkey1" : "subvalue1",
...
},
"key2" :
...
}
class StaticDataEarlyLoad:
def __init__(self):
self.static_data = big_static_data
# other init
def handle_use_id(self, id):
return complex_handle(self.static_data, id)
...
class StaticDataLazyLoad:
def __init__(self):
# not init static data
# other init
def handle_use_id(self, id):
return complex_handle(big_static_data, id)
...
Just as the above codes say, whenever we call the instance's handle_use_id, we may get different performance issues.
IMO, early load will load the data when the instance is created, and will be in memory till the instance is garbaged. And for late load, the static data won't be loaded till we call the handle_use_id method. Am I right? (Since I'm not so clear with Python's internal, I'm not sure how long the instance will last till garbaged). And If I'm right, the early load means a big memory requirement and the late load means we have to load the data each time when invoking the method( a big overhead?)
Now, we are a web based project, So which should be selected as the best approach? (handle_use_id will be invoked very frequently.)
Thanks.
A:
In your example, StaticDataLazyLoad (once the syntax for init is correct) wont make a big difference.
"big_static_data" is initialized ("loaded") when the module is imported. It will immediately require some memory, no matter whether an instance of your classes is created or not.
An instance of StaticDataEarlyLoad will just create a new reference to big_static_data, not a new copy.
Thus, a lookup in StaticDataEarlyLoad may be slightly faster, since the data is referenced via self in the local scope (lookup "self", then lookup "self.static_data").
A lookup in StaticDataLazyLoad will not find "big_static_data" in the local scope, python will then look it up in the global scope and find it. Since the global scope is probably larger, this lookup may take longer than the lookup of "self.static_data".
A:
big_static_data is created once at the beginning of the file (at least in the code that you show).
This consumes memory.
When you create an instance of StaticDataEarlyLoad,
StaticDataEarlyLoad().static_data is a reference to big_static_data.
It consumes a very minor amount of memory. It merely points at the same dictionary that big_static_data points to. No copy of big_static_data is made, there is no real "loading" going on.
When instance StaticDataEarlyLoad() gets garbage-collected, a little memory is freed, but the big_static_data remains.
StaticDataLazyLoad does much the same thing, but doesn't create an attribute static_data. It just references big_static_data directly. The difference in memory consumption between StaticDataEarlyLoad and StaticDataLazyLoad is very minor. And there will be essentially no difference in speed.
it is always best to make explicit what a class depends upon.
StaticDataEarlyLoad depends on big_static_data.
Therefore, you should define
class StaticDataEarlyLoad:
def __init__(self,static_data):
self.static_data = static_data
And initialize instances with StaticDataEarlyLoad(big_static_data).
There is essentially no difference in speed between this definition and the one you posted. Putting dependencies into the call signature of __init__ is just a good idea for the sake of organization, and after all you are using Python's OOP for good control of organization, right?
|
lazy load or early load for python?
|
We've got the following code sample:
big_static_data = {
"key1" : {
"subkey1" : "subvalue1",
...
},
"key2" :
...
}
class StaticDataEarlyLoad:
def __init__(self):
self.static_data = big_static_data
# other init
def handle_use_id(self, id):
return complex_handle(self.static_data, id)
...
class StaticDataLazyLoad:
def __init__(self):
# not init static data
# other init
def handle_use_id(self, id):
return complex_handle(big_static_data, id)
...
Just as the above codes say, whenever we call the instance's handle_use_id, we may get different performance issues.
IMO, early load will load the data when the instance is created, and will be in memory till the instance is garbaged. And for late load, the static data won't be loaded till we call the handle_use_id method. Am I right? (Since I'm not so clear with Python's internal, I'm not sure how long the instance will last till garbaged). And If I'm right, the early load means a big memory requirement and the late load means we have to load the data each time when invoking the method( a big overhead?)
Now, we are a web based project, So which should be selected as the best approach? (handle_use_id will be invoked very frequently.)
Thanks.
|
[
"In your example, StaticDataLazyLoad (once the syntax for init is correct) wont make a big difference.\n\"big_static_data\" is initialized (\"loaded\") when the module is imported. It will immediately require some memory, no matter whether an instance of your classes is created or not.\nAn instance of StaticDataEarlyLoad will just create a new reference to big_static_data, not a new copy.\nThus, a lookup in StaticDataEarlyLoad may be slightly faster, since the data is referenced via self in the local scope (lookup \"self\", then lookup \"self.static_data\").\nA lookup in StaticDataLazyLoad will not find \"big_static_data\" in the local scope, python will then look it up in the global scope and find it. Since the global scope is probably larger, this lookup may take longer than the lookup of \"self.static_data\".\n",
"big_static_data is created once at the beginning of the file (at least in the code that you show).\nThis consumes memory.\nWhen you create an instance of StaticDataEarlyLoad, \nStaticDataEarlyLoad().static_data is a reference to big_static_data.\nIt consumes a very minor amount of memory. It merely points at the same dictionary that big_static_data points to. No copy of big_static_data is made, there is no real \"loading\" going on.\nWhen instance StaticDataEarlyLoad() gets garbage-collected, a little memory is freed, but the big_static_data remains.\nStaticDataLazyLoad does much the same thing, but doesn't create an attribute static_data. It just references big_static_data directly. The difference in memory consumption between StaticDataEarlyLoad and StaticDataLazyLoad is very minor. And there will be essentially no difference in speed.\nit is always best to make explicit what a class depends upon.\nStaticDataEarlyLoad depends on big_static_data.\nTherefore, you should define\nclass StaticDataEarlyLoad:\n def __init__(self,static_data):\n self.static_data = static_data\n\nAnd initialize instances with StaticDataEarlyLoad(big_static_data).\nThere is essentially no difference in speed between this definition and the one you posted. Putting dependencies into the call signature of __init__ is just a good idea for the sake of organization, and after all you are using Python's OOP for good control of organization, right? \n"
] |
[
3,
3
] |
[] |
[] |
[
"performance",
"python"
] |
stackoverflow_0001756276_performance_python.txt
|
Q:
Custom traversal and page templates
Using Marius Gedminas's excellent blog post, I have created a custom traverser for a folder in my site.
This allows me to show: http://foo.com/folder/random_id
Instead of: http://foo.com/folder/object.html?id=random_id
The configuration side works great, I can catch the random_ids and search through my messages for the correct one, ready to display.
My problem is that I'm unsure how to then display the data via my usual page templates - at the TODO point in his original code ;)
if name == 'mycalendar':
mycalendar = ... # TODO: do something to get the appropriate object
return mycalendar
Usually I'd use something similar to:
class Test(BrowserPage):
template = ViewPageTemplateFile('atest.pt')
def __call__(self):
return self.template()
But I can't work out how to do this correctly in the context of the custom traversal.
UPDATE: To be clear I want to avoid adding anything else to the url (No: http://foo.com/folder/random_id/read).
I don't need the view to be available via any other address (No: http://foo.com/folder/read)
The ZCML for the view I'd like to use is:
<browser:page
for="foo.interfaces.IFooFolderContainer"
name="read"
template="read.pt"
permission="zope.ManageContent"
/>
I'm guessing (on further advice), something along the lines of:
return getMultiAdapter((mycalendar, self.request), IPageTemplate, name=u'read')
Or even a default view for the object type (a dict in this case) that's being returned:
<browser:page
for="dict"
name="read"
template="read.pt"
permission="zope.ManageContent"
/>
A:
It would be easier to answer your question if you showed what your custom traverser is doing.
Essentially, you want something like this:
def publishTraverse(self, request, name):
if name in self.context:
return MyMessageView(self.context[name], request)
# fall back to views such as index.html
view = queryMultiAdapter((self.context, request), name=name)
if view is not None:
return view
# give up and return a 404 Not Found error page
raise NotFound(self.context, name, request)
where MyMessageView can be something as simple as
class MyMessageView(BrowserPage):
__call__ = ViewPageTemplateFile('read.pt')
Disclaimer: I'm not sure if the view you instantiate directly will be protected by a security wrapper; make sure your functional tests ensure anonymous users can't view messages if that's what you want.
A:
If you end up at a proper object with your custom traverser, you can just tack on the template name and user "context" in that template. So http://foo.com/folder/random_id/my_template and in the template do the normal <h1 tal:content="context/title" /> stuff.
A:
IIUC, what you want is to render the 'read' view when somebody requests /folder/random_id. If that's the case, all you need to do is make your traversal return an object (IFolderContent, maybe) representing a random_id and specify the 'view' page as the defaultView for IFolderContent.
The defaultView is needed because there's no view specified for the random_id object in your URL.
|
Custom traversal and page templates
|
Using Marius Gedminas's excellent blog post, I have created a custom traverser for a folder in my site.
This allows me to show: http://foo.com/folder/random_id
Instead of: http://foo.com/folder/object.html?id=random_id
The configuration side works great, I can catch the random_ids and search through my messages for the correct one, ready to display.
My problem is that I'm unsure how to then display the data via my usual page templates - at the TODO point in his original code ;)
if name == 'mycalendar':
mycalendar = ... # TODO: do something to get the appropriate object
return mycalendar
Usually I'd use something similar to:
class Test(BrowserPage):
template = ViewPageTemplateFile('atest.pt')
def __call__(self):
return self.template()
But I can't work out how to do this correctly in the context of the custom traversal.
UPDATE: To be clear I want to avoid adding anything else to the url (No: http://foo.com/folder/random_id/read).
I don't need the view to be available via any other address (No: http://foo.com/folder/read)
The ZCML for the view I'd like to use is:
<browser:page
for="foo.interfaces.IFooFolderContainer"
name="read"
template="read.pt"
permission="zope.ManageContent"
/>
I'm guessing (on further advice), something along the lines of:
return getMultiAdapter((mycalendar, self.request), IPageTemplate, name=u'read')
Or even a default view for the object type (a dict in this case) that's being returned:
<browser:page
for="dict"
name="read"
template="read.pt"
permission="zope.ManageContent"
/>
|
[
"It would be easier to answer your question if you showed what your custom traverser is doing.\nEssentially, you want something like this:\ndef publishTraverse(self, request, name):\n if name in self.context:\n return MyMessageView(self.context[name], request)\n\n # fall back to views such as index.html\n view = queryMultiAdapter((self.context, request), name=name)\n if view is not None:\n return view\n\n # give up and return a 404 Not Found error page\n raise NotFound(self.context, name, request)\n\nwhere MyMessageView can be something as simple as\nclass MyMessageView(BrowserPage):\n __call__ = ViewPageTemplateFile('read.pt')\n\nDisclaimer: I'm not sure if the view you instantiate directly will be protected by a security wrapper; make sure your functional tests ensure anonymous users can't view messages if that's what you want.\n",
"If you end up at a proper object with your custom traverser, you can just tack on the template name and user \"context\" in that template. So http://foo.com/folder/random_id/my_template and in the template do the normal <h1 tal:content=\"context/title\" /> stuff.\n",
"IIUC, what you want is to render the 'read' view when somebody requests /folder/random_id. If that's the case, all you need to do is make your traversal return an object (IFolderContent, maybe) representing a random_id and specify the 'view' page as the defaultView for IFolderContent.\nThe defaultView is needed because there's no view specified for the random_id object in your URL.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python",
"zope",
"zpt"
] |
stackoverflow_0001752090_python_zope_zpt.txt
|
Q:
Problem with db.get in Google App Engine
When I run the following code:
query = datastore.Food_Item.all()
results = query.fetch(1)
foodA = results[0]
foodB = db.get(foodA.key())
I would expect foodA and foodB to be the same type. However, I see that the foodA is of type "model.datastore.Food_Item" and foodB is of type "datastore.Food_Item". Why are they different?
FYI, the Food_Item model is defined in datastore.py, which is found in the "model" directory. I'm new to app engine, so any feedback you could provide would be greatly appreciated. Thanks!
A:
It seems likely you're importing the same module (model.datastore) by different names in different places - for example, by using a relative import inside the model package. db.get returns whichever name it saw when the module was first imported, while your own code (the query) returns whatever you explicitly specified.
|
Problem with db.get in Google App Engine
|
When I run the following code:
query = datastore.Food_Item.all()
results = query.fetch(1)
foodA = results[0]
foodB = db.get(foodA.key())
I would expect foodA and foodB to be the same type. However, I see that the foodA is of type "model.datastore.Food_Item" and foodB is of type "datastore.Food_Item". Why are they different?
FYI, the Food_Item model is defined in datastore.py, which is found in the "model" directory. I'm new to app engine, so any feedback you could provide would be greatly appreciated. Thanks!
|
[
"It seems likely you're importing the same module (model.datastore) by different names in different places - for example, by using a relative import inside the model package. db.get returns whichever name it saw when the module was first imported, while your own code (the query) returns whatever you explicitly specified.\n"
] |
[
4
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001756059_google_app_engine_python.txt
|
Q:
Nonblocking webserver on .Net for Comet applications
I am trying to implement a Comet style (e.g. chat) application using IronPython. While I don't need to scale to twitter like dimensions, it is vital that the response time is lightening fast. All the possibilities in Python (Twisted, Tornado, Magnum-Py) do not work with IronPython, often because of epoll support.
Is there a default choice in the .Net world for comet style applications? Or a pure python implementation with long-pulling support? I have tried NTornado, but performance is currently very poor (100-1000x slower than Tornado).
A:
There sure is. Check out WebSync, a full comet solution for .NET/IIS. To my knowledge, it's the only full implementation of comet for .NET available today. You can use the on-demand version for free (up to a limit), or pick up the server version to host it yourself. It's pretty inexpensive too, no runtime fees, etc.
|
Nonblocking webserver on .Net for Comet applications
|
I am trying to implement a Comet style (e.g. chat) application using IronPython. While I don't need to scale to twitter like dimensions, it is vital that the response time is lightening fast. All the possibilities in Python (Twisted, Tornado, Magnum-Py) do not work with IronPython, often because of epoll support.
Is there a default choice in the .Net world for comet style applications? Or a pure python implementation with long-pulling support? I have tried NTornado, but performance is currently very poor (100-1000x slower than Tornado).
|
[
"There sure is. Check out WebSync, a full comet solution for .NET/IIS. To my knowledge, it's the only full implementation of comet for .NET available today. You can use the on-demand version for free (up to a limit), or pick up the server version to host it yourself. It's pretty inexpensive too, no runtime fees, etc.\n"
] |
[
2
] |
[] |
[] |
[
".net",
"comet",
"ironpython",
"python"
] |
stackoverflow_0001730986_.net_comet_ironpython_python.txt
|
Q:
Django development server CPU intensive - how to analyse?
I'm noticing that my django development server (version 1.1.1) on my local windows7 machine is using a lot of CPU (~30%, according to task manager's python.exe entry), even in idle state, i.e. no request coming in/going out. Is there an established way of analysing what might be responsible for this?
Thanks!
Martin
A:
FWIW, you should do the profiling, but when you do I'll bet you find that the answer is "polling for changes to your files so it can auto-reload." You might do a quick test with "python manage.py runserver --noreload" and see how that affects the CPU usage.
A:
Hit Control-C and crash the process. It will probably crash somewhere that it's spending a lot of time.
Or you could use a profiler.
A:
http://docs.python.org/library/profile.html
That's the standard approach.
A:
The standard approach is to use a profiler. If, for some reason you can't (such as there is no profiler available in the Apache modpython that is running your Django) your best bet might be simply to instrument your program with logging. Watch the messages from your program, and see what you can learn from them.
If you see a message "Entering CalculateFoo()" and then five seconds later "Exiting CalculateFoo()" that's a major clue there. Or if one particular function keeps printing over and over and over.
Here's a short discussion of Python logging.
Python debugging tips
EDIT: I just noticed that you specifically said this is on your Windows 7 desktop. So, use a profiler. But I'll leave this answer up to cover the general case.
|
Django development server CPU intensive - how to analyse?
|
I'm noticing that my django development server (version 1.1.1) on my local windows7 machine is using a lot of CPU (~30%, according to task manager's python.exe entry), even in idle state, i.e. no request coming in/going out. Is there an established way of analysing what might be responsible for this?
Thanks!
Martin
|
[
"FWIW, you should do the profiling, but when you do I'll bet you find that the answer is \"polling for changes to your files so it can auto-reload.\" You might do a quick test with \"python manage.py runserver --noreload\" and see how that affects the CPU usage.\n",
"Hit Control-C and crash the process. It will probably crash somewhere that it's spending a lot of time.\nOr you could use a profiler. \n",
"http://docs.python.org/library/profile.html\nThat's the standard approach.\n",
"The standard approach is to use a profiler. If, for some reason you can't (such as there is no profiler available in the Apache modpython that is running your Django) your best bet might be simply to instrument your program with logging. Watch the messages from your program, and see what you can learn from them.\nIf you see a message \"Entering CalculateFoo()\" and then five seconds later \"Exiting CalculateFoo()\" that's a major clue there. Or if one particular function keeps printing over and over and over.\nHere's a short discussion of Python logging.\nPython debugging tips\nEDIT: I just noticed that you specifically said this is on your Windows 7 desktop. So, use a profiler. But I'll leave this answer up to cover the general case.\n"
] |
[
19,
4,
3,
1
] |
[] |
[] |
[
"cpu",
"django",
"python"
] |
stackoverflow_0001750676_cpu_django_python.txt
|
Q:
How to specify a baseDN when connecting to LDAP via python?
I want to connect to a ldap server with python-ldap using a specific baseDN.
import ldap
baseDN="ou=unit,o=org.c=xx" # doesn't work
#baseDN="" # works
host="ldaps://test.org.xx:636"
userDN="cn=proxyhlrb,ou=services,o=org,c=xx"
passwd="secret"
server=ldap.initialize(host+"/"+baseDN)
server.bind_s(userDN,passwd,ldap.AUTH_SIMPLE)
What is wrong here? According to the documentation the argument of ldap.initialize must be a valid LDAP URL according to RFC4516 and therefore using a host+baseDN should work. Is there another way to specify a baseDN in python-ldap?
A:
I think this resource would be interesting for you. It nicely explains how to combine LDAP with Python.
http://www.packtpub.com/article/python-ldap-applications-ldap-opearations
Edit: is the port you are using correct? In PHP, developers mainly use port 389 for LDAP connects, bindings and queries.
|
How to specify a baseDN when connecting to LDAP via python?
|
I want to connect to a ldap server with python-ldap using a specific baseDN.
import ldap
baseDN="ou=unit,o=org.c=xx" # doesn't work
#baseDN="" # works
host="ldaps://test.org.xx:636"
userDN="cn=proxyhlrb,ou=services,o=org,c=xx"
passwd="secret"
server=ldap.initialize(host+"/"+baseDN)
server.bind_s(userDN,passwd,ldap.AUTH_SIMPLE)
What is wrong here? According to the documentation the argument of ldap.initialize must be a valid LDAP URL according to RFC4516 and therefore using a host+baseDN should work. Is there another way to specify a baseDN in python-ldap?
|
[
"I think this resource would be interesting for you. It nicely explains how to combine LDAP with Python.\nhttp://www.packtpub.com/article/python-ldap-applications-ldap-opearations\nEdit: is the port you are using correct? In PHP, developers mainly use port 389 for LDAP connects, bindings and queries.\n"
] |
[
0
] |
[] |
[] |
[
"connection",
"ldap",
"python"
] |
stackoverflow_0001756977_connection_ldap_python.txt
|
Q:
Python LEPL LineAwareConfiguration trouble
I'm new to using python's LEPL, and it looks great. However, I'm trying to use the LineAwareConfiguration to easily handle a grammar in which whitespace matters, and I'm running into some serious issues. Namely, this code works:
from lepl import *
broken = Token(r'.')
parser = broken[:].string_parser()
While this code yields a UnicodeEncodeError:
from lepl import *
broken = Token(r'.')
parser = broken[:].string_parser(LineAwareConfiguration())
I've tried debugging on my own, and the code is way too complex for me to understand what is going on. Does anyone know LEPL well enough to tell me why this isn't working? LineAwareConfiguration seems pretty broken in this case, and it's not exactly a corner case.
It should be noted that other tokens (such as Token(r'[^a]')) also throw the unicode error, not just one with r'.'.
Can anyone help?
A:
yeah, sorry about this. it's at least partly related to the difference between normal (byte) and unicode strings in python 2.6 (the line aware code is new this last release). i will get a fixed release out as soon as i can - hopefully by the weekend. if you keep watching the mailing list there may be a point before then at which there's something in hg that would be worth testing.
at the moment (ie this morning before work - this is not in hg yet) i have everything compiling, but various tokens now simply fail to match.
believe me, i would have preferred the first lepl related post here to be something more positive than this, so i am working on it.... :)
[later - 2009-11-22] ok, i think that release 3.3.2 fixes this. the problem was that, although in general unicode and "normal" strings inter-operate, an error is generated if a normal string is used as a template to format a unicode string. so now all templates are converted to unicode.
A:
Never mind: it looks like this is a known bug and that it's being worked on. Shows me to ask a question before I check the mailing lists...
|
Python LEPL LineAwareConfiguration trouble
|
I'm new to using python's LEPL, and it looks great. However, I'm trying to use the LineAwareConfiguration to easily handle a grammar in which whitespace matters, and I'm running into some serious issues. Namely, this code works:
from lepl import *
broken = Token(r'.')
parser = broken[:].string_parser()
While this code yields a UnicodeEncodeError:
from lepl import *
broken = Token(r'.')
parser = broken[:].string_parser(LineAwareConfiguration())
I've tried debugging on my own, and the code is way too complex for me to understand what is going on. Does anyone know LEPL well enough to tell me why this isn't working? LineAwareConfiguration seems pretty broken in this case, and it's not exactly a corner case.
It should be noted that other tokens (such as Token(r'[^a]')) also throw the unicode error, not just one with r'.'.
Can anyone help?
|
[
"yeah, sorry about this. it's at least partly related to the difference between normal (byte) and unicode strings in python 2.6 (the line aware code is new this last release). i will get a fixed release out as soon as i can - hopefully by the weekend. if you keep watching the mailing list there may be a point before then at which there's something in hg that would be worth testing.\nat the moment (ie this morning before work - this is not in hg yet) i have everything compiling, but various tokens now simply fail to match.\nbelieve me, i would have preferred the first lepl related post here to be something more positive than this, so i am working on it.... :)\n[later - 2009-11-22] ok, i think that release 3.3.2 fixes this. the problem was that, although in general unicode and \"normal\" strings inter-operate, an error is generated if a normal string is used as a template to format a unicode string. so now all templates are converted to unicode.\n",
"Never mind: it looks like this is a known bug and that it's being worked on. Shows me to ask a question before I check the mailing lists...\n"
] |
[
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001752645_python.txt
|
Q:
Checking files retrieved by Twisted's FTPClient.retrieveFile method for completeness
I'm writing a custom ftp client to act as a gatekeeper for incoming multimedia content from subcontractors hired by one of our partners. I chose twisted because it allows me to parse the file contents before writing the files to disk locally, and I've been looking for occasion to explore twisted anyway. I'm using 'twisted.protocols.ftp.FTPClient.retrieveFile' to get the file, passing the escaped path to the file, and a protocol to the 'retrieveFile' method. I want to be absolutely sure that the entire file has been retrieved because the event handler in the call back is going to write the file to disk locally, then delete the remote file from the ftp server alla '-E' switch behavior in the lftp client. My question is, do I really need to worry about this, or can I assume that an err back will happen if the file is not fully retrieved?
A:
There are a couple unit tests for behavior in this area.
twisted.test.test_ftp.FTPClientTestCase.test_failedRETR is the most directly relevant one. It covers the case where the control and data connections are lost while a file transfer is in progress.
It seems to me that test coverage in this area could be significantly improved. There are no tests covering the case where just the data connection is lost while a transfer is in progress, for example. One thing that makes this tricky, though, is that FTP is not a very robust protocol. The end of a file transfer is signaled by the data connection closing. To be safe, you have to check to see if you received as many bytes as you expected to receive. The only way to perform this check is to know the file size in advance or ask the server for it using LIST (FTPClient.list).
Given all this, I'd suggest that when a file transfer completes, you always ask the server how many bytes you should have gotten and make sure it agrees with the number of bytes delivered to your protocol. You may sometimes get an errback on the Deferred returned from retrieveFile, but this will keep you safe even in the cases where you don't.
|
Checking files retrieved by Twisted's FTPClient.retrieveFile method for completeness
|
I'm writing a custom ftp client to act as a gatekeeper for incoming multimedia content from subcontractors hired by one of our partners. I chose twisted because it allows me to parse the file contents before writing the files to disk locally, and I've been looking for occasion to explore twisted anyway. I'm using 'twisted.protocols.ftp.FTPClient.retrieveFile' to get the file, passing the escaped path to the file, and a protocol to the 'retrieveFile' method. I want to be absolutely sure that the entire file has been retrieved because the event handler in the call back is going to write the file to disk locally, then delete the remote file from the ftp server alla '-E' switch behavior in the lftp client. My question is, do I really need to worry about this, or can I assume that an err back will happen if the file is not fully retrieved?
|
[
"There are a couple unit tests for behavior in this area.\ntwisted.test.test_ftp.FTPClientTestCase.test_failedRETR is the most directly relevant one. It covers the case where the control and data connections are lost while a file transfer is in progress.\nIt seems to me that test coverage in this area could be significantly improved. There are no tests covering the case where just the data connection is lost while a transfer is in progress, for example. One thing that makes this tricky, though, is that FTP is not a very robust protocol. The end of a file transfer is signaled by the data connection closing. To be safe, you have to check to see if you received as many bytes as you expected to receive. The only way to perform this check is to know the file size in advance or ask the server for it using LIST (FTPClient.list).\nGiven all this, I'd suggest that when a file transfer completes, you always ask the server how many bytes you should have gotten and make sure it agrees with the number of bytes delivered to your protocol. You may sometimes get an errback on the Deferred returned from retrieveFile, but this will keep you safe even in the cases where you don't.\n"
] |
[
4
] |
[] |
[] |
[
"client",
"ftp",
"python",
"twisted"
] |
stackoverflow_0001757276_client_ftp_python_twisted.txt
|
Q:
Gracefully convert .rar to .zip using Python
I'm currently making system call to "unrar and zip" commands. It interrupts and requires me to enter password while encounter password propected archives.
Is it possible to let it run and return a "unsuccessful" value to main program on any error or password prompt?
Can we natively use rarfile and zipfile library to do the job without creating any temporary files?
A:
I think it's very difficult to do the task without using temporary files. If you are converting very large files you need to use temporary space in disk.
You can use the PyUnRAR2 library, it will let you examine and extract the files of a RAR archive. You can extract the files to a temporary folder created with the tempfile python module. After that create a ZIP file using the zipfile python module.
Note that in order to use PyUnRAR2 you need the RAR proprietary binary files.
A:
Maybe this could help: http://www.noah.org/wiki/Pexpect#Description_of_Pexpect
|
Gracefully convert .rar to .zip using Python
|
I'm currently making system call to "unrar and zip" commands. It interrupts and requires me to enter password while encounter password propected archives.
Is it possible to let it run and return a "unsuccessful" value to main program on any error or password prompt?
Can we natively use rarfile and zipfile library to do the job without creating any temporary files?
|
[
"I think it's very difficult to do the task without using temporary files. If you are converting very large files you need to use temporary space in disk.\nYou can use the PyUnRAR2 library, it will let you examine and extract the files of a RAR archive. You can extract the files to a temporary folder created with the tempfile python module. After that create a ZIP file using the zipfile python module.\nNote that in order to use PyUnRAR2 you need the RAR proprietary binary files.\n",
"Maybe this could help: http://www.noah.org/wiki/Pexpect#Description_of_Pexpect\n"
] |
[
2,
0
] |
[] |
[] |
[
"compression",
"python",
"rar",
"zip"
] |
stackoverflow_0001756109_compression_python_rar_zip.txt
|
Q:
How to append a reading to a python list?
i am using GM862 module and i want to write the cordinates as it is in a file "cordinates.txt" but i get some error, this is the code i wrote:
import MDM
cordlist = []
f = open("cordinates.txt", 'w')
def AcquiredPosition():
res = MDM.send('AT$GPSACP\r', 0)
res = MDM.receive(30)
if(res.find('OK') != -1):
tmp = res.split("\r\n")
res = tmp[1]
tmp = res.split(" ")
return tmp[1]
else:
return ""
while (1):
res = MDM.receive(60)
p = AcquiredPosition()
cordlist.append(p)
cordlist.append("\r\n")
f.writelines(cordlist)
so the problem that the cordinates are being repeted in the list each time the appened happened.
and this is an example of the file content called "cordinates.txt":
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 first time
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 repeted1
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03 first time
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 repeted2
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03 repeted1
160451.246,2612.7634N,05027.5939E,3.0,23.6,2,143.18,1.36,0.73,181109,03 first time
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 repeted3
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03
160451.246,2612.7634N,05027.5939E,3.0,23.6,2,143.18,1.36,0.73,181109,03
160458.246,2612.7471N,05027.5979E,3.0,23.6,2,333.97,7.66,4.13,181109,03
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 and so on...
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03
160451.246,2612.7634N,05027.5939E,3.0,23.6,2,143.18,1.36,0.73,181109,03
160458.246,2612.7471N,05027.5979E,3.0,23.6,2,333.97,7.66,4.13,181109,03
160504.246,2612.7496N,05027.5961E,3.0,47.2,3,316.66,3.16,1.70,181109,04
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03
160451.246,2612.7634N,05027.5939E,3.0,23.6,2,143.18,1.36,0.73,181109,03
160458.246,2612.7471N,05027.5979E,3.0,23.6,2,333.97,7.66,4.13,181109,03
160504.246,2612.7496N,05027.5961E,3.0,47.2,3,316.66,3.16,1.70,181109,04
160510.000,2612.7446N,05027.5996E,3.0,53.7,3,162.56,0.50,0.27,181109,04
thanks for any help.
A:
You are appending to your list and then writing the full list to the file each time through the loop.
You need to clear down the list in each pass through the loop.
Put cordlist = [] as the first line under while(1)
A:
Why not open the file in append mode ('a' instead of 'w') and just writelines to that?
A:
Because that's what you've asked it to do. On every iteration, you append an item to the list, then write out all the lines so far. So each time you'll repeat everything you've already done, plus the one new line.
Since your function only returns a single line I don't know why you're bothering with a list at all - just write the result of the function straight to the file.
|
How to append a reading to a python list?
|
i am using GM862 module and i want to write the cordinates as it is in a file "cordinates.txt" but i get some error, this is the code i wrote:
import MDM
cordlist = []
f = open("cordinates.txt", 'w')
def AcquiredPosition():
res = MDM.send('AT$GPSACP\r', 0)
res = MDM.receive(30)
if(res.find('OK') != -1):
tmp = res.split("\r\n")
res = tmp[1]
tmp = res.split(" ")
return tmp[1]
else:
return ""
while (1):
res = MDM.receive(60)
p = AcquiredPosition()
cordlist.append(p)
cordlist.append("\r\n")
f.writelines(cordlist)
so the problem that the cordinates are being repeted in the list each time the appened happened.
and this is an example of the file content called "cordinates.txt":
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 first time
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 repeted1
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03 first time
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 repeted2
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03 repeted1
160451.246,2612.7634N,05027.5939E,3.0,23.6,2,143.18,1.36,0.73,181109,03 first time
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 repeted3
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03
160451.246,2612.7634N,05027.5939E,3.0,23.6,2,143.18,1.36,0.73,181109,03
160458.246,2612.7471N,05027.5979E,3.0,23.6,2,333.97,7.66,4.13,181109,03
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03 and so on...
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03
160451.246,2612.7634N,05027.5939E,3.0,23.6,2,143.18,1.36,0.73,181109,03
160458.246,2612.7471N,05027.5979E,3.0,23.6,2,333.97,7.66,4.13,181109,03
160504.246,2612.7496N,05027.5961E,3.0,47.2,3,316.66,3.16,1.70,181109,04
160439.246,2612.7206N,05027.6068E,3.0,23.6,2,339.34,4.21,2.27,181109,03
160445.246,2612.7305N,05027.6079E,3.0,23.6,2,161.61,6.37,3.43,181109,03
160451.246,2612.7634N,05027.5939E,3.0,23.6,2,143.18,1.36,0.73,181109,03
160458.246,2612.7471N,05027.5979E,3.0,23.6,2,333.97,7.66,4.13,181109,03
160504.246,2612.7496N,05027.5961E,3.0,47.2,3,316.66,3.16,1.70,181109,04
160510.000,2612.7446N,05027.5996E,3.0,53.7,3,162.56,0.50,0.27,181109,04
thanks for any help.
|
[
"You are appending to your list and then writing the full list to the file each time through the loop.\nYou need to clear down the list in each pass through the loop.\nPut cordlist = [] as the first line under while(1)\n",
"Why not open the file in append mode ('a' instead of 'w') and just writelines to that?\n",
"Because that's what you've asked it to do. On every iteration, you append an item to the list, then write out all the lines so far. So each time you'll repeat everything you've already done, plus the one new line.\nSince your function only returns a single line I don't know why you're bothering with a list at all - just write the result of the function straight to the file.\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001758068_python.txt
|
Q:
Twisted: source IP address for outbound connections
I'm in the process of implementing a service -- written in Python with the Twisted framework, running on Debian GNU/Linux -- that checks the availability of SIP servers. For this I use the OPTIONS method (a SIP protocol feature), as this seems to be a commonplace practice. In order to construct correct and RFC compliant headers, I need to know the source IP address and the source port for the connection that is going to be established. [How] can this be done with Twisted?
This is what I tried:
I subclassed protocol.DatagramProtocol and within startProtocol(self) I used self.transport.getHost().host and self.transport.getHost().port. The latter is indeed the port that's going to be used, whereas the former only yields 0.0.0.0.
I guess that at this point Twisted doesn't [yet?] know which interface and as such which source IP address will be used. Does Twisted provide a facility that could help me with this or do I need to interface with the OS (routing) in a different way? Or did I just use self.transport.getHost().host incorrectly?
A:
For the sake of completeness I answer my own question:
Make sure you use connect() on the transport before trying to determine the host's source IP address. The following excerpt shows the relevant part of a protocol implementation:
class FooBarProtocol(protocol.DatagramProtocol):
def startProtocol(self):
self.transport.getHost().host # => 0.0.0.0
self.transport.connect(self.dstHost, self.dstPort)
self.transport.getHost().host # => 192.168.1.102
A:
If you are using UDP then the endpoint is determined by either:
calling bind() on the socket and explicitly giving it an address
sending a packet
If you want a few more details, check this response.
The problem is that I'm not that familiar with twisted. From what I can tell by a quick perusal of the source, it looks like you might want to use a reactor like t.i.d.SelectReactor instead. This is what t.n.d.DNSDatagramProtocol does under the hood.
If you take twisted out of the picture, then the following snippet shows what is going on:
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
<socket._socketobject object at 0x10025d670>
>>> s.getsockname() # this is an unbound or unnamed socket
('0.0.0.0', 0)
>>> s.bind( ('0.0.0.0', 0) ) # 0.0.0.0 is INADDR_ANY, 0 means pick a port
>>> s.getsockname() # IP is still zero, but it has picked a port
('0.0.0.0', 56814)
Get the host name is a little trickier if you need to support multiple network interfaces or IPv4 and IPv6. If you can make the interface used configurable, then pass it in as the first member of the tuple to socket.bind() and you are set.
Now the hard part is doing this within the confines of the abstractions that twisted provides. Unfortunately, I can't help a whole lot there. I would recommend looking for examples on how you can get access to the underlying socket or find a way to pass the socket information into the framework.
Good luck.
A:
Did you see if that you want to do is possible with the SIP implementation that is part of Twisted?
In any case, how you set the source address and port for UDP in Twisted is quite similar to how you set them without Twisted. In Twisted, reactor.listenUDP(port, protocol, interface) binds an UDP socket to a specific port and interface and handles the received datagrams to your protocol. Inside the protocol, self.transport.write(msg, addr) sends a datagram to addr using the address that the protocol is bound to as source address.
Reading your question again, I think the only part you were missing was passing interface to reactor.listenUDP(...).
|
Twisted: source IP address for outbound connections
|
I'm in the process of implementing a service -- written in Python with the Twisted framework, running on Debian GNU/Linux -- that checks the availability of SIP servers. For this I use the OPTIONS method (a SIP protocol feature), as this seems to be a commonplace practice. In order to construct correct and RFC compliant headers, I need to know the source IP address and the source port for the connection that is going to be established. [How] can this be done with Twisted?
This is what I tried:
I subclassed protocol.DatagramProtocol and within startProtocol(self) I used self.transport.getHost().host and self.transport.getHost().port. The latter is indeed the port that's going to be used, whereas the former only yields 0.0.0.0.
I guess that at this point Twisted doesn't [yet?] know which interface and as such which source IP address will be used. Does Twisted provide a facility that could help me with this or do I need to interface with the OS (routing) in a different way? Or did I just use self.transport.getHost().host incorrectly?
|
[
"For the sake of completeness I answer my own question:\nMake sure you use connect() on the transport before trying to determine the host's source IP address. The following excerpt shows the relevant part of a protocol implementation:\nclass FooBarProtocol(protocol.DatagramProtocol):\n def startProtocol(self):\n self.transport.getHost().host # => 0.0.0.0\n self.transport.connect(self.dstHost, self.dstPort)\n self.transport.getHost().host # => 192.168.1.102\n\n",
"If you are using UDP then the endpoint is determined by either:\n\ncalling bind() on the socket and explicitly giving it an address\nsending a packet\n\nIf you want a few more details, check this response.\nThe problem is that I'm not that familiar with twisted. From what I can tell by a quick perusal of the source, it looks like you might want to use a reactor like t.i.d.SelectReactor instead. This is what t.n.d.DNSDatagramProtocol does under the hood.\nIf you take twisted out of the picture, then the following snippet shows what is going on:\n>>> import socket\n>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)\n<socket._socketobject object at 0x10025d670>\n>>> s.getsockname() # this is an unbound or unnamed socket\n('0.0.0.0', 0)\n>>> s.bind( ('0.0.0.0', 0) ) # 0.0.0.0 is INADDR_ANY, 0 means pick a port\n>>> s.getsockname() # IP is still zero, but it has picked a port\n('0.0.0.0', 56814)\n\nGet the host name is a little trickier if you need to support multiple network interfaces or IPv4 and IPv6. If you can make the interface used configurable, then pass it in as the first member of the tuple to socket.bind() and you are set.\nNow the hard part is doing this within the confines of the abstractions that twisted provides. Unfortunately, I can't help a whole lot there. I would recommend looking for examples on how you can get access to the underlying socket or find a way to pass the socket information into the framework.\nGood luck.\n",
"Did you see if that you want to do is possible with the SIP implementation that is part of Twisted?\nIn any case, how you set the source address and port for UDP in Twisted is quite similar to how you set them without Twisted. In Twisted, reactor.listenUDP(port, protocol, interface) binds an UDP socket to a specific port and interface and handles the received datagrams to your protocol. Inside the protocol, self.transport.write(msg, addr) sends a datagram to addr using the address that the protocol is bound to as source address.\nReading your question again, I think the only part you were missing was passing interface to reactor.listenUDP(...).\n"
] |
[
8,
0,
0
] |
[] |
[] |
[
"linux",
"network_programming",
"networking",
"python",
"twisted"
] |
stackoverflow_0001622454_linux_network_programming_networking_python_twisted.txt
|
Q:
Google App Engine - design considerations about cron tasks
I'm developing software using the Google App Engine.
I have some considerations about the optimal design regarding the following issue: I need to create and save snapshots of some entities at regular intervals.
In the conventional relational db world, I would create db jobs which would insert new summary records.
For example, a job would insert a record for every active user that would contain his current score to the "userrank" table, say, every hour.
I'd like to know what's the best method to achieve this in Google App Engine. I know that there is the Cron service, but does it allow us to execute jobs which will insert/update thousands of records?
A:
I think you'll find that snapshotting every user's state every hour isn't something that will scale well no matter what your framework. A more ordinary environment will disguise this by letting you have longer running tasks, but you'll still reach the point where it's not practical to take a snapshot of every user's data, every hour.
My suggestion would be this: Add a 'last snapshot' field, and subclass the put() function of your model (assuming you're using Python; the same is possible in Java, but I don't know the syntax), such that whenever you update a record, it checks if it's been more than an hour since the last snapshot, and if so, creates and writes a snapshot record.
In order to prevent concurrent updates creating two identical snapshots, you'll want to give the snapshots a key name derived from the time at which the snapshot was taken. That way, if two concurrent updates try to write a snapshot, one will harmlessly overwrite the other.
To get the snapshot for a given hour, simply query for the oldest snapshot newer than the requested period. As an added bonus, since inactive records aren't snapshotted, you're saving a lot of space, too.
A:
Have you considered using the remote api instead? This way you could get a shell to your datastore and avoid the timeouts. The Mapper class they demonstrate in that link is quite useful and I've used it successfully to do batch operations on ~1500 objects.
That said, cron should work fine too. You do have a limit on the time of each individual request so you can't just chew through them all at once, but you can use redirection to loop over as many users as you want, processing one user at a time. There should be an example of this in the docs somewhere if you need help with this approach.
A:
I would use a combination of Cron jobs and a looping url fetch method detailed here: http://stage.vambenepe.com/archives/549. In this way you can catch your timeouts and begin another request.
To summarize the article, the cron job calls your initial process, you catch the timeout error and call the process again, masked as a second url. You have to ping between two URLs to keep app engine from thinking you are in a accidental loop. You also need to be careful that you do not loop infinitely. Make sure that there is an end state for your updating loop, since this would put you over your quotas pretty quickly if it never ended.
|
Google App Engine - design considerations about cron tasks
|
I'm developing software using the Google App Engine.
I have some considerations about the optimal design regarding the following issue: I need to create and save snapshots of some entities at regular intervals.
In the conventional relational db world, I would create db jobs which would insert new summary records.
For example, a job would insert a record for every active user that would contain his current score to the "userrank" table, say, every hour.
I'd like to know what's the best method to achieve this in Google App Engine. I know that there is the Cron service, but does it allow us to execute jobs which will insert/update thousands of records?
|
[
"I think you'll find that snapshotting every user's state every hour isn't something that will scale well no matter what your framework. A more ordinary environment will disguise this by letting you have longer running tasks, but you'll still reach the point where it's not practical to take a snapshot of every user's data, every hour.\nMy suggestion would be this: Add a 'last snapshot' field, and subclass the put() function of your model (assuming you're using Python; the same is possible in Java, but I don't know the syntax), such that whenever you update a record, it checks if it's been more than an hour since the last snapshot, and if so, creates and writes a snapshot record.\nIn order to prevent concurrent updates creating two identical snapshots, you'll want to give the snapshots a key name derived from the time at which the snapshot was taken. That way, if two concurrent updates try to write a snapshot, one will harmlessly overwrite the other.\nTo get the snapshot for a given hour, simply query for the oldest snapshot newer than the requested period. As an added bonus, since inactive records aren't snapshotted, you're saving a lot of space, too.\n",
"Have you considered using the remote api instead? This way you could get a shell to your datastore and avoid the timeouts. The Mapper class they demonstrate in that link is quite useful and I've used it successfully to do batch operations on ~1500 objects.\nThat said, cron should work fine too. You do have a limit on the time of each individual request so you can't just chew through them all at once, but you can use redirection to loop over as many users as you want, processing one user at a time. There should be an example of this in the docs somewhere if you need help with this approach.\n",
"I would use a combination of Cron jobs and a looping url fetch method detailed here: http://stage.vambenepe.com/archives/549. In this way you can catch your timeouts and begin another request.\nTo summarize the article, the cron job calls your initial process, you catch the timeout error and call the process again, masked as a second url. You have to ping between two URLs to keep app engine from thinking you are in a accidental loop. You also need to be careful that you do not loop infinitely. Make sure that there is an end state for your updating loop, since this would put you over your quotas pretty quickly if it never ended.\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"cron",
"database",
"google_app_engine",
"python"
] |
stackoverflow_0000814896_cron_database_google_app_engine_python.txt
|
Q:
How to read line (from a file) and then append + print in python?
for line in file:
print line
In the code above when I change it to:
for line in file:
print line + " just a string"
This only appends "just a string" to the last line
PS: Python newbie
A:
Iterating over a file includes the line endings, so just remove them:
for line in file:
print line.rstrip("\n"), "something"
Note that print will append its own newline, so even without appending "something" you'd want to do this (or use sys.stdout.write instead of print). You may also use line.rstrip() if you want to remove all trailing whitespace (e.g. spaces and tabs too).
Documentation:
Files support the iterator protocol. Each iteration returns the same result as file.readline(), and iteration ends when the readline() method returns an empty string.
http://docs.python.org/library/stdtypes.html#file.readline (quoted text is below the methods)
A:
The line received through the iterator includes the newline character at the end - so if you want "something" to be appended on the same line you will need to cut this off.
for line in file:
print line[:-1] + " something"
A:
This is how you can append 'something' at the end of each line:
import fileinput
for line in fileinput.input("dat.txt"):
print line.rstrip(), ' something'
If you want to append 'something' to line and then print the line:
import fileinput
for line in fileinput.input("dat.txt"):
line = line.rstrip() + ' something'
print line
# now you can continue processing line with something appended to it
dat.txt file:
> cat dat.txt
one
two and three
four -
five
.
output:
> ./r.py
one something
two and three something
four - something
five something
. something
|
How to read line (from a file) and then append + print in python?
|
for line in file:
print line
In the code above when I change it to:
for line in file:
print line + " just a string"
This only appends "just a string" to the last line
PS: Python newbie
|
[
"Iterating over a file includes the line endings, so just remove them:\nfor line in file:\n print line.rstrip(\"\\n\"), \"something\"\n\nNote that print will append its own newline, so even without appending \"something\" you'd want to do this (or use sys.stdout.write instead of print). You may also use line.rstrip() if you want to remove all trailing whitespace (e.g. spaces and tabs too).\nDocumentation:\n\nFiles support the iterator protocol. Each iteration returns the same result as file.readline(), and iteration ends when the readline() method returns an empty string.\n\n\nhttp://docs.python.org/library/stdtypes.html#file.readline (quoted text is below the methods)\n\n",
"The line received through the iterator includes the newline character at the end - so if you want \"something\" to be appended on the same line you will need to cut this off. \nfor line in file:\n print line[:-1] + \" something\"\n\n",
"This is how you can append 'something' at the end of each line:\nimport fileinput\n\nfor line in fileinput.input(\"dat.txt\"):\n print line.rstrip(), ' something'\n\nIf you want to append 'something' to line and then print the line:\nimport fileinput\n\nfor line in fileinput.input(\"dat.txt\"):\n line = line.rstrip() + ' something'\n print line\n # now you can continue processing line with something appended to it\n\ndat.txt file:\n> cat dat.txt\none\ntwo and three\nfour -\nfive\n.\n\noutput:\n> ./r.py\none something\ntwo and three something\nfour - something\nfive something\n. something\n\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001759193_python.txt
|
Q:
What is the right way to organize python unittests into suites?
I have some test case classes organized in directories
foo_tests
foo_tests1.py
foo_tests2.py
...
bar_tests
bar_tests1.py
...
The test cases look like:
foo_tests1.py:
import unittest
class FooTestsOne(unittest.TestCase):
def test_1():
assert(1=1)
def test_2():
#...
How do you organize test suites out of test case classes like this? There are facilities in unittest for TestLoaders and TestSuite objects but where are they declared and used? What I want is to define certain suites in a separate file that i can run the tests with:
suite1.py
import unittest
import foo_test1
suite = unittest.TestSuite((unittest.makeSuite(foo_tests1.FooTestsOne),
unittest.makeSuite(foo_tests2.FooTeststwo),
))
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
But this is not the right way to aggregate tests into suites. When I import the testcase class ("import foo_test1") to reference it so I can put it in a larger suite the tests inside are immediately run (during the import). What is the right way to aggregates tests into suites? I need fine grain control as to what tests go into which suites... I've read the TestSuite documentation, but it doesn't seem to provide many examples...
A:
Tests are not supposed to run during import. Maybe you have unittest.main() at the bottom of foo_test1.py?
Your script should work, except that
result = unittest.TextTestRunner(verbosity=2).run(suite())
should be
result = unittest.TextTestRunner(verbosity=2).run(suite)
|
What is the right way to organize python unittests into suites?
|
I have some test case classes organized in directories
foo_tests
foo_tests1.py
foo_tests2.py
...
bar_tests
bar_tests1.py
...
The test cases look like:
foo_tests1.py:
import unittest
class FooTestsOne(unittest.TestCase):
def test_1():
assert(1=1)
def test_2():
#...
How do you organize test suites out of test case classes like this? There are facilities in unittest for TestLoaders and TestSuite objects but where are they declared and used? What I want is to define certain suites in a separate file that i can run the tests with:
suite1.py
import unittest
import foo_test1
suite = unittest.TestSuite((unittest.makeSuite(foo_tests1.FooTestsOne),
unittest.makeSuite(foo_tests2.FooTeststwo),
))
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
But this is not the right way to aggregate tests into suites. When I import the testcase class ("import foo_test1") to reference it so I can put it in a larger suite the tests inside are immediately run (during the import). What is the right way to aggregates tests into suites? I need fine grain control as to what tests go into which suites... I've read the TestSuite documentation, but it doesn't seem to provide many examples...
|
[
"Tests are not supposed to run during import. Maybe you have unittest.main() at the bottom of foo_test1.py?\nYour script should work, except that \nresult = unittest.TextTestRunner(verbosity=2).run(suite())\n\nshould be \nresult = unittest.TextTestRunner(verbosity=2).run(suite)\n\n"
] |
[
3
] |
[] |
[] |
[
"python",
"unit_testing"
] |
stackoverflow_0001759128_python_unit_testing.txt
|
Q:
How to generate a graphic on the fly with cherrypy
I am developing a small web application using cherrypy and I would like to generate some graphs from the data stored in a database. The web pages with tables are easy and I plan to use matplotlib for the graphs themselves, but how do I set the content-type for the method so they return images instead of plain text? Will cherrypy "sniff" the result and change the content-type automatically?
A:
You need to set the content-type header of the response manually, either in the app config, using the response.headers tool, or in the handler method.
In the handler method, there are two options covered on the MimeDecorator page of the Cherrypy Tools wiki.
In the method body:
def hello(self):
cherrypy.response.headers['Content-Type']= 'image/png'
return generate_image_data()
Or using the tool decorator in Cherrypy 3:
@cherrypy.tools.response_headers([('Content-Type', 'image/png')])
def hello(self):
return generate_image_data()
The wiki also defines a custom decorator:
def mimetype(type):
def decorate(func):
def wrapper(*args, **kwargs):
cherrypy.response.headers['Content-Type'] = type
return func(*args, **kwargs)
return wrapper
return decorate
class MyClass:
@mimetype("image/png")
def hello(self):
return generate_image_data()
A:
You can change the content type of the response:
cherrypy.response.headers['Content-Type'] = "image/png"
|
How to generate a graphic on the fly with cherrypy
|
I am developing a small web application using cherrypy and I would like to generate some graphs from the data stored in a database. The web pages with tables are easy and I plan to use matplotlib for the graphs themselves, but how do I set the content-type for the method so they return images instead of plain text? Will cherrypy "sniff" the result and change the content-type automatically?
|
[
"You need to set the content-type header of the response manually, either in the app config, using the response.headers tool, or in the handler method.\nIn the handler method, there are two options covered on the MimeDecorator page of the Cherrypy Tools wiki.\nIn the method body:\ndef hello(self):\n cherrypy.response.headers['Content-Type']= 'image/png'\n return generate_image_data()\n\nOr using the tool decorator in Cherrypy 3:\n@cherrypy.tools.response_headers([('Content-Type', 'image/png')])\ndef hello(self):\n return generate_image_data()\n\nThe wiki also defines a custom decorator:\ndef mimetype(type):\n def decorate(func):\n def wrapper(*args, **kwargs):\n cherrypy.response.headers['Content-Type'] = type\n return func(*args, **kwargs)\n return wrapper\n return decorate\n\nclass MyClass: \n @mimetype(\"image/png\")\n def hello(self):\n return generate_image_data()\n\n",
"You can change the content type of the response:\ncherrypy.response.headers['Content-Type'] = \"image/png\"\n\n"
] |
[
6,
0
] |
[] |
[] |
[
"cherrypy",
"dynamic",
"graph",
"python"
] |
stackoverflow_0001759608_cherrypy_dynamic_graph_python.txt
|
Q:
python prompt with a bash like interface
I am using the python prompt to practice some regular expressions. I was wondering if there was a way to use the up/down arrows (like bash) to cycle through the old commands typed. I know its possible since it works on python on cygwin/windows.
thanks
A:
Use the rlcompleter module to get both readline and completion.
Sample PYTHONSTARTUP code:
try:
import readline
except ImportError:
print "Module readline unavailable."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
Sample .bashrc code to set your python startup file:
if [ -f ~/.pythonstartup.py ]
then
export PYTHONSTARTUP=~/.pythonstartup.py
fi
A:
As well as compiling with readline enabled as suggested in another answer, you can also use rlrwrap to add readline at run time, even if it wasn't complied in; like so:
rlwrap python
A:
You want ipython.
A:
If you compile python with readline support, the REPL environment should do this for you.
|
python prompt with a bash like interface
|
I am using the python prompt to practice some regular expressions. I was wondering if there was a way to use the up/down arrows (like bash) to cycle through the old commands typed. I know its possible since it works on python on cygwin/windows.
thanks
|
[
"Use the rlcompleter module to get both readline and completion.\nSample PYTHONSTARTUP code:\ntry:\n import readline\nexcept ImportError:\n print \"Module readline unavailable.\"\nelse:\n import rlcompleter\n readline.parse_and_bind(\"tab: complete\")\n\nSample .bashrc code to set your python startup file:\nif [ -f ~/.pythonstartup.py ]\nthen\n export PYTHONSTARTUP=~/.pythonstartup.py\nfi\n\n",
"As well as compiling with readline enabled as suggested in another answer, you can also use rlrwrap to add readline at run time, even if it wasn't complied in; like so:\nrlwrap python\n\n",
"You want ipython.\n",
"If you compile python with readline support, the REPL environment should do this for you.\n"
] |
[
7,
7,
6,
6
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001758819_python.txt
|
Q:
Python: Issue reading data lines multiple times from a file
I am trying to make a Python2.6 script on a Win32 that will read all the text files stored in a directory and print only the lines containing actual data. A sample file -
Set : 1
Date: 10212009
12 34 56
25 67 90
End Set
+++++++++
Set: 2
Date: 10222009
34 56 89
25 67 89
End Set
In the above example file, I want to print only the lines 3, 4 and 9, 10 (the actual data values). The program does this iteratively on all txt files.
I wrote the script as below and am testing it on a single txt file as I go.
My logic is to read the input files one by one and search for a start string. As soon as the match is found, start searching for end string. when both are found, print the lines from start string to end string.Repeat on the rest of the file before opening another file.
The problem I am having is that it successfully reads the Set 1 of data, but then screws up on subsequent sets in the file. For set 2, it identifies the no. of lines to read, but prints them starting at incorrect line number.
A little digging leads to following explanations -
1. Using seek and tell to reposition the 2nd iteration of the loop, which did not work since the file is read from buffer and that screws up "tell" value.
2. Opening the file in binary mode helped someone, but it is not working for me.
3. Open the file with 0 buffer mode, but it did not work.
Second problem I am having is when it prints data from Set 1, it inserts a blank line between 2 lines of data values. How can I get rid of it?
Note: Ignore all references to next_run in the code below. I was trying it out for repositioning line read. Subsequent searches for start string should begin from the last position of end string
#!C:/Python26 python
# Import necessary modules
import os, glob, string, sys, fileinput, linecache
from goto import goto, label
# Set working path
path = 'C:\\System_Data'
# --------------------
# PARSE DATA MODULE
# --------------------
# Define the search strings for data
start_search = "Set :"
end_search ="End Set"
# For Loop to read the input txt files one by one
for inputfile in glob.glob( os.path.join( path, '*.txt' ) ):
inputfile_fileHandle = open ( inputfile, 'rb', 0 )
print( "Current file being read: " +inputfile )
# start_line initializes to first line
start_line = 0
# After first set of data is extracted, next_run will store the position to read the rest of the file
# next_run = 0
# start reading the input files, one line by one line
for line in inputfile:
line = inputfile_fileHandle.readline()
start_line += 1
# next_run+=1
# If a line matched with the start_search string
has_match = line.find( start_search )
if has_match >= 0:
print ( "Start String found at line number: %d" %( start_line ) )
# Store the location where the search will be restarted
# next_run = inputfile_fileHandle.tell() #inputfile_fileHandle.lineno()
print ("Current Position: %d" % next_run)
end_line = start_line
print ( "Start_Line: %d" %start_line )
print ( "End_Line: %d" %end_line )
#print(line)
for line in inputfile:
line = inputfile_fileHandle.readline()
#print (line)
end_line += 1
has_match = line.find(end_search)
if has_match >= 0:
print 'End String found at line number: %d' % (end_line)
# total lines to print:
k=0
# for loop to print all the lines from start string to end string
for j in range(0,end_line-start_line-1):
print linecache.getline(inputfile, start_line +1+ j )
k+=1
print ( "Number of lines Printed: %d " %k )
# Using goto to get out of 2 loops at once
goto .re_search_start_string
label .re_search_start_string
#inputfile_fileHandle.seek(next_run,0)
inputfile_fileHandle.close ()
A:
in_data = False
for line in open( 'data.txt' ):
if line.startswith( 'Date:' ):
in_data = True
elif line.startswith( 'End Set' ):
in_data = False
elif in_data:
print line.rstrip()
Just put something like that inside a loop over your files (i.e. os.walk) and you should be good to go
A:
I'd probably do something much simpler, like this:
import glob, os
start_search = "Set :"
end_search = "End Set"
path = '.'
for filename in glob.glob(os.path.join(path, '*.txt')):
inputfile = open(filename, 'rb', 0)
print("Current file being read: " + filename)
is_in_set = False
while True:
line = inputfile.readline()
if not line: break
if line.startswith(start_search):
is_in_set = True
inputfile.readline() # Discard the next line.
elif line.startswith(end_search):
is_in_set = False
print('---')
elif is_in_set:
print(line.rstrip()) # The rstrip removes the extra blank lines.
If you also want the line numbers, wrap the file object so that every time you call readline() it counts the line numbers.
A:
The first thing I'd do is build a generator that uses a simple state machine to extract the data from a sequence:
def extract_data(seq):
state = "Waiting"
for item in seq:
if state == "Waiting":
if item.startswith("Set"):
state = "SkippingDateLine"
continue
if state == "SkippingDateLine":
state = "EmittingData"
continue
if state == "EmittingData":
if item.startswith("End Set"):
state = "Waiting"
continue
yield item.rstrip()
Now I can test that generator to see if it really does what I think it's doing:
>>> data = """Set : 1
Date: 10212009
12 34 56
25 67 90
End Set
+++++++++
Set: 2
Date: 10222009
34 56 89
25 67 89
End Set""".split("\n")
>>> print list(extract_data(data))
['12 34 56', '25 67 90', '34 56 89', '25 67 89']
From here it's simple to make a generator that yields the data from a file given its name:
def extract_data_from_file(filename):
with open(filename, 'rb') as f:
for item in extract_data(f):
yield item
...and to test it:
>>> list(extract_data_from_file(r'c:\temp\test\test1.txt'))
['12 34 56', '25 67 90', '34 56 89', '25 67 89']
Now build a generator that goes through all the text files in a directory:
def extract_data_from_directory(path):
for filename in os.listdir(path):
if filename.endswith('.txt'):
fullname = os.path.join(path, filename)
for item in extract_data_from_file(fullname):
yield item
...and then, after making a copy of test1.txt, test it:
>>> list(extract_data_from_directory(r'c:\temp\test'))
['12 34 56', '25 67 90', '34 56 89', '25 67 89', '12 34 56', '25 67 90', '34 56 89', '25 67 89']
A:
Follow the presentation slides from David M. Beazley at (if you are certain you want to skip the intro, start at page 18):
http://www.dabeaz.com/generators/
That is undisputably (in my opinion :) the very best way to solve what you are trying to achieve.
Basically, the thing you want is generators, and os.walk. A snip from Beazleys code:
import os
import fnmatch
import re
import gzip, bz2
def gen_find(filepat,top):
for path, dirlist, filelist in os.walk(top):
for name in fnmatch.filter(filelist,filepat):
yield os.path.join(path,name)
def gen_open(filenames):
for name in filenames:
if name.endswith(".gz"):
yield gzip.open(name)
elif name.endswith(".bz2"):
yield bz2.BZ2File(name)
else:
yield open(name)
def gen_cat(sources):
for s in sources:
for item in s:
yield item
def gen_grep(pat, lines):
patc = re.compile(pat)
for line in lines:
if patc.search(line): yield line
lognames = gen_find("access-log*", "/usr/www")
logfiles = gen_open(lognames)
loglines = gen_cat(logfiles)
patlines = gen_grep(pat, loglines)
# in your example you could set pat as "^[\d ]+$"
A:
You have many issues here.
for line in inputfile:
line = inputfile_fileHandle.readline()
inputfile is the name of your file, so this loop is going to be executed once for each character in the name of the file, definitely not what you want. You do this twice (nested), so for sure too many lines are being read.
The goto module was a joke. Get rid of it.
When you open the file, don't add 'b' to the mode. These are text files, open them as text, not binary.
A:
I'd probably do something even easier:
grep -E '[0-9][0-9] [0-9][0-9] [0-9][0-9]' *.txt
grep is available on Win32
A:
Several errors:
for line in inputfile:
inputfile is your filename. So the for loop will iterate over each character of the filename.
You need to do
for line in inputfile_fileHandle:
Then, line already contains your current line. Also, you probably don't need to open the file using 'rb' since it's a text file.
Then you nest an identical for loop inside the first loop (which is currently also completely wrong, iterating over the filename once again).
Not to mention the goto/label nonsense :)
kurosch has written a good version.
A:
f=0
for line in open("file"):
if "End Set" in line: f=0
if "Date" in line: f=1
elif f: print line.strip()
output
$ ./python.py
12 34 56
25 67 90
34 56 89
25 67 89
|
Python: Issue reading data lines multiple times from a file
|
I am trying to make a Python2.6 script on a Win32 that will read all the text files stored in a directory and print only the lines containing actual data. A sample file -
Set : 1
Date: 10212009
12 34 56
25 67 90
End Set
+++++++++
Set: 2
Date: 10222009
34 56 89
25 67 89
End Set
In the above example file, I want to print only the lines 3, 4 and 9, 10 (the actual data values). The program does this iteratively on all txt files.
I wrote the script as below and am testing it on a single txt file as I go.
My logic is to read the input files one by one and search for a start string. As soon as the match is found, start searching for end string. when both are found, print the lines from start string to end string.Repeat on the rest of the file before opening another file.
The problem I am having is that it successfully reads the Set 1 of data, but then screws up on subsequent sets in the file. For set 2, it identifies the no. of lines to read, but prints them starting at incorrect line number.
A little digging leads to following explanations -
1. Using seek and tell to reposition the 2nd iteration of the loop, which did not work since the file is read from buffer and that screws up "tell" value.
2. Opening the file in binary mode helped someone, but it is not working for me.
3. Open the file with 0 buffer mode, but it did not work.
Second problem I am having is when it prints data from Set 1, it inserts a blank line between 2 lines of data values. How can I get rid of it?
Note: Ignore all references to next_run in the code below. I was trying it out for repositioning line read. Subsequent searches for start string should begin from the last position of end string
#!C:/Python26 python
# Import necessary modules
import os, glob, string, sys, fileinput, linecache
from goto import goto, label
# Set working path
path = 'C:\\System_Data'
# --------------------
# PARSE DATA MODULE
# --------------------
# Define the search strings for data
start_search = "Set :"
end_search ="End Set"
# For Loop to read the input txt files one by one
for inputfile in glob.glob( os.path.join( path, '*.txt' ) ):
inputfile_fileHandle = open ( inputfile, 'rb', 0 )
print( "Current file being read: " +inputfile )
# start_line initializes to first line
start_line = 0
# After first set of data is extracted, next_run will store the position to read the rest of the file
# next_run = 0
# start reading the input files, one line by one line
for line in inputfile:
line = inputfile_fileHandle.readline()
start_line += 1
# next_run+=1
# If a line matched with the start_search string
has_match = line.find( start_search )
if has_match >= 0:
print ( "Start String found at line number: %d" %( start_line ) )
# Store the location where the search will be restarted
# next_run = inputfile_fileHandle.tell() #inputfile_fileHandle.lineno()
print ("Current Position: %d" % next_run)
end_line = start_line
print ( "Start_Line: %d" %start_line )
print ( "End_Line: %d" %end_line )
#print(line)
for line in inputfile:
line = inputfile_fileHandle.readline()
#print (line)
end_line += 1
has_match = line.find(end_search)
if has_match >= 0:
print 'End String found at line number: %d' % (end_line)
# total lines to print:
k=0
# for loop to print all the lines from start string to end string
for j in range(0,end_line-start_line-1):
print linecache.getline(inputfile, start_line +1+ j )
k+=1
print ( "Number of lines Printed: %d " %k )
# Using goto to get out of 2 loops at once
goto .re_search_start_string
label .re_search_start_string
#inputfile_fileHandle.seek(next_run,0)
inputfile_fileHandle.close ()
|
[
"in_data = False\nfor line in open( 'data.txt' ):\n if line.startswith( 'Date:' ):\n in_data = True\n elif line.startswith( 'End Set' ):\n in_data = False\n elif in_data:\n print line.rstrip()\n\nJust put something like that inside a loop over your files (i.e. os.walk) and you should be good to go\n",
"I'd probably do something much simpler, like this:\nimport glob, os\n\nstart_search = \"Set :\" \nend_search = \"End Set\" \npath = '.'\n\nfor filename in glob.glob(os.path.join(path, '*.txt')): \n inputfile = open(filename, 'rb', 0)\n print(\"Current file being read: \" + filename)\n is_in_set = False\n while True:\n line = inputfile.readline()\n if not line: break\n if line.startswith(start_search):\n is_in_set = True\n inputfile.readline() # Discard the next line.\n elif line.startswith(end_search):\n is_in_set = False\n print('---')\n elif is_in_set:\n print(line.rstrip()) # The rstrip removes the extra blank lines.\n\nIf you also want the line numbers, wrap the file object so that every time you call readline() it counts the line numbers.\n",
"The first thing I'd do is build a generator that uses a simple state machine to extract the data from a sequence:\ndef extract_data(seq):\n state = \"Waiting\"\n for item in seq:\n if state == \"Waiting\":\n if item.startswith(\"Set\"):\n state = \"SkippingDateLine\"\n continue\n if state == \"SkippingDateLine\":\n state = \"EmittingData\"\n continue\n if state == \"EmittingData\":\n if item.startswith(\"End Set\"):\n state = \"Waiting\"\n continue\n yield item.rstrip()\n\nNow I can test that generator to see if it really does what I think it's doing:\n>>> data = \"\"\"Set : 1 \nDate: 10212009 \n12 34 56 \n25 67 90\nEnd Set \n+++++++++\nSet: 2 \nDate: 10222009 \n34 56 89 \n25 67 89 \nEnd Set\"\"\".split(\"\\n\")\n\n>>> print list(extract_data(data))\n['12 34 56', '25 67 90', '34 56 89', '25 67 89']\n\nFrom here it's simple to make a generator that yields the data from a file given its name:\ndef extract_data_from_file(filename):\n with open(filename, 'rb') as f:\n for item in extract_data(f):\n yield item\n\n...and to test it:\n>>> list(extract_data_from_file(r'c:\\temp\\test\\test1.txt'))\n['12 34 56', '25 67 90', '34 56 89', '25 67 89']\n\nNow build a generator that goes through all the text files in a directory:\ndef extract_data_from_directory(path):\n for filename in os.listdir(path):\n if filename.endswith('.txt'):\n fullname = os.path.join(path, filename)\n for item in extract_data_from_file(fullname):\n yield item\n\n...and then, after making a copy of test1.txt, test it:\n>>> list(extract_data_from_directory(r'c:\\temp\\test'))\n['12 34 56', '25 67 90', '34 56 89', '25 67 89', '12 34 56', '25 67 90', '34 56 89', '25 67 89']\n\n",
"Follow the presentation slides from David M. Beazley at (if you are certain you want to skip the intro, start at page 18):\nhttp://www.dabeaz.com/generators/\nThat is undisputably (in my opinion :) the very best way to solve what you are trying to achieve.\nBasically, the thing you want is generators, and os.walk. A snip from Beazleys code:\nimport os\nimport fnmatch\nimport re\nimport gzip, bz2\n\ndef gen_find(filepat,top):\n for path, dirlist, filelist in os.walk(top):\n for name in fnmatch.filter(filelist,filepat):\n yield os.path.join(path,name)\n\ndef gen_open(filenames):\n for name in filenames:\n if name.endswith(\".gz\"):\n yield gzip.open(name)\n elif name.endswith(\".bz2\"):\n yield bz2.BZ2File(name)\n else:\n yield open(name)\n\ndef gen_cat(sources):\n for s in sources:\n for item in s:\n yield item\n\ndef gen_grep(pat, lines):\n patc = re.compile(pat)\n for line in lines:\n if patc.search(line): yield line\n\nlognames = gen_find(\"access-log*\", \"/usr/www\")\nlogfiles = gen_open(lognames)\nloglines = gen_cat(logfiles)\npatlines = gen_grep(pat, loglines)\n# in your example you could set pat as \"^[\\d ]+$\"\n\n",
"You have many issues here.\n for line in inputfile: \n line = inputfile_fileHandle.readline() \n\ninputfile is the name of your file, so this loop is going to be executed once for each character in the name of the file, definitely not what you want. You do this twice (nested), so for sure too many lines are being read.\nThe goto module was a joke. Get rid of it.\nWhen you open the file, don't add 'b' to the mode. These are text files, open them as text, not binary.\n",
"I'd probably do something even easier:\ngrep -E '[0-9][0-9] [0-9][0-9] [0-9][0-9]' *.txt\n\ngrep is available on Win32\n",
"Several errors:\nfor line in inputfile: \n\ninputfile is your filename. So the for loop will iterate over each character of the filename. \nYou need to do\nfor line in inputfile_fileHandle:\n\nThen, line already contains your current line. Also, you probably don't need to open the file using 'rb' since it's a text file.\nThen you nest an identical for loop inside the first loop (which is currently also completely wrong, iterating over the filename once again).\nNot to mention the goto/label nonsense :)\nkurosch has written a good version.\n",
"f=0\nfor line in open(\"file\"): \n if \"End Set\" in line: f=0\n if \"Date\" in line: f=1\n elif f: print line.strip() \n\noutput\n$ ./python.py\n12 34 56\n25 67 90\n34 56 89\n25 67 89\n\n"
] |
[
2,
2,
2,
1,
1,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001759320_python.txt
|
Q:
How can I run a Python program over telnet?
How can I run a Python program so it outputs its STDOUT and inputs its STDIN to/from a remote telnet client?
All the program does is print out text then wait for raw_input(), repeatedly. I want a remote user to use it without needing shell access. It can be single threaded/single user.
A:
On a Unix system, you can use inetd for this. It will take care of opening the network connection for you, so your program will work as-is.
A:
Make the Python script into the shell for that user. (Or if that doesn't work, wrap it up in bash script or even a executable).
(You might have to put it in /etc/shells (or equiv.))
A:
If you don't need full telnet functionality, you can just use a socket.
Check out the Socket Server module in the standard python library.
It'll enable you to easily write a program that'll listen on a port for input/output.
It won't support the proper telnet protocol negotiation, but you might not need that for what you're doing.
A:
You can just create a new linux user and set their shell to your script.
Then when they telnet in and enter the username/password, the program runs instead of bash or whatever the default shell is.
|
How can I run a Python program over telnet?
|
How can I run a Python program so it outputs its STDOUT and inputs its STDIN to/from a remote telnet client?
All the program does is print out text then wait for raw_input(), repeatedly. I want a remote user to use it without needing shell access. It can be single threaded/single user.
|
[
"On a Unix system, you can use inetd for this. It will take care of opening the network connection for you, so your program will work as-is.\n",
"Make the Python script into the shell for that user. (Or if that doesn't work, wrap it up in bash script or even a executable).\n(You might have to put it in /etc/shells (or equiv.))\n",
"If you don't need full telnet functionality, you can just use a socket.\nCheck out the Socket Server module in the standard python library.\nIt'll enable you to easily write a program that'll listen on a port for input/output.\nIt won't support the proper telnet protocol negotiation, but you might not need that for what you're doing. \n",
"You can just create a new linux user and set their shell to your script.\nThen when they telnet in and enter the username/password, the program runs instead of bash or whatever the default shell is.\n"
] |
[
10,
5,
4,
0
] |
[] |
[] |
[
"python",
"telnet"
] |
stackoverflow_0001758276_python_telnet.txt
|
Q:
How to merge duplicates in 2D python arrays
I have a set of data similar to this:
# Start_Time End_Time Call_Type Info
1 13:14:37.236 13:14:53.700 Ping1 RTT(Avr):160ms
2 13:14:58.955 13:15:29.984 Ping2 RTT(Avr):40ms
3 13:19:12.754 13:19:14.757 Ping3_1 RTT(Avr):620ms
3 13:19:12.754 Ping3_2 RTT(Avr):210ms
4 13:14:58.955 13:15:29.984 Ping4 RTT(Avr):360ms
5 13:19:12.754 13:19:14.757 Ping1 RTT(Avr):40ms
6 13:19:59.862 13:20:01.522 Ping2 RTT(Avr):163ms
...
When I parse through it, I need to merge the results of Ping3_1 and Ping3_2, take the average of those two rows, and export that as one row, so the end of result would be like this:
# Start_Time End_Time Call_Type Info
1 13:14:37.236 13:14:53.700 Ping1 RTT(Avr):160ms
2 13:14:58.955 13:15:29.984 Ping2 RTT(Avr):40ms
3 13:19:12.754 13:19:14.757 Ping3 RTT(Avr):415ms
4 13:14:58.955 13:15:29.984 Ping4 RTT(Avr):360ms
5 13:19:12.754 13:19:14.757 Ping1 RTT(Avr):40ms
6 13:19:59.862 13:20:01.522 Ping2 RTT(Avr):163ms
...
Currently, I am concatenating columns 0 and 1 to make a unique key, finding the duplication there, then doing the rest of the special treatment for those parallel pings. It is not elegant at all. Just wonder what is the better way to do it. Thanks!
A:
Assuming your duplicates are adjacent (as they're shown on your question), itertools.groupby is the ideal way to identify them as duplicates (with a little help from operator.itemgetter to extract the "key" defining identity. Assuming you have a list of objects (the pings) with attributes such as .start and .end:
import itertools
import operator
def merge(listofpings):
k = operator.itemgetter('start', 'end')
for i, grp in itertools.groupby(listofpings, key=k):
lst = list(grp)
if len(lst) > 2:
item = mergepings(lst)
else:
item = lst[0]
emitping(i, item)
assuming you already have functions mergepings to merge a list of > 1 "duplicate" pings, and emitping to emit a numbered ping (bare or merged).
If listofpings is not already properly sorted, just add listofpings.sort(key=k) just before the for loop (presumably emitting in sorted order is OK, right?).
A:
Assuming the duplicates are adjacent you can use a generator like this. I guess you already have some code to average the pings
def average_pings(ping1, ping2):
pass
def merge_pings(seq):
prev_key=prev_key=None
for item in seq:
key = item.split()[:2]
if key == prev_key:
yield average_pings(prev_item, item)
else:
yield item
prev_key=key
prev_item=item
A:
I'm not sure on how your data is structured, so I'll assume a list of dicts for duck typing purposes.
I'm also assuming the real primary key of your dataset is Start.
for i in range(len(dataset)-1):
#Detect duplicates, assuming they are sorted properly
if dataset[i]["Start"] == dataset[i+1]["Start"]:
#Merge 'em
dataset[i+1] = merge(dataset[i], dataset[i+1])
#Deleting items from the array you are iterating over is a bad idea
dataset[i] = None
dataset = [item for item in dataset if item != None] #so just delete them later
...where merge would be the function that actually does the merging.
Not elegant, C-ish, but probably better than what you are currently using.
They're not sorted?
dataset.sort( (lambda x,y: return cmp(x["Start"],y["Start"])) )
Now they should be.
|
How to merge duplicates in 2D python arrays
|
I have a set of data similar to this:
# Start_Time End_Time Call_Type Info
1 13:14:37.236 13:14:53.700 Ping1 RTT(Avr):160ms
2 13:14:58.955 13:15:29.984 Ping2 RTT(Avr):40ms
3 13:19:12.754 13:19:14.757 Ping3_1 RTT(Avr):620ms
3 13:19:12.754 Ping3_2 RTT(Avr):210ms
4 13:14:58.955 13:15:29.984 Ping4 RTT(Avr):360ms
5 13:19:12.754 13:19:14.757 Ping1 RTT(Avr):40ms
6 13:19:59.862 13:20:01.522 Ping2 RTT(Avr):163ms
...
When I parse through it, I need to merge the results of Ping3_1 and Ping3_2, take the average of those two rows, and export that as one row, so the end of result would be like this:
# Start_Time End_Time Call_Type Info
1 13:14:37.236 13:14:53.700 Ping1 RTT(Avr):160ms
2 13:14:58.955 13:15:29.984 Ping2 RTT(Avr):40ms
3 13:19:12.754 13:19:14.757 Ping3 RTT(Avr):415ms
4 13:14:58.955 13:15:29.984 Ping4 RTT(Avr):360ms
5 13:19:12.754 13:19:14.757 Ping1 RTT(Avr):40ms
6 13:19:59.862 13:20:01.522 Ping2 RTT(Avr):163ms
...
Currently, I am concatenating columns 0 and 1 to make a unique key, finding the duplication there, then doing the rest of the special treatment for those parallel pings. It is not elegant at all. Just wonder what is the better way to do it. Thanks!
|
[
"Assuming your duplicates are adjacent (as they're shown on your question), itertools.groupby is the ideal way to identify them as duplicates (with a little help from operator.itemgetter to extract the \"key\" defining identity. Assuming you have a list of objects (the pings) with attributes such as .start and .end:\nimport itertools\nimport operator\n\ndef merge(listofpings):\n k = operator.itemgetter('start', 'end')\n for i, grp in itertools.groupby(listofpings, key=k):\n lst = list(grp)\n if len(lst) > 2:\n item = mergepings(lst)\n else:\n item = lst[0]\n emitping(i, item)\n\nassuming you already have functions mergepings to merge a list of > 1 \"duplicate\" pings, and emitping to emit a numbered ping (bare or merged).\nIf listofpings is not already properly sorted, just add listofpings.sort(key=k) just before the for loop (presumably emitting in sorted order is OK, right?).\n",
"Assuming the duplicates are adjacent you can use a generator like this. I guess you already have some code to average the pings\ndef average_pings(ping1, ping2):\n pass\n\ndef merge_pings(seq):\n prev_key=prev_key=None\n for item in seq:\n key = item.split()[:2]\n if key == prev_key:\n yield average_pings(prev_item, item)\n else:\n yield item\n prev_key=key\n prev_item=item\n\n",
"I'm not sure on how your data is structured, so I'll assume a list of dicts for duck typing purposes.\nI'm also assuming the real primary key of your dataset is Start.\nfor i in range(len(dataset)-1):\n #Detect duplicates, assuming they are sorted properly\n if dataset[i][\"Start\"] == dataset[i+1][\"Start\"]:\n #Merge 'em\n dataset[i+1] = merge(dataset[i], dataset[i+1])\n\n #Deleting items from the array you are iterating over is a bad idea\n dataset[i] = None\n\ndataset = [item for item in dataset if item != None] #so just delete them later\n\n...where merge would be the function that actually does the merging.\nNot elegant, C-ish, but probably better than what you are currently using.\nThey're not sorted?\ndataset.sort( (lambda x,y: return cmp(x[\"Start\"],y[\"Start\"])) )\n\nNow they should be.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"arrays",
"duplicates",
"merge",
"python"
] |
stackoverflow_0001759369_arrays_duplicates_merge_python.txt
|
Q:
extract the number and name of python method arguments
How can I return the arguments of a function in a different module
#Module: functionss.py
def simple(a, b, c):
print "does something"
#Module: extract.py
#load the called module and function
def get_args(module_name, function_name):
modFile, modPath, modDesc = imp.find_module(module_name)
mod = imp.load_module(module_name,modFile,modPath,modDesc)
attr = getattr(mod, function_name)
#this is the part I don't get - how do I read the arguments
return = attr.get_the_args()
if __name__ == "__main__":
print get_args("functions.py", "simple")
#this would ideally print [a, b, c]
A:
Use inspect.getargspec for the "heavy lifting" (introspecting a function).
Use __import__ to import a module (given its module name -- "functions.py" is a terrible way to specify a module name;-).
Use getattr(moduleobject, functionname) to get the function object given module object and function name.
|
extract the number and name of python method arguments
|
How can I return the arguments of a function in a different module
#Module: functionss.py
def simple(a, b, c):
print "does something"
#Module: extract.py
#load the called module and function
def get_args(module_name, function_name):
modFile, modPath, modDesc = imp.find_module(module_name)
mod = imp.load_module(module_name,modFile,modPath,modDesc)
attr = getattr(mod, function_name)
#this is the part I don't get - how do I read the arguments
return = attr.get_the_args()
if __name__ == "__main__":
print get_args("functions.py", "simple")
#this would ideally print [a, b, c]
|
[
"Use inspect.getargspec for the \"heavy lifting\" (introspecting a function).\nUse __import__ to import a module (given its module name -- \"functions.py\" is a terrible way to specify a module name;-).\nUse getattr(moduleobject, functionname) to get the function object given module object and function name.\n"
] |
[
1
] |
[] |
[] |
[
"arguments",
"function",
"python"
] |
stackoverflow_0001760945_arguments_function_python.txt
|
Q:
sum of two numbers coming from the command line
I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):
import sys
a= sys.argv[1]
b= sys.argv[2]
sum=str( a+b)
print " sum is", sum
A:
You should do this:
import sys
a, b = sys.argv[1:2]
summ = int(a) + int(b)
print "sum is", summ
There is no need for str() when printing an integer. But you should use int() if you want to add a and b as integers.
A:
The error list index out of range means that you are trying to access a list item that is outside the bounds of the list.
Example:
>>> mylist = ['hello', 'world']
>>> print mylist[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
In your case, the error comes from either sys.argv[1] or sys.argv[2].
Make sure you actually pass something to the program from the command line.
A:
Assuming your inputs are integers:
import sys
summ = sum(map(int,sys.argv[1:])
print "sum is ", summ
or
import sys
summ = sum(int(i) for i in sys.argv[1:])
print "sum is ", summ
If not, change int to float.
The second method is probably more pythonic, but the first is a little faster in this instance.
>>>import timeit
>>>t1 = timeit.Timer("sum(map(int,['3','5','7','9']))")
>>>t2 = timeit.Timer("sum(int(i) for i in ['3','5','7','9'])")
>>>print t1.timeit()
3.0187220573425293
>>>print t2.timeit()
3.4699549674987793
A:
su = int(a) + int(b)
print("sum is %d" % su)
And you should be careful with your variable naming. sum shadows the built-in, it's not a good practice to do that (that is, don't name variables as built-in functions or any globally defined name).
A:
If your error is "list index out of range", then the problem is that your list doesn't have enough items. Which list? The only list you're using is sys.argv, so to populate it, you need to pass more items on the command line.
Alternatively, check for the length of the argument list with len(sys.argv) and prompt interactively (e.g. using raw_input()) to get the values if they're not in sys.argv.
A:
If you wish to sum the numbers as floating points number use "float" instead of "int", like in the following snippet.
import sys
try:
a, b = sys.argv[1:3]
print "sum is ", float(a) + float(b)
except ValueError:
print "please give me two numbers to sum"
Beware that floating points are different from real numbers, so that you could obtain seemingly "strange" results about which there is a wealth of documentation on the web.
A:
Thanks to every one. I got the answer
for i in range (1,51):
if i%5==0:
print i,"\n"
else:
print i,
|
sum of two numbers coming from the command line
|
I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):
import sys
a= sys.argv[1]
b= sys.argv[2]
sum=str( a+b)
print " sum is", sum
|
[
"You should do this:\nimport sys\na, b = sys.argv[1:2]\nsumm = int(a) + int(b)\nprint \"sum is\", summ\n\nThere is no need for str() when printing an integer. But you should use int() if you want to add a and b as integers.\n",
"The error list index out of range means that you are trying to access a list item that is outside the bounds of the list.\nExample:\n>>> mylist = ['hello', 'world']\n>>> print mylist[2]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nIndexError: list index out of range\n\nIn your case, the error comes from either sys.argv[1] or sys.argv[2].\nMake sure you actually pass something to the program from the command line.\n",
"Assuming your inputs are integers:\nimport sys\nsumm = sum(map(int,sys.argv[1:])\nprint \"sum is \", summ\n\nor\nimport sys\nsumm = sum(int(i) for i in sys.argv[1:])\nprint \"sum is \", summ\n\nIf not, change int to float.\nThe second method is probably more pythonic, but the first is a little faster in this instance.\n>>>import timeit\n>>>t1 = timeit.Timer(\"sum(map(int,['3','5','7','9']))\")\n>>>t2 = timeit.Timer(\"sum(int(i) for i in ['3','5','7','9'])\")\n>>>print t1.timeit()\n3.0187220573425293\n>>>print t2.timeit()\n3.4699549674987793\n\n",
"su = int(a) + int(b)\nprint(\"sum is %d\" % su)\n\nAnd you should be careful with your variable naming. sum shadows the built-in, it's not a good practice to do that (that is, don't name variables as built-in functions or any globally defined name).\n",
"If your error is \"list index out of range\", then the problem is that your list doesn't have enough items. Which list? The only list you're using is sys.argv, so to populate it, you need to pass more items on the command line.\nAlternatively, check for the length of the argument list with len(sys.argv) and prompt interactively (e.g. using raw_input()) to get the values if they're not in sys.argv.\n",
"If you wish to sum the numbers as floating points number use \"float\" instead of \"int\", like in the following snippet.\nimport sys\ntry:\n a, b = sys.argv[1:3]\n print \"sum is \", float(a) + float(b)\nexcept ValueError:\n print \"please give me two numbers to sum\"\n\nBeware that floating points are different from real numbers, so that you could obtain seemingly \"strange\" results about which there is a wealth of documentation on the web.\n",
"Thanks to every one. I got the answer\nfor i in range (1,51):\n if i%5==0:\n print i,\"\\n\"\n else:\n print i,\n"
] |
[
5,
3,
3,
0,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001356348_python.txt
|
Q:
Shorten Python imports?
I'm working on a Django project. Let's call it myproject. Now my code is littered with myproject.folder.file.function. Is there anyway I can remove the need to prefix all my imports and such with myproject.? What if I want to rename my project later? It kind of annoys me that I need to prefix stuff like that when the very file I'm importing it from is inside that same project. Shouldn't be necessary.
A:
from myproject.folder import file (horrible name, btw, trampling over the builtin type file, but that's another rant;-), then use file.function -- if file (gotta hate that module name;-) is still too long for you, add e.g. as fi to the from statement, and use fi.function. If you want to rename myproject to myhorror, you only need to touch the from statements addressing it (you could use relative imports, but those would break 2.5 compatibility and therefore ban you from App Engine for now -- too high a price to pay for minor convenience, for me at least;-).
Edit: if just about every file needs some given supporting module, that's a powerful reason for making sure that supporting module lives in a directory (or zipfile) that's on sys.path (it's probably worth doing even if, say, only 30% of the files need that supporting module!-).
A:
import x as y
import x.y as z
from x import y as z
The "as" allows you to give your own name to an imported module. For example, import os as System would allow you to call the components of the os module like so:
System.path.abspath('bla')
For more information about imports, read: Importing Python Modules
A:
If you don't mind clobbering file:
from myproject.folder import file
If you want to make file something shorter:
import myproject.folder.file as f
You could create your own import statement if you were feeling really fancy:
head = 'myproject.folder.'
def my_import(name,*args,**kwargs):
try:
return __import__(name, *args, **kwargs)
except ImportError:
return __import__(head+name, *args, **kwargs)
file = my_import('file')
You can also be outright evil, and hack the builtin python import statement:
head = 'myproject.folder.'
_import = __import__ # don't clobber __import__ yet
def my_import(name,*args,**kwargs):
try:
return _import(name,*args,**kwargs)
except ImportError:
return _import(head+name, *args, **kwargs)
__builtins__.__import__ = my_import # God just killed a maintainer
# elsewhere, after the above abomination has run:
import file # I hope you are happy.
Actually, I'm exaggerating the evil of clobbering built-in functions. It's not that bad. But it is a little bit hairy.
|
Shorten Python imports?
|
I'm working on a Django project. Let's call it myproject. Now my code is littered with myproject.folder.file.function. Is there anyway I can remove the need to prefix all my imports and such with myproject.? What if I want to rename my project later? It kind of annoys me that I need to prefix stuff like that when the very file I'm importing it from is inside that same project. Shouldn't be necessary.
|
[
"from myproject.folder import file (horrible name, btw, trampling over the builtin type file, but that's another rant;-), then use file.function -- if file (gotta hate that module name;-) is still too long for you, add e.g. as fi to the from statement, and use fi.function. If you want to rename myproject to myhorror, you only need to touch the from statements addressing it (you could use relative imports, but those would break 2.5 compatibility and therefore ban you from App Engine for now -- too high a price to pay for minor convenience, for me at least;-).\nEdit: if just about every file needs some given supporting module, that's a powerful reason for making sure that supporting module lives in a directory (or zipfile) that's on sys.path (it's probably worth doing even if, say, only 30% of the files need that supporting module!-).\n",
"import x as y\nimport x.y as z\nfrom x import y as z\n\nThe \"as\" allows you to give your own name to an imported module. For example, import os as System would allow you to call the components of the os module like so:\nSystem.path.abspath('bla')\nFor more information about imports, read: Importing Python Modules\n",
"If you don't mind clobbering file:\nfrom myproject.folder import file\n\nIf you want to make file something shorter:\nimport myproject.folder.file as f \n\nYou could create your own import statement if you were feeling really fancy:\nhead = 'myproject.folder.'\ndef my_import(name,*args,**kwargs):\n try:\n return __import__(name, *args, **kwargs)\n except ImportError: \n return __import__(head+name, *args, **kwargs)\n\nfile = my_import('file')\n\nYou can also be outright evil, and hack the builtin python import statement:\nhead = 'myproject.folder.'\n\n_import = __import__ # don't clobber __import__ yet\n\ndef my_import(name,*args,**kwargs):\n try: \n return _import(name,*args,**kwargs)\n except ImportError:\n return _import(head+name, *args, **kwargs)\n\n__builtins__.__import__ = my_import # God just killed a maintainer\n\n# elsewhere, after the above abomination has run:\nimport file # I hope you are happy.\n\nActually, I'm exaggerating the evil of clobbering built-in functions. It's not that bad. But it is a little bit hairy.\n"
] |
[
5,
4,
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001760963_django_python.txt
|
Q:
Python: Convert string into function name; getattr or equal?
I am editing PROSS.py to work with .cif files for protein structures. Inside the existing PROSS.py, there is the following functions (I believe that's the correct name if it's not associated with any class?), just existing within the .py file:
...
def unpack_pdb_line(line, ATOF=_atof, ATOI=_atoi, STRIP=string.strip):
...
...
def read_pdb(f, as_protein=0, as_rna=0, as_dna=0, all_models=0,
unpack=unpack_pdb_line, atom_build=atom_build):
I am adding an optons parser for command line arguments, and one of the options is to specify an alternate method to use besides unpack_pdb_line. So the pertinent part of the options parser is:
...
parser.add_option("--un", dest="unpack_method", default="unpack_pdb_line", type="string", help="Unpack method to use. Default is unpack_pdb_line.")
...
unpack=options.unpack_method
However, options.unpack_method is a string and I need to use the function with the same name as the string inside options.unpack_method. How do I use getattr etc to convert the string into the actual function name?
Thanks,
Paul
A:
Usually you just use a dict and store (func_name, function) pairs:
unpack_options = { 'unpack_pdb_line' : unpack_pdb_line,
'some_other' : some_other_function }
unpack_function = unpack_options[options.unpack_method]
A:
If you want to exploit the dictionaries (&c) that Python's already keeping on your behalf, I'd suggest:
def str2fun(astr):
module, _, function = astr.rpartition('.')
if module:
__import__(module)
mod = sys.modules[module]
else:
mod = sys.modules['__main__'] # or whatever's the "default module"
return getattr(mod, function)
You'll probably want to check the function's signature (and catch exceptions to provide nicer error messages) e.g. via inspect, but this is a useful general-purpose function.
It's easy to add a dictionary of shortcuts, as a fallback, if some known functions full string names (including module/package qualifications) are unwieldy to express this way.
Note we don't use __import__'s result (it doesn't work right when the function is in a module inside some package, as __import__ returns the top-level name of the package... just accessing sys.modules after the import is more practical).
A:
If you are taking input from a user, for the sake of security it is probably best to
use a hand-made dict which will accept only a well-defined set of admissible user inputs:
unpack_options = { 'unpack_pdb_line' : unpack_pdb_line,
'unpack_pdb_line2' : unpack_pdb_line2,
}
Ignoring security for a moment, let us note in passing that an easy way to
go from (strings of variable names) to (the value referenced by the variable name)
is to use the globals() builtin dict:
unpack_function=globals()['unpack_pdb_line']
Of course, that will only work if the variable unpack_pdb_line is in the global namespace.
If you need to reach into a packgae for a module, or a module for a variable, then
you could use this function
import sys
def str_to_obj(astr):
print('processing %s'%astr)
try:
return globals()[astr]
except KeyError:
try:
__import__(astr)
mod=sys.modules[astr]
return mod
except ImportError:
module,_,basename=astr.rpartition('.')
if module:
mod=str_to_obj(module)
return getattr(mod,basename)
else:
raise
You could use it like this:
str_to_obj('scipy.stats')
# <module 'scipy.stats' from '/usr/lib/python2.6/dist-packages/scipy/stats/__init__.pyc'>
str_to_obj('scipy.stats.stats')
# <module 'scipy.stats.stats' from '/usr/lib/python2.6/dist-packages/scipy/stats/stats.pyc'>
str_to_obj('scipy.stats.stats.chisquare')
# <function chisquare at 0xa806844>
It works for nested packages, modules, functions, or (global) variables.
A:
vars()["unpack_pdb_line"]() will work too.
or
globals() or locals() will also work similar way.
>>> def a():return 1
>>>
>>> vars()["a"]
<function a at 0x009D1230>
>>>
>>> vars()["a"]()
1
>>> locals()["a"]()
1
>>> globals()["a"]()
1
Cheers,
A:
function = eval_dottedname(name if '.' in name else "%s.%s" % (__name__, name))
Where eval_dottedname():
def eval_dottedname(dottedname):
"""
>>> eval_dottedname("os.path.join") #doctest: +ELLIPSIS
<function join at 0x...>
>>> eval_dottedname("sys.exit") #doctest: +ELLIPSIS
<built-in function exit>
>>> eval_dottedname("sys") #doctest: +ELLIPSIS
<module 'sys' (built-in)>
"""
return reduce(getattr, dottedname.split(".")[1:],
__import__(dottedname.partition(".")[0]))
eval_dottedname() is the only one among all answers that supports arbitrary names with multiple dots in them e.g., `'datetime.datetime.now'. Though it doesn't work for nested modules that require import, but I can't even remember an example from stdlib for such module.
|
Python: Convert string into function name; getattr or equal?
|
I am editing PROSS.py to work with .cif files for protein structures. Inside the existing PROSS.py, there is the following functions (I believe that's the correct name if it's not associated with any class?), just existing within the .py file:
...
def unpack_pdb_line(line, ATOF=_atof, ATOI=_atoi, STRIP=string.strip):
...
...
def read_pdb(f, as_protein=0, as_rna=0, as_dna=0, all_models=0,
unpack=unpack_pdb_line, atom_build=atom_build):
I am adding an optons parser for command line arguments, and one of the options is to specify an alternate method to use besides unpack_pdb_line. So the pertinent part of the options parser is:
...
parser.add_option("--un", dest="unpack_method", default="unpack_pdb_line", type="string", help="Unpack method to use. Default is unpack_pdb_line.")
...
unpack=options.unpack_method
However, options.unpack_method is a string and I need to use the function with the same name as the string inside options.unpack_method. How do I use getattr etc to convert the string into the actual function name?
Thanks,
Paul
|
[
"Usually you just use a dict and store (func_name, function) pairs:\nunpack_options = { 'unpack_pdb_line' : unpack_pdb_line,\n 'some_other' : some_other_function }\n\nunpack_function = unpack_options[options.unpack_method]\n\n",
"If you want to exploit the dictionaries (&c) that Python's already keeping on your behalf, I'd suggest:\ndef str2fun(astr):\n module, _, function = astr.rpartition('.')\n if module:\n __import__(module)\n mod = sys.modules[module]\n else:\n mod = sys.modules['__main__'] # or whatever's the \"default module\"\n return getattr(mod, function)\n\nYou'll probably want to check the function's signature (and catch exceptions to provide nicer error messages) e.g. via inspect, but this is a useful general-purpose function.\nIt's easy to add a dictionary of shortcuts, as a fallback, if some known functions full string names (including module/package qualifications) are unwieldy to express this way.\nNote we don't use __import__'s result (it doesn't work right when the function is in a module inside some package, as __import__ returns the top-level name of the package... just accessing sys.modules after the import is more practical).\n",
"If you are taking input from a user, for the sake of security it is probably best to\nuse a hand-made dict which will accept only a well-defined set of admissible user inputs:\nunpack_options = { 'unpack_pdb_line' : unpack_pdb_line,\n 'unpack_pdb_line2' : unpack_pdb_line2,\n } \n\nIgnoring security for a moment, let us note in passing that an easy way to\ngo from (strings of variable names) to (the value referenced by the variable name)\nis to use the globals() builtin dict:\nunpack_function=globals()['unpack_pdb_line']\n\nOf course, that will only work if the variable unpack_pdb_line is in the global namespace. \nIf you need to reach into a packgae for a module, or a module for a variable, then\nyou could use this function\nimport sys\ndef str_to_obj(astr):\n print('processing %s'%astr)\n try:\n return globals()[astr]\n except KeyError:\n try:\n __import__(astr)\n mod=sys.modules[astr]\n return mod\n except ImportError:\n module,_,basename=astr.rpartition('.')\n if module:\n mod=str_to_obj(module)\n return getattr(mod,basename)\n else:\n raise\n\nYou could use it like this:\nstr_to_obj('scipy.stats')\n# <module 'scipy.stats' from '/usr/lib/python2.6/dist-packages/scipy/stats/__init__.pyc'>\n\nstr_to_obj('scipy.stats.stats')\n# <module 'scipy.stats.stats' from '/usr/lib/python2.6/dist-packages/scipy/stats/stats.pyc'>\n\nstr_to_obj('scipy.stats.stats.chisquare')\n# <function chisquare at 0xa806844>\n\nIt works for nested packages, modules, functions, or (global) variables.\n",
"vars()[\"unpack_pdb_line\"]() will work too.\nor \nglobals() or locals() will also work similar way.\n>>> def a():return 1\n>>>\n>>> vars()[\"a\"]\n<function a at 0x009D1230>\n>>>\n>>> vars()[\"a\"]()\n1\n>>> locals()[\"a\"]()\n1\n>>> globals()[\"a\"]()\n1\n\nCheers,\n",
"function = eval_dottedname(name if '.' in name else \"%s.%s\" % (__name__, name))\n\nWhere eval_dottedname():\ndef eval_dottedname(dottedname):\n \"\"\"\n >>> eval_dottedname(\"os.path.join\") #doctest: +ELLIPSIS\n <function join at 0x...>\n >>> eval_dottedname(\"sys.exit\") #doctest: +ELLIPSIS\n <built-in function exit>\n >>> eval_dottedname(\"sys\") #doctest: +ELLIPSIS\n <module 'sys' (built-in)>\n \"\"\"\n return reduce(getattr, dottedname.split(\".\")[1:],\n __import__(dottedname.partition(\".\")[0]))\n\neval_dottedname() is the only one among all answers that supports arbitrary names with multiple dots in them e.g., `'datetime.datetime.now'. Though it doesn't work for nested modules that require import, but I can't even remember an example from stdlib for such module.\n"
] |
[
9,
4,
3,
3,
1
] |
[] |
[] |
[
"function",
"getattr",
"python"
] |
stackoverflow_0001738687_function_getattr_python.txt
|
Q:
Installing Trac with Subversion 1.6
I'm trying to set up Trac on my server and have successfully installed it, compiled the bytecode and run the tracd server. The only problem is that it's not reading my SVN repository.
The error I'm receiving is:
Warning: Can't synchronize with the repository (Couldn't open Subversion repository /data1/repos: SubversionException: ("Expected FS format '2'; found format '4'", 160043)). Look in the Trac log for more information.
(Yes, my single repository is in a folder called "repos" - I didn't set that bit up)
The trac.ini looks like this:
repository_dir = /data1/repos
repository_type = svn
I'm running: Trac 0.11.5, Python 2.4.3, Collabnet SVN 1.6.5, SWIG 1.3.29
A:
Is your python svn library updated? Sounds like it's stale.
A:
you should make sure the python binding match your SVN version.
to get the binding you can use the SVN source and compile the wrapper, the install give an overview of the process how to build that binding.
first you would have to download the svn source
BUILDING SWIG BINDINGS FOR SVN ON UNIX
after build the swig binding
Step 1: Install a suitable version of
SWIG (which is
currently swig version 1.3.24 - 1.3.31).
* Perhaps your distribution packages a suitable version - if it
does
install it, and skip to the last bullet point in this section.
* Go to http://www.swig.org/, download the source tarball, and
unpack.
* In the SWIG-1.3.xx directory, run ./configure.
If you plan to build the Python bindings, and have a system
with more than one version of Python installed, you may need
to pass
--with-python=/path/to/correct/python/binary
to the configure script. You need Python 2.4 or above.
If you plan to build the Perl bindings, and have a system
with more than one version of perl installed, you may need
to pass
--with-perl5=/path/to/correct/perl/binary
to the configure script. You need Perl 5.8.0 or above.
* Build and install.
Run 'make && make install'
* To verify you have SWIG installed correctly, run "swig
-version"
from the command line. SWIG should report that it is version
1.3.24
or newer.
and then python things
Step 3: Install Specific Language
Bindings
Python
Run 'make swig-py' from the top of the Subversion source tree,
to build the bindings.
(This will invoke SWIG on the *.i files, resulting in a collection
of .c source files. It will then compile and link those .c files
into
Python libraries.)
Run 'make check-swig-py' from the top of the Subversion source
tree, to test the bindings
Run 'make install-swig-py' (as root, typically)
from the top of the Subversion source tree. This will copy
your new Python libraries into the appropriate system location.
Note: If you don't have access to install to Python's site-packages
directory, you can have the Python modules install to your home
directory. You can do this by running
'make install-swig-py swig_pydir=~'.
Note: If you want to install to an alternate prefix (usually only
if you are building packages), you can supply the prefix here. An
example of doing this for building rpms looks like
'make install-swig-py DESTDIR=$RPM_BUILD_ROOT/usr'.
Make sure that whatever directory the bindings got installed
in
is in your Python search path. That directory depends on how you
installed; a typical location is /usr/local/lib/svn-python/.
There are several ways to do this. See Python's documentation for
'sys.path' and 'PYTHONPATH'. A nice way to do this is:
$ echo /usr/local/lib/svn-python \
/usr/lib/python2.x/site-packages/subversion.pth
You may also need to update your operating system's dynamic linker
configuration to enable Python to load these new libraries. On some
systems this is done by running 'ldconfig'.
A:
It may be that the Subversion Python bindings are compiled against a too-old version of Subversion, but given FS format 2 is pre-1.0, it's possible something else is wrong. You can get the Subversion client library version like this:
>>> import svn.client
>>> svn.client.svn_client_version().major
1
>>> svn.client.svn_client_version().minor
6
>>> svn.client.svn_client_version().patch
5
A:
Looks like these guys answered your question pretty thoroughly but FYI: setup the log file so you can read it during your next problem. In your trac.ini somewhere:
[logging]
log_file = trac.log
# log_format = <inherited>
log_level = DEBUG
log_type = file
After that, try to deploy trac to apache if possible - with mod_python or FastCGI the trac documentation says it's a lot faster than running tracd.
|
Installing Trac with Subversion 1.6
|
I'm trying to set up Trac on my server and have successfully installed it, compiled the bytecode and run the tracd server. The only problem is that it's not reading my SVN repository.
The error I'm receiving is:
Warning: Can't synchronize with the repository (Couldn't open Subversion repository /data1/repos: SubversionException: ("Expected FS format '2'; found format '4'", 160043)). Look in the Trac log for more information.
(Yes, my single repository is in a folder called "repos" - I didn't set that bit up)
The trac.ini looks like this:
repository_dir = /data1/repos
repository_type = svn
I'm running: Trac 0.11.5, Python 2.4.3, Collabnet SVN 1.6.5, SWIG 1.3.29
|
[
"Is your python svn library updated? Sounds like it's stale.\n",
"you should make sure the python binding match your SVN version. \nto get the binding you can use the SVN source and compile the wrapper, the install give an overview of the process how to build that binding. \nfirst you would have to download the svn source\nBUILDING SWIG BINDINGS FOR SVN ON UNIX\nafter build the swig binding \n\nStep 1: Install a suitable version of\n SWIG (which is\n currently swig version 1.3.24 - 1.3.31).\n* Perhaps your distribution packages a suitable version - if it\n\ndoes\n install it, and skip to the last bullet point in this section.\n* Go to http://www.swig.org/, download the source tarball, and\n\nunpack.\n* In the SWIG-1.3.xx directory, run ./configure.\n\n If you plan to build the Python bindings, and have a system\n with more than one version of Python installed, you may need\n to pass\n\n --with-python=/path/to/correct/python/binary\n\n to the configure script. You need Python 2.4 or above.\n\n If you plan to build the Perl bindings, and have a system\n with more than one version of perl installed, you may need\n to pass\n\n --with-perl5=/path/to/correct/perl/binary\n\n to the configure script. You need Perl 5.8.0 or above.\n\n* Build and install.\n\n Run 'make && make install'\n\n* To verify you have SWIG installed correctly, run \"swig\n\n-version\"\n from the command line. SWIG should report that it is version\n 1.3.24\n or newer.\n\nand then python things\n\nStep 3: Install Specific Language\n Bindings\n\nPython\n\nRun 'make swig-py' from the top of the Subversion source tree,\n to build the bindings.\n(This will invoke SWIG on the *.i files, resulting in a collection\n of .c source files. It will then compile and link those .c files\n into\n Python libraries.)\nRun 'make check-swig-py' from the top of the Subversion source\n tree, to test the bindings \nRun 'make install-swig-py' (as root, typically)\n from the top of the Subversion source tree. This will copy\n your new Python libraries into the appropriate system location.\nNote: If you don't have access to install to Python's site-packages\n directory, you can have the Python modules install to your home\n directory. You can do this by running\n 'make install-swig-py swig_pydir=~'.\nNote: If you want to install to an alternate prefix (usually only\n if you are building packages), you can supply the prefix here. An\n example of doing this for building rpms looks like\n 'make install-swig-py DESTDIR=$RPM_BUILD_ROOT/usr'.\nMake sure that whatever directory the bindings got installed\n in\n is in your Python search path. That directory depends on how you\n installed; a typical location is /usr/local/lib/svn-python/.\nThere are several ways to do this. See Python's documentation for\n 'sys.path' and 'PYTHONPATH'. A nice way to do this is:\n $ echo /usr/local/lib/svn-python \\\n\n/usr/lib/python2.x/site-packages/subversion.pth\n\nYou may also need to update your operating system's dynamic linker\n configuration to enable Python to load these new libraries. On some\n systems this is done by running 'ldconfig'.\n\n\n\n",
"It may be that the Subversion Python bindings are compiled against a too-old version of Subversion, but given FS format 2 is pre-1.0, it's possible something else is wrong. You can get the Subversion client library version like this:\n>>> import svn.client\n>>> svn.client.svn_client_version().major\n1\n>>> svn.client.svn_client_version().minor\n6\n>>> svn.client.svn_client_version().patch\n5\n\n",
"Looks like these guys answered your question pretty thoroughly but FYI: setup the log file so you can read it during your next problem. In your trac.ini somewhere:\n[logging]\nlog_file = trac.log\n# log_format = <inherited>\nlog_level = DEBUG\nlog_type = file\n\nAfter that, try to deploy trac to apache if possible - with mod_python or FastCGI the trac documentation says it's a lot faster than running tracd.\n"
] |
[
3,
3,
2,
0
] |
[] |
[] |
[
"installation",
"python",
"svn",
"trac"
] |
stackoverflow_0001740165_installation_python_svn_trac.txt
|
Q:
mechanize can't login python
I'm making auto-login script by use mechanize python.
Before I was used mechanize with no problem, but www.gmarket.co.kr in this site I couldn't make it .
whenever i try to login always login page was returned even with correct gmarket id , pass, i can't login and I saw some suspicious message
"<script language=javascript>top.location.reload();</script>"
I think this related with my problem, but don't know exactly how to handle .
Here is sample id and pass for login test
id: tgi177 pass: tk1047
if anyone can help me much appreciate thanks in advance
CODE:
# -*- coding: cp949 -*-
from lxml.html import parse, fromstring
import sys,os
import mechanize, urllib
import cookielib
import re
from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag
try:
params = urllib.urlencode({'command':'login',
'url':'http%3A%2F%2Fwww.gmarket.co.kr%2F',
'member_type':'mem',
'member_yn':'Y',
'login_id':'tgi177',
'image1.x':'31',
'image1.y':'26',
'passwd':'tk1047',
'buyer_nm':'',
'buyer_tel_no1':'',
'buyer_tel_no2':'',
'buyer_tel_no3':''
})
rq = mechanize.Request("http://www.gmarket.co.kr/challenge/login.asp")
rs = mechanize.urlopen(rq)
data = rs.read()
logged_in = r'input_login_check_value' in data
if logged_in:
print ' login success !'
rq = mechanize.Request("http://www.gmarket.co.kr")
rs = mechanize.urlopen(rq)
data = rs.read()
print data
else:
print 'login failed!'
pass
quit()
except:
pass
A:
mechanize doesn't have the ability to interact with JavaScript. Probably spidermonkey module will help you (I have no experience with it, but description is quite promising). Also you could handle such reload (e.g.Browser.reload() for this particular case) manually if it's the only site you have this problem.
Update:
Quick look through your page shows that you have submit to other URL (with https: scheme). Look through checkValid() JavaScript function. Posting to it gives other result. Note, that this looks like homework you should do yourself before asking.
|
mechanize can't login python
|
I'm making auto-login script by use mechanize python.
Before I was used mechanize with no problem, but www.gmarket.co.kr in this site I couldn't make it .
whenever i try to login always login page was returned even with correct gmarket id , pass, i can't login and I saw some suspicious message
"<script language=javascript>top.location.reload();</script>"
I think this related with my problem, but don't know exactly how to handle .
Here is sample id and pass for login test
id: tgi177 pass: tk1047
if anyone can help me much appreciate thanks in advance
CODE:
# -*- coding: cp949 -*-
from lxml.html import parse, fromstring
import sys,os
import mechanize, urllib
import cookielib
import re
from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag
try:
params = urllib.urlencode({'command':'login',
'url':'http%3A%2F%2Fwww.gmarket.co.kr%2F',
'member_type':'mem',
'member_yn':'Y',
'login_id':'tgi177',
'image1.x':'31',
'image1.y':'26',
'passwd':'tk1047',
'buyer_nm':'',
'buyer_tel_no1':'',
'buyer_tel_no2':'',
'buyer_tel_no3':''
})
rq = mechanize.Request("http://www.gmarket.co.kr/challenge/login.asp")
rs = mechanize.urlopen(rq)
data = rs.read()
logged_in = r'input_login_check_value' in data
if logged_in:
print ' login success !'
rq = mechanize.Request("http://www.gmarket.co.kr")
rs = mechanize.urlopen(rq)
data = rs.read()
print data
else:
print 'login failed!'
pass
quit()
except:
pass
|
[
"mechanize doesn't have the ability to interact with JavaScript. Probably spidermonkey module will help you (I have no experience with it, but description is quite promising). Also you could handle such reload (e.g.Browser.reload() for this particular case) manually if it's the only site you have this problem.\nUpdate:\nQuick look through your page shows that you have submit to other URL (with https: scheme). Look through checkValid() JavaScript function. Posting to it gives other result. Note, that this looks like homework you should do yourself before asking.\n"
] |
[
1
] |
[] |
[] |
[
"mechanize",
"python"
] |
stackoverflow_0001760245_mechanize_python.txt
|
Q:
Python SIP library
I need to write python application connect to trixbox that run as SIP server. But I not found any library that implement in python. I found SIP SKD at http://www.vaxvoip.com/ but it not support python. Can anyone suggest me an alternative to VaxVoip?
Thank you.
A:
There are Python bindings for the PJSUA API.
A:
Twisted supports SIP. That's really cool
A:
You might want to have a look at Sippy. It's a B2BUA with a complete SIP stack implementation underneath (you could use just that). It's written entirely in Python, so it's pretty hackable. Sippy is implemented with Twisted but uses none of its SIP functionality.
|
Python SIP library
|
I need to write python application connect to trixbox that run as SIP server. But I not found any library that implement in python. I found SIP SKD at http://www.vaxvoip.com/ but it not support python. Can anyone suggest me an alternative to VaxVoip?
Thank you.
|
[
"There are Python bindings for the PJSUA API.\n",
"Twisted supports SIP. That's really cool\n",
"You might want to have a look at Sippy. It's a B2BUA with a complete SIP stack implementation underneath (you could use just that). It's written entirely in Python, so it's pretty hackable. Sippy is implemented with Twisted but uses none of its SIP functionality.\n"
] |
[
19,
15,
10
] |
[] |
[] |
[
"python",
"sip",
"trixbox",
"voip"
] |
stackoverflow_0001286875_python_sip_trixbox_voip.txt
|
Q:
Detach a subprocess started using python multiprocessing module
I would like to create a process using the mutliprocessing module in python but ensure it continues running after the process that created the subprocess exits.
I can get the required functionality using the subprocess module and Popen, but I want to run my code as a function, not as a script. The reason I want to do this is to simplify creating pyro (python remote objects) objects. I want to start the pyro object request handler in a separate process using multiprocessing, but then I want the main process to exit while the process supporting the pyro object continues to run.
A:
I finally got what I wanted. I appreciate any suggestions to improve the code.
def start_server():
pyrodaemon = Pyro.core.Daemon()
#setup daemon and nameserver
#Don't want to close the pyro socket
#Need to remove SIGTERM map so Processing doesn't kill the subprocess
#Need to explicitly detach for some reason I don't understand
with daemon.DaemonContext(files_preserve=[pyrodaemon.sock],signal_map={signal.SIGTERM:None},detach_process=True):
while running:
pyrodaemon.handleRequests(timeout=1.0)
#when finished, clean up
pyrodaemon.shutdown()
def main():
p = Process(target=start_server)
p.daemon=True # Need to inform Process that this should run as a daemon
p.start()
time.sleep(3.0) # Important when running this program stand alone: Must wait long enough for start_server to get into the daemon context before the main program exits or Process will take down the subprocess before it detaches
do_other_stuff_not_in_the_daemon()
|
Detach a subprocess started using python multiprocessing module
|
I would like to create a process using the mutliprocessing module in python but ensure it continues running after the process that created the subprocess exits.
I can get the required functionality using the subprocess module and Popen, but I want to run my code as a function, not as a script. The reason I want to do this is to simplify creating pyro (python remote objects) objects. I want to start the pyro object request handler in a separate process using multiprocessing, but then I want the main process to exit while the process supporting the pyro object continues to run.
|
[
"I finally got what I wanted. I appreciate any suggestions to improve the code.\ndef start_server():\n pyrodaemon = Pyro.core.Daemon()\n #setup daemon and nameserver\n #Don't want to close the pyro socket\n #Need to remove SIGTERM map so Processing doesn't kill the subprocess\n #Need to explicitly detach for some reason I don't understand\n with daemon.DaemonContext(files_preserve=[pyrodaemon.sock],signal_map={signal.SIGTERM:None},detach_process=True):\n while running:\n pyrodaemon.handleRequests(timeout=1.0)\n #when finished, clean up\n pyrodaemon.shutdown()\n\ndef main():\n p = Process(target=start_server)\n p.daemon=True # Need to inform Process that this should run as a daemon\n p.start()\n time.sleep(3.0) # Important when running this program stand alone: Must wait long enough for start_server to get into the daemon context before the main program exits or Process will take down the subprocess before it detaches\n do_other_stuff_not_in_the_daemon()\n\n"
] |
[
4
] |
[] |
[] |
[
"detach",
"multiprocessing",
"pyro",
"python",
"subprocess"
] |
stackoverflow_0001757388_detach_multiprocessing_pyro_python_subprocess.txt
|
Q:
How to uncheck a checkbox to stop infinite drawing in pyqt?
My problem is I want to keep rotating the scene if the checkbox is checked, and stop this rotation immediately once it is unchecked. However, "keep rotating" means an infinite loop...
So after entering the loop, the program gets kind of freezed and no longer react to my "uncheck" signal. Is there a way to interrupt this loop? The following is skeleton of related code.
Thanks!
class Draw(QGLWidget):
def __init__(...):
...
self.rotate=0
self.auto=False
def paintGL(self):
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glRotatef(self.rotate,0.0,0.0,1.0)
draw stuff...
glFlush()
def autoRotate(self,auto): # auto is an integer and used here as true/false
self.auto=auto
while self.auto:
self.rotate+=0.5
if self.rotate>360:
self.rotate-=360
self.updateGL()
if auto==False:
break
class SpiralWidgetDemo(QtGui.QMainWindow):
def __init__(self):
...
auto=QtGui.QCheckBox("Auto")
self.connect(auto,QtCore.SIGNAL("stateChanged(int)"),widget.autoRotate)
A:
You must not implement this as a loop. This is defined to break the interaction of the program, as it prevents the "main loop" of the Qt application from running.
Put your drawing code into an event handler (like redraw event), and use a timer to generate events at regular intervals (e.g. 10/s).
|
How to uncheck a checkbox to stop infinite drawing in pyqt?
|
My problem is I want to keep rotating the scene if the checkbox is checked, and stop this rotation immediately once it is unchecked. However, "keep rotating" means an infinite loop...
So after entering the loop, the program gets kind of freezed and no longer react to my "uncheck" signal. Is there a way to interrupt this loop? The following is skeleton of related code.
Thanks!
class Draw(QGLWidget):
def __init__(...):
...
self.rotate=0
self.auto=False
def paintGL(self):
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glRotatef(self.rotate,0.0,0.0,1.0)
draw stuff...
glFlush()
def autoRotate(self,auto): # auto is an integer and used here as true/false
self.auto=auto
while self.auto:
self.rotate+=0.5
if self.rotate>360:
self.rotate-=360
self.updateGL()
if auto==False:
break
class SpiralWidgetDemo(QtGui.QMainWindow):
def __init__(self):
...
auto=QtGui.QCheckBox("Auto")
self.connect(auto,QtCore.SIGNAL("stateChanged(int)"),widget.autoRotate)
|
[
"You must not implement this as a loop. This is defined to break the interaction of the program, as it prevents the \"main loop\" of the Qt application from running.\nPut your drawing code into an event handler (like redraw event), and use a timer to generate events at regular intervals (e.g. 10/s).\n"
] |
[
1
] |
[] |
[] |
[
"pyopengl",
"pyqt",
"python"
] |
stackoverflow_0001761352_pyopengl_pyqt_python.txt
|
Q:
Read password from stdin
Scenario: An interactive CLI Python program, that is in need for a password. That means also, there's no GUI solution possible.
In bash I could get a password read in without re-prompting it on screen via
read -s
Is there something similar for Python? I.e.,
password = raw_input('Password: ', dont_print_statement_back_to_screen)
Alternative: Replace the typed characters with '*' before sending them back to screen (aka browser' style).
A:
>>> import getpass
>>> pw = getpass.getpass()
A:
Yes, getpass: "Prompt the user for a password without echoing."
Edit: I had not played with this module myself yet, so this is what I just cooked up (wouldn't be surprised if you find similar code all over the place, though):
import getpass
def login():
user = input("Username [%s]: " % getpass.getuser())
if not user:
user = getpass.getuser()
pprompt = lambda: (getpass.getpass(), getpass.getpass('Retype password: '))
p1, p2 = pprompt()
while p1 != p2:
print('Passwords do not match. Try again')
p1, p2 = pprompt()
return user, p1
(This is Python 3.x; use raw_input instead of input when using Python 2.x.)
|
Read password from stdin
|
Scenario: An interactive CLI Python program, that is in need for a password. That means also, there's no GUI solution possible.
In bash I could get a password read in without re-prompting it on screen via
read -s
Is there something similar for Python? I.e.,
password = raw_input('Password: ', dont_print_statement_back_to_screen)
Alternative: Replace the typed characters with '*' before sending them back to screen (aka browser' style).
|
[
">>> import getpass\n>>> pw = getpass.getpass()\n\n",
"Yes, getpass: \"Prompt the user for a password without echoing.\"\nEdit: I had not played with this module myself yet, so this is what I just cooked up (wouldn't be surprised if you find similar code all over the place, though):\nimport getpass\n\ndef login():\n user = input(\"Username [%s]: \" % getpass.getuser())\n if not user:\n user = getpass.getuser()\n\n pprompt = lambda: (getpass.getpass(), getpass.getpass('Retype password: '))\n\n p1, p2 = pprompt()\n while p1 != p2:\n print('Passwords do not match. Try again')\n p1, p2 = pprompt()\n\n return user, p1\n\n(This is Python 3.x; use raw_input instead of input when using Python 2.x.)\n"
] |
[
296,
55
] |
[] |
[] |
[
"interactive",
"passwords",
"prompt",
"python"
] |
stackoverflow_0001761744_interactive_passwords_prompt_python.txt
|
Q:
Numpy equivalent of MATLAB's cell array
I want to create a MATLAB-like cell array in Numpy. How can I accomplish this?
A:
Matlab cell arrays are most similar to Python lists, since they can hold any object - but scipy.io.loadmat imports them as numpy object arrays - which is an array with dtype=object.
To be honest though you are just as well off using Python lists - if you are holding general objects you will loose almost all of the advantages of numpy arrays (which are designed to hold a sequence of values which each take the same amount of memory).
|
Numpy equivalent of MATLAB's cell array
|
I want to create a MATLAB-like cell array in Numpy. How can I accomplish this?
|
[
"Matlab cell arrays are most similar to Python lists, since they can hold any object - but scipy.io.loadmat imports them as numpy object arrays - which is an array with dtype=object.\nTo be honest though you are just as well off using Python lists - if you are holding general objects you will loose almost all of the advantages of numpy arrays (which are designed to hold a sequence of values which each take the same amount of memory).\n"
] |
[
18
] |
[] |
[] |
[
"matlab",
"numpy",
"python"
] |
stackoverflow_0001761419_matlab_numpy_python.txt
|
Q:
How to convert text into URL syntax on Python?
I want to convert Python string to URL syntax.
For example
>>> u'한글'.encode('utf-8')
'\xed\x95\x9c\xea\xb8\x80' to '%ed%95%9c%ea%b8%80'
A:
>>> import urllib2
>>> urllib2.quote('한글')
'%ED%95%9C%EA%B8%80'
|
How to convert text into URL syntax on Python?
|
I want to convert Python string to URL syntax.
For example
>>> u'한글'.encode('utf-8')
'\xed\x95\x9c\xea\xb8\x80' to '%ed%95%9c%ea%b8%80'
|
[
">>> import urllib2\n>>> urllib2.quote('한글')\n'%ED%95%9C%EA%B8%80'\n\n"
] |
[
10
] |
[] |
[] |
[
"python",
"url"
] |
stackoverflow_0001762123_python_url.txt
|
Q:
Fastest way to search 1GB+ a string of data for the first occurrence of a pattern in Python
There's a 1 Gigabyte string of arbitrary data which you can assume to be equivalent to something like:
1_gb_string=os.urandom(1*gigabyte)
We will be searching this string, 1_gb_string, for an infinite number of fixed width, 1 kilobyte patterns, 1_kb_pattern. Every time we search the pattern will be different. So caching opportunities are not apparent. The same 1 gigabyte string will be searched over and over. Here is a simple generator to describe what's happening:
def findit(1_gb_string):
1_kb_pattern=get_next_pattern()
yield 1_gb_string.find(1_kb_pattern)
Note that only the first occurrence of the pattern needs to be found. After that, no other major processing should be done.
What can I use that's faster than python's bultin find for matching 1KB patterns against 1GB or greater data strings?
(I am already aware of how to split up the string and searching it in parallel, so you can disregard that basic optimization.)
Update: Please bound memory requirements to 16GB.
A:
As you clarify that long-ish preprocessing is acceptable, I'd suggest a variant of Rabin-Karp: "an algorithm of choice for multiple pattern search", as wikipedia puts it.
Define a "rolling hash" function, i.e., one such that, when you know the hash for haystack[x:x+N], computing the hash for haystack[x+1:x+N+1] is O(1). (Normal hashing functions such as Python's built-in hash do not have this property, which is why you have to write your own, otherwise the preprocessing becomes exhaustingly long rather than merely long-ish;-). A polynomial approach is fruitful, and you could use, say, 30-bit hash results (by masking if needed, i.e., you can do the computation w/more precision and just store the masked 30 bits of choice). Let's call this rolling hash function RH for clarity.
So, compute 1G of RH results as you roll along the haystack 1GB string; if you just stored these it would give you an array H of 1G 30-bit values (4GB) mapping index-in-haystack->RH value. But you want the reverse mapping, so use instead an array A of 2**30 entries (1G entries) that for each RH value gives you all the indices of interest in the haystack (indices at which that RH value occurs); for each entry you store the index of the first possibly-interesting haystack index into another array B of 1G indices into the haystack which is ordered to keep all indices into haystack with identical RH values ("collisions" in hashing terms) adjacent. H, A and B both have 1G entries of 4 bytes each, so 12GB total.
Now for each incoming 1K needle, compute its RH, call it k, and use it as an index into A; A[k] gives you the first index b into B at which it's worth comparing. So, do:
ib = A[k]
b = B[ib]
while b < len(haystack) - 1024:
if H[b] != k: return "not found"
if needle == haystack[b:b+1024]: return "found at", b
ib += 1
b = B[ib]
with a good RH you should have few collisions, so the while should execute very few times until returning one way or another. So each needle-search should be really really fast.
A:
There are a number of string matching algorithms use in the field of genetics to find substrings. You might try this paper or this paper
A:
Are you willing to spend a significant time preprocessing the string?
If you are, what you can do is build a list of n-grams with offsets.
Suppose your alphabet is hex bytes and you are using 1-grams.
Then for 00-ff, you can create a dictionary that looks like this(perlese, sorry)
$offset_list{00} = @array_of_offsets
$offset_list{01} = #...etc
where you walk down the string and build the @array_of_offsets from all points where bytes happen. You can do this for arbitrary n-grams.
This provides a "start point for search" that you can use to walk.
Of course, the downside is that you have to preprocess the string, so that's your tradeoff.
edit:
The basic idea here is to match prefixes. This may bomb out badly if the information is super-similar, but if it has a fair amount of divergence between n-grams, you should be able to match prefixes pretty well.
Let's quantify divergence, since you've not discussed the kind of info you're analyzing. For the purposes of this algorithm, we can characterize divergence as a distance function: you need a decently high Hamming distance. If the hamming distance between n-grams is, say, 1, the above idea won't work. But if it's n-1, the above algorithm will be much easier.
To improve on my algorithm, let's build an algorithm that does some successive elimination of possibilities:
We can invoke Shannon Entropy to define information of a given n-gram. Take your search string and successively build a prefix based upon the first m characters. When the entropy of the m-prefix is 'sufficiently high', use it later.
Define p to be an m-prefix of the search string
Search your 1 GB string and create an array of offsets that match p.
Extend the m-prefix to be some k-prefix, k > m, entropy of k-prefix higher than m-prefix.
Keep the elements offset array defined above, such that they match the k-prefix string. Discard the non-matching elements.
Goto 4 until the entire search string is met.
In a sense, this is like reversing Huffman encoding.
A:
As far as I know, standard find algorithm is naive algorithm with complexity about n*m comparisons, because
it checks patterns against every possible offset. There are some more effective algoithms, requiring about n+m comparisons.
If your string is not a natural language string, you can try
Knuth–Morris–Pratt algorithm . Boyer–Moore search algorithm is fast and simple enough too.
A:
With infinite memory, you can hash every 1k string along with its position in the 1 GB file.
With less than infinite memory, you will be bounded by how many memory pages you touch when searching.
A:
I don't know definitively if the find() method for strings is faster than the search() method provided by Python's re (regular expressions) module, but there's only one way to find out.
If you're just searching a string, what you want is this:
import re
def findit(1_gb_string):
yield re.search(1_kb_pattern, 1_gb_string)
However, if you really only want the first match, you might be better off using finditer(), which returns an iterator, and with such large operations might actually be better.
A:
http://www.youtube.com/watch?v=V5hZoJ6uK-s
Will be of most value to you. Its an MIT lecture on Dynamic Programming
A:
If the patterns are fairly random, you can precompute the location of n-prefixes of strings.
Instead of going over all options for n-prefixes, just use the actual ones in the 1GB string - there will be less than 1Gig of those. Use as big a prefix as fits in your memory, I don't have 16GB RAM to check but a prefix of 4 could work (at least in a memory-efficient data structures), if not try 3 or even 2.
For a random 1GB string and random 1KB patterns, you should get a few 10s of locations per prefix if you use 3-byte prefixes, but 4-byte prefixes should get you an average of 0 or 1 , so lookup should be fast.
Precompute Locations
def find_all(pattern, string):
cur_loc = 0
while True:
next_loc = string.find(pattern, cur_loc)
if next_loc < 0: return
yield next_loc
cur_loc = next_loc+1
big_string = ...
CHUNK_SIZE = 1024
PREFIX_SIZE = 4
precomputed_indices = {}
for i in xrange(len(big_string)-CHUNK_SIZE):
prefix = big_string[i:i+PREFIX_SIZE]
if prefix not in precomputed_indices:
precomputed_indices[prefix] = tuple(find_all(prefix, big_string))
Look up a pattern
def find_pattern(pattern):
prefix = pattern[:PREFIX_SIZE]
# optimization - big prefixes will result in many misses
if prefix not in precomputed_indices:
return -1
for loc in precomputed_indices[prefix]:
if big_string[loc:loc+CHUNK_SIZE] == pattern:
return loc
return -1
A:
Someone hinted at a possible way to index this thing if you have abundant RAM (or possibly even disk/swap) available.
Imagine if you performed a simple 32-bit CRC on a 1K block extending from each character in the original Gig string. This would result in 4bytes of checksum data for each byte offset from the beginning of the data.
By itself this might give a modest improvement in search speed. The checksum of each 1K search target could be checked against each CRC ... which each collision tested for a true match. That should still be a couple orders of magnitude faster than a normal linear search.
That, obviously, costs us 4GB of RAM for he CRC array (plus the original Gig for the original data and a little more overhead for the environment and our program).
If we have ~16GB we could sort the checksums and store a list of offsets where each is found. That becomes an indexed search (average of about 16 probes per target search ... worst case around 32 or 33 (might be a fence post there).
It's possible that a 16BG file index would still give better performance than a linear checksum search and it would almost certainly be better than a linear raw search (unless you have extremely slow filesystems/storage).
(Adding): I should clarify that this strategy is only beneficial given that you've described a need to do many searches on the same one gigabyte data blob.
You might use a threaded approach to building the index (while reading it as well as having multiple threads performing the checksumming). You might also offload the indexing into separate processes or a cluster of nodes (particularly if you use a file-based index --- the ~16GB option described above). With a simple 32-bit CRC you might be able to perform the checksums/indexing as fast as your reader thread can get the data (but we are talking about 1024 checksums for each 1K of data so perhaps not).
You might further improve performance by coding a Python module in C for actually performing the search ... and/or possibly for performing the checksumming/indexing.
The development and testing of such C extensions entail other trade-offs, obviously enough. It sounds like this would have near zero re-usability.
A:
One efficient but complex way is full-text indexing with the Burrows-Wheeler transform. It involves performing a BWT on your source text, then using a small index on that to quickly find any substring in the text that matches your input pattern.
The time complexity of this algorithm is roughly O(n) with the length of the string you're matching - and independent of the length of the input string! Further, the size of the index is not much larger than the input data, and with compression can even be reduced below the size of the source text.
|
Fastest way to search 1GB+ a string of data for the first occurrence of a pattern in Python
|
There's a 1 Gigabyte string of arbitrary data which you can assume to be equivalent to something like:
1_gb_string=os.urandom(1*gigabyte)
We will be searching this string, 1_gb_string, for an infinite number of fixed width, 1 kilobyte patterns, 1_kb_pattern. Every time we search the pattern will be different. So caching opportunities are not apparent. The same 1 gigabyte string will be searched over and over. Here is a simple generator to describe what's happening:
def findit(1_gb_string):
1_kb_pattern=get_next_pattern()
yield 1_gb_string.find(1_kb_pattern)
Note that only the first occurrence of the pattern needs to be found. After that, no other major processing should be done.
What can I use that's faster than python's bultin find for matching 1KB patterns against 1GB or greater data strings?
(I am already aware of how to split up the string and searching it in parallel, so you can disregard that basic optimization.)
Update: Please bound memory requirements to 16GB.
|
[
"As you clarify that long-ish preprocessing is acceptable, I'd suggest a variant of Rabin-Karp: \"an algorithm of choice for multiple pattern search\", as wikipedia puts it.\nDefine a \"rolling hash\" function, i.e., one such that, when you know the hash for haystack[x:x+N], computing the hash for haystack[x+1:x+N+1] is O(1). (Normal hashing functions such as Python's built-in hash do not have this property, which is why you have to write your own, otherwise the preprocessing becomes exhaustingly long rather than merely long-ish;-). A polynomial approach is fruitful, and you could use, say, 30-bit hash results (by masking if needed, i.e., you can do the computation w/more precision and just store the masked 30 bits of choice). Let's call this rolling hash function RH for clarity.\nSo, compute 1G of RH results as you roll along the haystack 1GB string; if you just stored these it would give you an array H of 1G 30-bit values (4GB) mapping index-in-haystack->RH value. But you want the reverse mapping, so use instead an array A of 2**30 entries (1G entries) that for each RH value gives you all the indices of interest in the haystack (indices at which that RH value occurs); for each entry you store the index of the first possibly-interesting haystack index into another array B of 1G indices into the haystack which is ordered to keep all indices into haystack with identical RH values (\"collisions\" in hashing terms) adjacent. H, A and B both have 1G entries of 4 bytes each, so 12GB total.\nNow for each incoming 1K needle, compute its RH, call it k, and use it as an index into A; A[k] gives you the first index b into B at which it's worth comparing. So, do:\nib = A[k]\nb = B[ib]\nwhile b < len(haystack) - 1024:\n if H[b] != k: return \"not found\"\n if needle == haystack[b:b+1024]: return \"found at\", b\n ib += 1\n b = B[ib]\n\nwith a good RH you should have few collisions, so the while should execute very few times until returning one way or another. So each needle-search should be really really fast.\n",
"There are a number of string matching algorithms use in the field of genetics to find substrings. You might try this paper or this paper\n",
"Are you willing to spend a significant time preprocessing the string?\nIf you are, what you can do is build a list of n-grams with offsets.\nSuppose your alphabet is hex bytes and you are using 1-grams. \nThen for 00-ff, you can create a dictionary that looks like this(perlese, sorry)\n$offset_list{00} = @array_of_offsets\n$offset_list{01} = #...etc\n\nwhere you walk down the string and build the @array_of_offsets from all points where bytes happen. You can do this for arbitrary n-grams. \nThis provides a \"start point for search\" that you can use to walk. \nOf course, the downside is that you have to preprocess the string, so that's your tradeoff.\nedit:\n\nThe basic idea here is to match prefixes. This may bomb out badly if the information is super-similar, but if it has a fair amount of divergence between n-grams, you should be able to match prefixes pretty well.\nLet's quantify divergence, since you've not discussed the kind of info you're analyzing. For the purposes of this algorithm, we can characterize divergence as a distance function: you need a decently high Hamming distance. If the hamming distance between n-grams is, say, 1, the above idea won't work. But if it's n-1, the above algorithm will be much easier.\nTo improve on my algorithm, let's build an algorithm that does some successive elimination of possibilities:\nWe can invoke Shannon Entropy to define information of a given n-gram. Take your search string and successively build a prefix based upon the first m characters. When the entropy of the m-prefix is 'sufficiently high', use it later.\n\nDefine p to be an m-prefix of the search string\nSearch your 1 GB string and create an array of offsets that match p.\nExtend the m-prefix to be some k-prefix, k > m, entropy of k-prefix higher than m-prefix.\nKeep the elements offset array defined above, such that they match the k-prefix string. Discard the non-matching elements.\nGoto 4 until the entire search string is met. \n\nIn a sense, this is like reversing Huffman encoding.\n",
"As far as I know, standard find algorithm is naive algorithm with complexity about n*m comparisons, because\nit checks patterns against every possible offset. There are some more effective algoithms, requiring about n+m comparisons.\nIf your string is not a natural language string, you can try \nKnuth–Morris–Pratt algorithm . Boyer–Moore search algorithm is fast and simple enough too.\n",
"With infinite memory, you can hash every 1k string along with its position in the 1 GB file.\nWith less than infinite memory, you will be bounded by how many memory pages you touch when searching.\n",
"I don't know definitively if the find() method for strings is faster than the search() method provided by Python's re (regular expressions) module, but there's only one way to find out.\nIf you're just searching a string, what you want is this:\nimport re\ndef findit(1_gb_string):\n yield re.search(1_kb_pattern, 1_gb_string)\n\nHowever, if you really only want the first match, you might be better off using finditer(), which returns an iterator, and with such large operations might actually be better.\n",
"http://www.youtube.com/watch?v=V5hZoJ6uK-s\nWill be of most value to you. Its an MIT lecture on Dynamic Programming\n",
"If the patterns are fairly random, you can precompute the location of n-prefixes of strings.\nInstead of going over all options for n-prefixes, just use the actual ones in the 1GB string - there will be less than 1Gig of those. Use as big a prefix as fits in your memory, I don't have 16GB RAM to check but a prefix of 4 could work (at least in a memory-efficient data structures), if not try 3 or even 2.\nFor a random 1GB string and random 1KB patterns, you should get a few 10s of locations per prefix if you use 3-byte prefixes, but 4-byte prefixes should get you an average of 0 or 1 , so lookup should be fast.\nPrecompute Locations\ndef find_all(pattern, string):\n cur_loc = 0\n while True:\n next_loc = string.find(pattern, cur_loc)\n if next_loc < 0: return\n yield next_loc\n cur_loc = next_loc+1\n\nbig_string = ...\nCHUNK_SIZE = 1024\nPREFIX_SIZE = 4\nprecomputed_indices = {}\nfor i in xrange(len(big_string)-CHUNK_SIZE):\n prefix = big_string[i:i+PREFIX_SIZE]\n if prefix not in precomputed_indices:\n precomputed_indices[prefix] = tuple(find_all(prefix, big_string))\n\nLook up a pattern\ndef find_pattern(pattern):\n prefix = pattern[:PREFIX_SIZE]\n # optimization - big prefixes will result in many misses\n if prefix not in precomputed_indices:\n return -1\n for loc in precomputed_indices[prefix]:\n if big_string[loc:loc+CHUNK_SIZE] == pattern:\n return loc\n return -1\n\n",
"Someone hinted at a possible way to index this thing if you have abundant RAM (or possibly even disk/swap) available.\nImagine if you performed a simple 32-bit CRC on a 1K block extending from each character in the original Gig string. This would result in 4bytes of checksum data for each byte offset from the beginning of the data.\nBy itself this might give a modest improvement in search speed. The checksum of each 1K search target could be checked against each CRC ... which each collision tested for a true match. That should still be a couple orders of magnitude faster than a normal linear search.\nThat, obviously, costs us 4GB of RAM for he CRC array (plus the original Gig for the original data and a little more overhead for the environment and our program).\nIf we have ~16GB we could sort the checksums and store a list of offsets where each is found. That becomes an indexed search (average of about 16 probes per target search ... worst case around 32 or 33 (might be a fence post there).\nIt's possible that a 16BG file index would still give better performance than a linear checksum search and it would almost certainly be better than a linear raw search (unless you have extremely slow filesystems/storage).\n(Adding): I should clarify that this strategy is only beneficial given that you've described a need to do many searches on the same one gigabyte data blob.\nYou might use a threaded approach to building the index (while reading it as well as having multiple threads performing the checksumming). You might also offload the indexing into separate processes or a cluster of nodes (particularly if you use a file-based index --- the ~16GB option described above). With a simple 32-bit CRC you might be able to perform the checksums/indexing as fast as your reader thread can get the data (but we are talking about 1024 checksums for each 1K of data so perhaps not).\nYou might further improve performance by coding a Python module in C for actually performing the search ... and/or possibly for performing the checksumming/indexing.\nThe development and testing of such C extensions entail other trade-offs, obviously enough. It sounds like this would have near zero re-usability.\n",
"One efficient but complex way is full-text indexing with the Burrows-Wheeler transform. It involves performing a BWT on your source text, then using a small index on that to quickly find any substring in the text that matches your input pattern.\nThe time complexity of this algorithm is roughly O(n) with the length of the string you're matching - and independent of the length of the input string! Further, the size of the index is not much larger than the input data, and with compression can even be reduced below the size of the source text.\n"
] |
[
12,
5,
1,
1,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"large_data_volumes",
"python",
"search"
] |
stackoverflow_0001750343_algorithm_large_data_volumes_python_search.txt
|
Q:
How to integrate Disqus to Facebook Connect-enabled site (python Tornado app)
I succesfully use Facebook auth for my Tornado-based site using FacebookMixin. I also have Facebook Connect auth enabled for my Disqus, which placed in page using javascript widget. When user already logged in using FB to my site, they still have to log to FB again when they want to comment using Disqus.
How Discus FB Connect suppose to works? I assumed i got seamless FB auth between those two (FacebookMixin/Disqus)
A:
how did you integrate disqus into your site? are you using their api in your backend?
If I understand disqus correctly then you would need to post to their service usign the data of the authenticated users, else (if they use the javascript widget) they would need to establish a fb connect session with disqus which might be a confusing experience.
|
How to integrate Disqus to Facebook Connect-enabled site (python Tornado app)
|
I succesfully use Facebook auth for my Tornado-based site using FacebookMixin. I also have Facebook Connect auth enabled for my Disqus, which placed in page using javascript widget. When user already logged in using FB to my site, they still have to log to FB again when they want to comment using Disqus.
How Discus FB Connect suppose to works? I assumed i got seamless FB auth between those two (FacebookMixin/Disqus)
|
[
"how did you integrate disqus into your site? are you using their api in your backend?\nIf I understand disqus correctly then you would need to post to their service usign the data of the authenticated users, else (if they use the javascript widget) they would need to establish a fb connect session with disqus which might be a confusing experience.\n"
] |
[
0
] |
[] |
[] |
[
"disqus",
"python",
"tornado"
] |
stackoverflow_0001762268_disqus_python_tornado.txt
|
Q:
Adding Lists Elements to 'Mega List'
Let's say I have a list somewhere called majorPowers which contain these two lists:
axis=["germany","italy","japan"]
allies=["russia","uk","us"]
I'd like to insert each of the elements of these lists, into a new mega-list. I'm currently doing this:
>>> temp = []
>>> temp = [ww2.append(t) for t in majorPowers]
>>>ww2
[['germany','italy','japan'],['russia','uk','us']]
How do I adjust this to not use the temp and to insert the individual elements into ww2 instead of the lists themselves(axis and allied).
Also, would the new mega-list itself be classed as a comprehensive list, or the process of making it?
EDIT:
Please note I do not want to do:
for a in list1:
for b in a:
c.append(b)
@S.Lott. I understand your point. However I'm trying to learn some of the tricks in Python, instead of the standard way I'd usually do things. This is just to open my mind to Python a little more!
A:
It is good that you ask this question, because it is bad form to misuse list
comprehensions like that. The code you show uses append, not to generate the
elements of temp, but because of its side effects. Avoid side effects in list
comprehensions!
So, there are a couple of things you can do. First, you can use
itertools.chain:
>>> from itertools import chain
>>> list(chain(*mayorPowers))
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
Instead of passing the elements of mayorPowers as individual arguments to chain, you can also use itertools.chain.from_iterable:
>>> list(chain.from_iterable(mayorPowers))
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
Or you can use extend:
>>> ww2 = []
>>> for mp in mayorPowers:
... ww2.extend(mp)
...
>>> ww2
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
Or sum (I like this one most, I suppose):
>>> sum(mayorPowers, [])
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
Or, to be a little crazy (uses functools.reduce and operator.add),
>>> from functools import reduce
>>> from operator import add
>>> reduce(add, mayorPowers)
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
A:
from itertools import chain
ww2 = list(chain.from_iterable(majorPower))
A:
try extend
for t in majorPowers: ww2.extend(t)
or
sum(majorPowers,[])
A:
I would use reduce:
from operator import add
ww2 = reduce(add, majorPowers)
|
Adding Lists Elements to 'Mega List'
|
Let's say I have a list somewhere called majorPowers which contain these two lists:
axis=["germany","italy","japan"]
allies=["russia","uk","us"]
I'd like to insert each of the elements of these lists, into a new mega-list. I'm currently doing this:
>>> temp = []
>>> temp = [ww2.append(t) for t in majorPowers]
>>>ww2
[['germany','italy','japan'],['russia','uk','us']]
How do I adjust this to not use the temp and to insert the individual elements into ww2 instead of the lists themselves(axis and allied).
Also, would the new mega-list itself be classed as a comprehensive list, or the process of making it?
EDIT:
Please note I do not want to do:
for a in list1:
for b in a:
c.append(b)
@S.Lott. I understand your point. However I'm trying to learn some of the tricks in Python, instead of the standard way I'd usually do things. This is just to open my mind to Python a little more!
|
[
"It is good that you ask this question, because it is bad form to misuse list\ncomprehensions like that. The code you show uses append, not to generate the\nelements of temp, but because of its side effects. Avoid side effects in list\ncomprehensions!\nSo, there are a couple of things you can do. First, you can use\nitertools.chain:\n>>> from itertools import chain\n>>> list(chain(*mayorPowers))\n['germany', 'italy', 'japan', 'russia', 'uk', 'us']\n\nInstead of passing the elements of mayorPowers as individual arguments to chain, you can also use itertools.chain.from_iterable:\n>>> list(chain.from_iterable(mayorPowers))\n['germany', 'italy', 'japan', 'russia', 'uk', 'us']\n\nOr you can use extend:\n>>> ww2 = []\n>>> for mp in mayorPowers:\n... ww2.extend(mp)\n...\n>>> ww2\n['germany', 'italy', 'japan', 'russia', 'uk', 'us']\n\nOr sum (I like this one most, I suppose):\n>>> sum(mayorPowers, [])\n['germany', 'italy', 'japan', 'russia', 'uk', 'us']\n\nOr, to be a little crazy (uses functools.reduce and operator.add),\n>>> from functools import reduce\n>>> from operator import add\n>>> reduce(add, mayorPowers)\n['germany', 'italy', 'japan', 'russia', 'uk', 'us']\n\n",
"from itertools import chain\nww2 = list(chain.from_iterable(majorPower))\n\n",
"try extend\nfor t in majorPowers: ww2.extend(t)\n\nor \nsum(majorPowers,[])\n\n",
"I would use reduce:\nfrom operator import add\nww2 = reduce(add, majorPowers)\n\n"
] |
[
5,
1,
0,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001762446_list_python.txt
|
Q:
UnicodeDecodeError when using socket.gethostname() result
Some of my users report that the following code may raise a UnicodeDecodeError when the hostname contains non-ascii characters (however I haven't been able to replicate this on my Windows Vista machine):
self.path = path
self.lock_file = os.path.abspath(path) + ".lock"
self.hostname = socket.gethostname()
self.pid = os.getpid()
dirname = os.path.dirname(self.lock_file)
self.unique_name = os.path.join(dirname, "%s.%s" % (self.hostname, self.pid))
The last part of the traceback is:
File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 537, in FileLock
File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 296, in __init__
File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 175, in __init__
File "ntpath.pyo", line 102, in join
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 7: ordinal not in range(128)
Any ideas on why and how to prevent it?
(The exception occurs with Python 2.5 on Windows XP)
A:
I don't think gethostname() is necessarily giving you a unicode object. It could be the directory name of lockfile. Regardless, one of them is a standard string with a non-ASCII (higher than 127) char in it and the other is a unicode string.
The problem is that the join function in the ntpath module (the module Python uses for os.path on Windows) attempts join the arguments given. This causes Python to try to convert the normal string parts to unicode. In your case the non-unicode string appears to have a non-ASCII character. This can't be reliably converted to unicode, so Python raises the exception.
A simpler way to trigger the problem:
>> from ntpath import join
>> join(u'abc', '\xff')
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
/home/msmits/<ipython console> in <module>()
/usr/lib64/python2.6/ntpath.pyc in join(a, *p)
106 path += b
107 else:
--> 108 path += "\\" + b
109 else:
110 # path is not empty and does not end with a backslash,
The traceback shows the problem line in ntpath.py.
You could work around this by using converting the args to join() to standard strings first as other answers suggest. Alternatively you could convert everything to unicode first. If a specific encoding is given to decode() high bytes can be converted to unicode.
For example:
>> '\xff'.decode('latin-1')
u'\xff'
A:
Yes, if either the hostname or the dirname is a unicode string, it is likely to give you that error. The best solution is typically to make sure both are unicode, and not just one of them.
A:
You want a unique string based on the hostname, but it's got Unicode characters in it. There are a variety of ways to reduce a Unicode string to an ascii string, depending on how you want to deal with non-ascii characters. Here's one:
self.hostname = socket.gethostname().encode('ascii', 'replace').replace('?', '_')
This will replace all non-ascii characters with a question mark, then change those to underscore (since file systems don't like questions marks in file names).
A:
I don't think that there is a problem with the actual code that you've posted, even if socket.gethostname() returns a unicode object. There will be a problem when you attempt to use name such that it is converted to a string first:
import os
hostname = u'\u1306blah'
pid = os.getpid()
name = os.path.join(os.path.dirname('/tmp/blah.lock'), "%s.%s" % (hostname, pid))
>>> type(name)
<type 'unicode'>
>>> name
u'/tmp/\u1306blah.28292'
>>> print name
/tmp/ጆblah.29032
>>> str(name)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u1306' in position 5: ordinal not in range(128)
You can see that str(name) raises the exception that you're seeing, but everything looks OK up until that point. What are you doing with name once you've constructed it?
|
UnicodeDecodeError when using socket.gethostname() result
|
Some of my users report that the following code may raise a UnicodeDecodeError when the hostname contains non-ascii characters (however I haven't been able to replicate this on my Windows Vista machine):
self.path = path
self.lock_file = os.path.abspath(path) + ".lock"
self.hostname = socket.gethostname()
self.pid = os.getpid()
dirname = os.path.dirname(self.lock_file)
self.unique_name = os.path.join(dirname, "%s.%s" % (self.hostname, self.pid))
The last part of the traceback is:
File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 537, in FileLock
File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 296, in __init__
File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 175, in __init__
File "ntpath.pyo", line 102, in join
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 7: ordinal not in range(128)
Any ideas on why and how to prevent it?
(The exception occurs with Python 2.5 on Windows XP)
|
[
"I don't think gethostname() is necessarily giving you a unicode object. It could be the directory name of lockfile. Regardless, one of them is a standard string with a non-ASCII (higher than 127) char in it and the other is a unicode string.\nThe problem is that the join function in the ntpath module (the module Python uses for os.path on Windows) attempts join the arguments given. This causes Python to try to convert the normal string parts to unicode. In your case the non-unicode string appears to have a non-ASCII character. This can't be reliably converted to unicode, so Python raises the exception.\nA simpler way to trigger the problem:\n>> from ntpath import join\n>> join(u'abc', '\\xff')\n---------------------------------------------------------------------------\nUnicodeDecodeError Traceback (most recent call last)\n\n/home/msmits/<ipython console> in <module>()\n\n/usr/lib64/python2.6/ntpath.pyc in join(a, *p)\n 106 path += b\n 107 else:\n--> 108 path += \"\\\\\" + b\n 109 else:\n 110 # path is not empty and does not end with a backslash,\n\nThe traceback shows the problem line in ntpath.py.\nYou could work around this by using converting the args to join() to standard strings first as other answers suggest. Alternatively you could convert everything to unicode first. If a specific encoding is given to decode() high bytes can be converted to unicode.\nFor example:\n>> '\\xff'.decode('latin-1')\nu'\\xff'\n\n",
"Yes, if either the hostname or the dirname is a unicode string, it is likely to give you that error. The best solution is typically to make sure both are unicode, and not just one of them.\n",
"You want a unique string based on the hostname, but it's got Unicode characters in it. There are a variety of ways to reduce a Unicode string to an ascii string, depending on how you want to deal with non-ascii characters. Here's one:\nself.hostname = socket.gethostname().encode('ascii', 'replace').replace('?', '_')\n\nThis will replace all non-ascii characters with a question mark, then change those to underscore (since file systems don't like questions marks in file names).\n",
"I don't think that there is a problem with the actual code that you've posted, even if socket.gethostname() returns a unicode object. There will be a problem when you attempt to use name such that it is converted to a string first:\nimport os\nhostname = u'\\u1306blah'\npid = os.getpid()\nname = os.path.join(os.path.dirname('/tmp/blah.lock'), \"%s.%s\" % (hostname, pid))\n\n>>> type(name)\n<type 'unicode'>\n\n>>> name\nu'/tmp/\\u1306blah.28292'\n\n>>> print name\n/tmp/ጆblah.29032\n\n>>> str(name)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\u1306' in position 5: ordinal not in range(128)\n\nYou can see that str(name) raises the exception that you're seeing, but everything looks OK up until that point. What are you doing with name once you've constructed it?\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0001290601_python_unicode.txt
|
Q:
Why is it when I print something, there is always a unicode next to it? (Python)
[u'Iphones', u'dont', u'receieve', u'messages']
Is there a way to print it without the "u" in front of it?
A:
What you are seeing is the __repr__() representation of the unicode string which includes the u to make it clear. If you don't want the u you could print the object (using __str__) - this works for me:
print [str(x) for x in l]
Probably better is to read up on python unicode and encode using the particular unicode codec you want:
print [x.encode() for x in l]
[edit]: to clarify repr and why the u is there - the goal of repr is to provide a convenient string representation, "to return a string that would yield an object with the same value when passed to eval()". Ie you can copy and paste the printed output and get the same object (list of unicode strings).
A:
Python contains string classes for both unicode strings and regular strings. The u before a string indicates that it is a unicode string.
>>> mystrings = [u'Iphones', u'dont', u'receieve', u'messages']
>>> [str(s) for s in mystrings]
['Iphones', 'dont', 'receieve', 'messages']
>>> type(u'Iphones')
<type 'unicode'>
>>> type('Iphones')
<type 'str'>
See http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange for more information about the string types available in Python.
|
Why is it when I print something, there is always a unicode next to it? (Python)
|
[u'Iphones', u'dont', u'receieve', u'messages']
Is there a way to print it without the "u" in front of it?
|
[
"What you are seeing is the __repr__() representation of the unicode string which includes the u to make it clear. If you don't want the u you could print the object (using __str__) - this works for me:\nprint [str(x) for x in l]\n\nProbably better is to read up on python unicode and encode using the particular unicode codec you want:\nprint [x.encode() for x in l]\n\n[edit]: to clarify repr and why the u is there - the goal of repr is to provide a convenient string representation, \"to return a string that would yield an object with the same value when passed to eval()\". Ie you can copy and paste the printed output and get the same object (list of unicode strings).\n",
"Python contains string classes for both unicode strings and regular strings. The u before a string indicates that it is a unicode string.\n>>> mystrings = [u'Iphones', u'dont', u'receieve', u'messages']\n>>> [str(s) for s in mystrings]\n['Iphones', 'dont', 'receieve', 'messages']\n>>> type(u'Iphones')\n<type 'unicode'>\n>>> type('Iphones')\n<type 'str'>\n\nSee http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange for more information about the string types available in Python.\n"
] |
[
9,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001762690_python.txt
|
Q:
Pyinstaller ld-linux-x86-64.so.2 linking problem
I'm trying to deploy my Python based application on another Linux host. Pyinstaller works flawlessly as long as I run the generated executable on my own system.
On the target box I get this error message:
/lib/ld-linux-x86-64.so.2: bad ELF
interpreter: No such file or directory
As the output of ldd shows Pyinstaller links my application against /lib/ld-linux-x86-64.so.2 which is only available at /lib64/ld-linux-x86-64.so.2 on the target system (where I only have basic user privileges, so symlinking the file is not an option).
How can I modify my executable to look for the library in /lib64/ instead of /lib/ ?
A:
This is not really a Python question, but a UNIX/Linux compile and link question.
First of all, are you using the latest Pyinstaller. If not, then try that. If you still have the problem, then please report the bug to the Pyinstaller developers here.
Try to workaround your problem by using LD_LIBRARY_PATH to point to the correct directory. For more info read this article
|
Pyinstaller ld-linux-x86-64.so.2 linking problem
|
I'm trying to deploy my Python based application on another Linux host. Pyinstaller works flawlessly as long as I run the generated executable on my own system.
On the target box I get this error message:
/lib/ld-linux-x86-64.so.2: bad ELF
interpreter: No such file or directory
As the output of ldd shows Pyinstaller links my application against /lib/ld-linux-x86-64.so.2 which is only available at /lib64/ld-linux-x86-64.so.2 on the target system (where I only have basic user privileges, so symlinking the file is not an option).
How can I modify my executable to look for the library in /lib64/ instead of /lib/ ?
|
[
"This is not really a Python question, but a UNIX/Linux compile and link question.\nFirst of all, are you using the latest Pyinstaller. If not, then try that. If you still have the problem, then please report the bug to the Pyinstaller developers here.\nTry to workaround your problem by using LD_LIBRARY_PATH to point to the correct directory. For more info read this article\n"
] |
[
1
] |
[] |
[] |
[
"deployment",
"dll",
"linux",
"pyinstaller",
"python"
] |
stackoverflow_0001761140_deployment_dll_linux_pyinstaller_python.txt
|
Q:
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
Apparently libigraph and python-igraph are the only packages on earth that can't be installed via apt-get or easy_install under Ubuntu 8.04 LTS 64-bit.
Installing both from source from source on seems to go smoothly...until I try to use them.
When I run python I get:
>>> import igraph
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "igraph/__init__.py", line 30, in <module>
from igraph.core import *
ImportError: No module named core
or (if I use the easy_install version of python-igraph)
>>> import igraph
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 30, in <module>
File "build/bdist.linux-x86_64/egg/igraph/core.py", line 7, in <module>
File "build/bdist.linux-x86_64/egg/igraph/core.py", line 6, in __bootstrap__
ImportError: libigraph.so.0: cannot open shared object file: No such file or directory
I grabbed the source from here
igraph 0.5.2 = http://igraph.sourceforge.net/download.html
python-igraph 0.5.2 = http://pypi.python.org/pypi/python-igraph/0.5.2
Can anybody point me in the right direction?
A:
How did you compile? Did you do a make install (if there was any).
As for the 'library not found' error in the easy_install version, i'd try the following:
'sudo updatedb' (to update the locate database)
'locate libigraph.so.0' (to find where this file is on your system. If you did a make install it could have went to /usr/local/lib ... or is it in the python lib dir?)
Find out if the directory where this file is in is missing from your current LD_LIBRARY_PATH ('echo $LD_LIBRARY_PATH').
If this directory is not in here, add it try 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/yourdirhere' (make it permanent by adding it to /etc/ld.so.conf) / 'ldconfig -n /yourdirhere'
A:
Note that there are official Ubuntu packages for igraph available from Launchpad as of 8 Nov 2009. See the corresponding page on Launchpad for instructions. Unlike the earlier Debian package repository, this should work on both 32-bit and 64-bit architectures.
A:
Where is libigraph.so.0 ? It doesn't seem to be in a location that python looks for such as /usr/lib , /usr/local/lib etc.
A:
I followed the steps in http://socialsynergyweb.org/network/blog/install-python-igraph-ubuntu-904-64-bit. Also to run the actual igraph , i used the script python-igraph-0.5.2/scripts/igraph. Now i am able to use the igraph . If I dont use the scripts/igraph script i get the same error you are getting.
|
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
|
Apparently libigraph and python-igraph are the only packages on earth that can't be installed via apt-get or easy_install under Ubuntu 8.04 LTS 64-bit.
Installing both from source from source on seems to go smoothly...until I try to use them.
When I run python I get:
>>> import igraph
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "igraph/__init__.py", line 30, in <module>
from igraph.core import *
ImportError: No module named core
or (if I use the easy_install version of python-igraph)
>>> import igraph
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 30, in <module>
File "build/bdist.linux-x86_64/egg/igraph/core.py", line 7, in <module>
File "build/bdist.linux-x86_64/egg/igraph/core.py", line 6, in __bootstrap__
ImportError: libigraph.so.0: cannot open shared object file: No such file or directory
I grabbed the source from here
igraph 0.5.2 = http://igraph.sourceforge.net/download.html
python-igraph 0.5.2 = http://pypi.python.org/pypi/python-igraph/0.5.2
Can anybody point me in the right direction?
|
[
"How did you compile? Did you do a make install (if there was any).\nAs for the 'library not found' error in the easy_install version, i'd try the following:\n\n'sudo updatedb' (to update the locate database)\n'locate libigraph.so.0' (to find where this file is on your system. If you did a make install it could have went to /usr/local/lib ... or is it in the python lib dir?)\nFind out if the directory where this file is in is missing from your current LD_LIBRARY_PATH ('echo $LD_LIBRARY_PATH').\nIf this directory is not in here, add it try 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/yourdirhere' (make it permanent by adding it to /etc/ld.so.conf) / 'ldconfig -n /yourdirhere'\n\n",
"Note that there are official Ubuntu packages for igraph available from Launchpad as of 8 Nov 2009. See the corresponding page on Launchpad for instructions. Unlike the earlier Debian package repository, this should work on both 32-bit and 64-bit architectures.\n",
"Where is libigraph.so.0 ? It doesn't seem to be in a location that python looks for such as /usr/lib , /usr/local/lib etc.\n",
"I followed the steps in http://socialsynergyweb.org/network/blog/install-python-igraph-ubuntu-904-64-bit. Also to run the actual igraph , i used the script python-igraph-0.5.2/scripts/igraph. Now i am able to use the igraph . If I dont use the scripts/igraph script i get the same error you are getting.\n"
] |
[
11,
2,
0,
0
] |
[] |
[] |
[
"64_bit",
"igraph",
"python",
"ubuntu_8.04"
] |
stackoverflow_0000834076_64_bit_igraph_python_ubuntu_8.04.txt
|
Q:
Create broken symlink with Python
Using Python I want to create a symbolic link pointing to a path that does not exist. However os.symlink just complains about "OSError: [Errno 2] No such file or directory:".. This can easily be done with the ln program, but how to do it in Python without calling the ln program from Python?
Edit: somehow I really messed this up :/ ... both answers below is correct
A:
Such error is raised when you try to create a symlink in non-existent directory. For example, the following code will fail if /tmp/subdir doesn't exist:
os.symlink('/usr/bin/python', '/tmp/subdir/python')
But this should run successfully:
src = '/usr/bin/python'
dst = '/tmp/subdir/python'
if not os.path.isdir(os.path.dirname(dst)):
os.makedirs(os.path.dirname(dst))
os.symlink(src, dst)
A:
The file doesn't need to exist in order to create the symlink. The following example demonstrates creating a symlink to a non-existing file:
First, check that there's no file named foobar in /home/wieslander/tmp:
[wieslander@rizzo tmp]$ ls -l /home/wieslander/tmp/foobar
ls: cannot access /home/wieslander/tmp/foobar: No such file or directory
Create a symlink named brokensymlink pointing to /home/wieslander/tmp/foobar:
[wieslander@rizzo tmp]$ python
Python 2.5.2 (r252:60911, Sep 30 2008, 15:42:03)
[GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.symlink('/home/wieslander/tmp/foobar', 'brokensymlink')
Check that the symlink was created and that the destination still doesn't exist:
[wieslander@rizzo tmp]$ ls -l brokensymlink
lrwxrwxrwx 1 wieslander wieslander 27 19 nov 13.13 brokensymlink -> /home/wieslander/tmp/foobar
[wieslander@rizzo tmp]$ ls -l /home/wieslander/tmp/foobar
ls: cannot access /home/wieslander/tmp/foobar: No such file or directory
A:
Are you sure you are calling symlink with the right parameters?
os.symlink('/usr/bin/python', 'python')
This should create a symlink to /usr/bin/python from python in the current working directory.
A:
This might be your answer:
$ python
Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.symlink('/this/does/not/exist', 'broken')
>>> os.symlink('broken', '/this/does/not/exist')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory
Did you reverse the arguments?
Or are you simply trying to create the symlink in a directory that does not exist?
|
Create broken symlink with Python
|
Using Python I want to create a symbolic link pointing to a path that does not exist. However os.symlink just complains about "OSError: [Errno 2] No such file or directory:".. This can easily be done with the ln program, but how to do it in Python without calling the ln program from Python?
Edit: somehow I really messed this up :/ ... both answers below is correct
|
[
"Such error is raised when you try to create a symlink in non-existent directory. For example, the following code will fail if /tmp/subdir doesn't exist:\nos.symlink('/usr/bin/python', '/tmp/subdir/python')\n\nBut this should run successfully:\nsrc = '/usr/bin/python'\ndst = '/tmp/subdir/python'\n\nif not os.path.isdir(os.path.dirname(dst)):\n os.makedirs(os.path.dirname(dst))\nos.symlink(src, dst)\n\n",
"The file doesn't need to exist in order to create the symlink. The following example demonstrates creating a symlink to a non-existing file:\nFirst, check that there's no file named foobar in /home/wieslander/tmp:\n[wieslander@rizzo tmp]$ ls -l /home/wieslander/tmp/foobar\nls: cannot access /home/wieslander/tmp/foobar: No such file or directory\n\nCreate a symlink named brokensymlink pointing to /home/wieslander/tmp/foobar:\n[wieslander@rizzo tmp]$ python\nPython 2.5.2 (r252:60911, Sep 30 2008, 15:42:03)\n[GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os\n>>> os.symlink('/home/wieslander/tmp/foobar', 'brokensymlink')\n\nCheck that the symlink was created and that the destination still doesn't exist:\n[wieslander@rizzo tmp]$ ls -l brokensymlink\nlrwxrwxrwx 1 wieslander wieslander 27 19 nov 13.13 brokensymlink -> /home/wieslander/tmp/foobar\n[wieslander@rizzo tmp]$ ls -l /home/wieslander/tmp/foobar\nls: cannot access /home/wieslander/tmp/foobar: No such file or directory\n\n",
"Are you sure you are calling symlink with the right parameters?\nos.symlink('/usr/bin/python', 'python')\n\nThis should create a symlink to /usr/bin/python from python in the current working directory.\n",
"This might be your answer:\n$ python\nPython 2.5.2 (r252:60911, Dec 2 2008, 09:26:14)\n[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os\n>>> os.symlink('/this/does/not/exist', 'broken')\n>>> os.symlink('broken', '/this/does/not/exist')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nOSError: [Errno 2] No such file or directory\n\nDid you reverse the arguments?\nOr are you simply trying to create the symlink in a directory that does not exist?\n"
] |
[
9,
3,
0,
0
] |
[] |
[] |
[
"ln",
"python",
"symlink"
] |
stackoverflow_0001762831_ln_python_symlink.txt
|
Q:
Testing complex datatypes?
What's are some ways of testing complex data types such as video, images, music, etc. I'm using TDD and wonder are there alternatives to "gold file" testing for rendering algorithms. I understand that there's ways to test other parts of the program that don't render and using those results you can infer. However, I'm particularly interested in rendering algorithms specifically image/video testing.
The question came up while I was using OpenCV/Python to do some basic facial recognition and want to verify its correctness.
Even if there's nothing definitive any suggestion will help.
A:
The idea how to test rendering is quite simple: to test a function use the inverse function and check if the input and output match (match is not equality in your case):
f(f^-1(x)) = x
To test a rendering algorithm you would encode the raw input, render the encoded values and analyze the difference between the rendered output and the raw input. One problem is to get the raw input, when encoding/decoding random input is not appropriate. Another challenge is to evaluate the differences between the raw input and rendering output. I suppose if you're writing some rendering software you should be able to do a frequency analysis on the data. (Some transformation should pop into your head now.)
If it is possible generate your test data. Text fixtures are a real maintenance problem. They only shine in the beginning. If they are changing in some kind everything breaks down. The main problem is that if your using a fixture your tests are going to repeat the fixture's content. This makes the interpretation of intent of your tests harder. If there is a magic value in your test what's the significant part of this value?
Fixture:
actual = parse("file.xml")
expected = "magic value"
assert(actual == expected)
Generated values:
expected = generate()
input = render(expected)
actual = parse()
assert(actual == expected)
The nice thing with generators is that you can build quite complex object graphs with them starting from primitive types and fields (python Quickcheck version).
Generator based tests are not deterministic by nature. But given enough trials they follow the Law of large numbers.
Their additional value is that they will produce a good test value range coverage. (Which is hard to achieve with test fixtures.) They will find unanticipated bugs in your code.
An alternative test approach is to test with a equivalent function:
f(x) = f'(x)
For example if you have a rendering function to compare against. This kind of test approach is useful if you have a working function. This function is your benchmark. It cannot be used in production because it is to slow or does use to much memory but can be easily debugged or proven to be correct.
A:
What's wrong with the "gold file" technique? It's part of your test fixture. Every test has a data fixture that's the equivalent to the "gold file" in a media-intensive application.
When doing ordinary TDD of ordinary business applications, one often has a golden database fixture that must be used.
Even when testing simple functions and core classes of an application, the setUp method creates a kind of "gold file" fixture for that class or function.
What's wrong with that technique? Please update your question with the specific problems you're having.
|
Testing complex datatypes?
|
What's are some ways of testing complex data types such as video, images, music, etc. I'm using TDD and wonder are there alternatives to "gold file" testing for rendering algorithms. I understand that there's ways to test other parts of the program that don't render and using those results you can infer. However, I'm particularly interested in rendering algorithms specifically image/video testing.
The question came up while I was using OpenCV/Python to do some basic facial recognition and want to verify its correctness.
Even if there's nothing definitive any suggestion will help.
|
[
"The idea how to test rendering is quite simple: to test a function use the inverse function and check if the input and output match (match is not equality in your case):\nf(f^-1(x)) = x\n\nTo test a rendering algorithm you would encode the raw input, render the encoded values and analyze the difference between the rendered output and the raw input. One problem is to get the raw input, when encoding/decoding random input is not appropriate. Another challenge is to evaluate the differences between the raw input and rendering output. I suppose if you're writing some rendering software you should be able to do a frequency analysis on the data. (Some transformation should pop into your head now.)\nIf it is possible generate your test data. Text fixtures are a real maintenance problem. They only shine in the beginning. If they are changing in some kind everything breaks down. The main problem is that if your using a fixture your tests are going to repeat the fixture's content. This makes the interpretation of intent of your tests harder. If there is a magic value in your test what's the significant part of this value?\nFixture:\nactual = parse(\"file.xml\")\nexpected = \"magic value\"\nassert(actual == expected)\n\nGenerated values:\nexpected = generate()\ninput = render(expected)\nactual = parse()\nassert(actual == expected)\n\nThe nice thing with generators is that you can build quite complex object graphs with them starting from primitive types and fields (python Quickcheck version).\nGenerator based tests are not deterministic by nature. But given enough trials they follow the Law of large numbers.\nTheir additional value is that they will produce a good test value range coverage. (Which is hard to achieve with test fixtures.) They will find unanticipated bugs in your code.\nAn alternative test approach is to test with a equivalent function:\nf(x) = f'(x)\n\nFor example if you have a rendering function to compare against. This kind of test approach is useful if you have a working function. This function is your benchmark. It cannot be used in production because it is to slow or does use to much memory but can be easily debugged or proven to be correct.\n",
"What's wrong with the \"gold file\" technique? It's part of your test fixture. Every test has a data fixture that's the equivalent to the \"gold file\" in a media-intensive application.\nWhen doing ordinary TDD of ordinary business applications, one often has a golden database fixture that must be used.\nEven when testing simple functions and core classes of an application, the setUp method creates a kind of \"gold file\" fixture for that class or function.\nWhat's wrong with that technique? Please update your question with the specific problems you're having.\n"
] |
[
2,
0
] |
[] |
[] |
[
"image",
"opencv",
"python",
"testing"
] |
stackoverflow_0001761663_image_opencv_python_testing.txt
|
Q:
What Is The Best Python Zip Module To Handle Large Files?
EDIT: Specifically compression and extraction speeds.
Any Suggestions?
Thanks
A:
So I made a random-ish large zipfile:
$ ls -l *zip
-rw-r--r-- 1 aleax 5000 115749854 Nov 18 19:16 large.zip
$ unzip -l large.zip | wc
23396 93633 2254735
i.e., 116 MB with 23.4K files in it, and timed things:
$ time unzip -d /tmp large.zip >/dev/null
real 0m14.702s
user 0m2.586s
sys 0m5.408s
this is the system-supplied commandline unzip binary -- no doubt as finely-tuned and optimized as a pure C executable can be. Then (after cleaning up /tmp;-)...:
$ time py26 -c'from zipfile import ZipFile; z=ZipFile("large.zip"); z.extractall("/tmp")'
real 0m13.274s
user 0m5.059s
sys 0m5.166s
...and this is Python with its standard library - a bit more demanding of CPU time, but over 10% faster in real, that is, elapsed time.
You're welcome to repeat such measurements of course (on your specific platform -- if it's CPU-poor, e.g a slow ARM chip, then Python's extra demands of CPU time may end up making it slower -- and your specific zipfiles of interest, since each large zipfile will have a very different mix and quite possibly performance). But what this suggests to me is that there isn't that much space to build a Python extension much faster than good old zipfile -- since Python using it beats the pure-C, system-included unzip!-)
A:
For handling large files without loading them into memory, use the new stream-based methods in Python 2.6's version of zipfile, such as ZipFile.open. Don't use extract or extractall unless you have strongly sanitised the filenames in the ZIP.
(You used to have to read all the bytes into memory, or hack around it like zipstream; this is now obsolete.)
|
What Is The Best Python Zip Module To Handle Large Files?
|
EDIT: Specifically compression and extraction speeds.
Any Suggestions?
Thanks
|
[
"So I made a random-ish large zipfile:\n$ ls -l *zip\n-rw-r--r-- 1 aleax 5000 115749854 Nov 18 19:16 large.zip\n$ unzip -l large.zip | wc\n 23396 93633 2254735\n\ni.e., 116 MB with 23.4K files in it, and timed things:\n$ time unzip -d /tmp large.zip >/dev/null\n\nreal 0m14.702s\nuser 0m2.586s\nsys 0m5.408s\n\nthis is the system-supplied commandline unzip binary -- no doubt as finely-tuned and optimized as a pure C executable can be. Then (after cleaning up /tmp;-)...:\n$ time py26 -c'from zipfile import ZipFile; z=ZipFile(\"large.zip\"); z.extractall(\"/tmp\")'\n\nreal 0m13.274s\nuser 0m5.059s\nsys 0m5.166s\n\n...and this is Python with its standard library - a bit more demanding of CPU time, but over 10% faster in real, that is, elapsed time.\nYou're welcome to repeat such measurements of course (on your specific platform -- if it's CPU-poor, e.g a slow ARM chip, then Python's extra demands of CPU time may end up making it slower -- and your specific zipfiles of interest, since each large zipfile will have a very different mix and quite possibly performance). But what this suggests to me is that there isn't that much space to build a Python extension much faster than good old zipfile -- since Python using it beats the pure-C, system-included unzip!-)\n",
"For handling large files without loading them into memory, use the new stream-based methods in Python 2.6's version of zipfile, such as ZipFile.open. Don't use extract or extractall unless you have strongly sanitised the filenames in the ZIP.\n(You used to have to read all the bytes into memory, or hack around it like zipstream; this is now obsolete.)\n"
] |
[
15,
5
] |
[] |
[] |
[
"compression",
"extraction",
"performance",
"python",
"zip"
] |
stackoverflow_0001759736_compression_extraction_performance_python_zip.txt
|
Q:
Python: asynchronous tcp socketserver
I'm looking http://docs.python.org/library/socketserver.html to try and handle asynchronous requests with the socketserver in python. At the very bottom there is an example, but it doesn't make sense. It says you use port 0 which assigns an arbitrary unused port. But how do you know what port to use for the client if they are not in the same program? I do not quite understand how to make this useful.
A:
Since the client is implemented in the same script as the server, the port is known. In a real-world scenario, you should specify a port for your daemon. Besides letting your clients know on which port to connect, you may also need to know so that you can open firewalls between your clients and your server.
A:
In the example you linked, they are fetching the port:
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 0
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
However, you should really be looking at www.twistedmatrix.com if you are serious about writing async handling :)
A:
You need to retrieve the port that was assigned to the socketserver once the bind is done: in this case, this will probably be through ip, port = server.server_address.
The arbitrary port is just if you want to create a server without specifying a port: the OS will assign an available port.
Of course there must also be a way to specify which port to bind to.
A:
server = ThreadedTCPServer((HOST, 0), ThreadedTCPRequestHandler)
ip, port = server.server_address
...
client(ip, port, "Hello World 1")
The PORT value 0 says "I don't care what port number it is," so the server_address's port value is assigned by the ThreadedTCPServer() call. It is not zero. Later, you pass that port value to the client, who uses it.
|
Python: asynchronous tcp socketserver
|
I'm looking http://docs.python.org/library/socketserver.html to try and handle asynchronous requests with the socketserver in python. At the very bottom there is an example, but it doesn't make sense. It says you use port 0 which assigns an arbitrary unused port. But how do you know what port to use for the client if they are not in the same program? I do not quite understand how to make this useful.
|
[
"Since the client is implemented in the same script as the server, the port is known. In a real-world scenario, you should specify a port for your daemon. Besides letting your clients know on which port to connect, you may also need to know so that you can open firewalls between your clients and your server.\n",
"In the example you linked, they are fetching the port:\n# Port 0 means to select an arbitrary unused port\nHOST, PORT = \"localhost\", 0\n\nserver = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)\nip, port = server.server_address\n\nHowever, you should really be looking at www.twistedmatrix.com if you are serious about writing async handling :)\n",
"You need to retrieve the port that was assigned to the socketserver once the bind is done: in this case, this will probably be through ip, port = server.server_address.\nThe arbitrary port is just if you want to create a server without specifying a port: the OS will assign an available port.\nOf course there must also be a way to specify which port to bind to.\n",
"server = ThreadedTCPServer((HOST, 0), ThreadedTCPRequestHandler)\nip, port = server.server_address\n\n...\n\nclient(ip, port, \"Hello World 1\")\n\nThe PORT value 0 says \"I don't care what port number it is,\" so the server_address's port value is assigned by the ThreadedTCPServer() call. It is not zero. Later, you pass that port value to the client, who uses it.\n"
] |
[
9,
5,
2,
0
] |
[] |
[] |
[
"asynchronous",
"networking",
"python",
"python_2.7"
] |
stackoverflow_0001763549_asynchronous_networking_python_python_2.7.txt
|
Q:
Deploying a python CGI app
I have developed a python CGI application which works just fine on my development box. My hosting provider however gives me little control of its server: I use a lot of custom stuff in my python environment (like sqlalchemy and mako templating) and the servers python version is far too old to be used. My question is: how do I set up a isolated, complete, standalone python environment in my home directory and install my required modules to run my app? ...the easiest way ;)
A:
how do I set up a isolated, complete, standalone python environment in my home directory
mkdir /home/me/.local (if it doesn't already exist. You don't have to use .local but it is becoming the normal place to put this)
mkdir /home/me/.local/src (ditto)
cd /home/me/.local/src
wget http://python.org/ftp/python/2.6.4/Python-2.6.4.tgz
gzip -d Python-2.6.4.tgz
tar xf Python-2.6.4.tar
cd Python-2.6.4
./configure --prefix=/home/me/.local
make
make install
Hopefully you can now run Python:
/home/me/.local/bin/python
Install packages you need using the usual setup.py script, but with your version of Python:
/home/me/.local/bin/python setup.py install
Set hashbang on CGI files to use your version of Python:
#!/home/me/.local/bin/python
Consider migrating your application to WSGI if you can. You can of course still deploy WSGI apps through CGI using a wsgiref.handlers.CGIHandler for now, but in the future when you have a less woeful hosting environment you'll be able to deploy using a much less wasteful server interface such as mod_wsgi.
A:
In your shoes, I'd use pyinstaller to bundle Python, my code, and all my dependencies into one installer executable, upload it, and run it. Just be sure to use the SVN trunk of pyinstaller -- the "released" version is WAY obsolete.
Be aware that with SQLAlchemy and everything else, with CGI you may find out you're really slow, since you're paying the full startup price everytime the page gets visited. But if CGI is all you can afford, I guess that's the way I would try to cope!-)
A:
This looks like a job for virtualenv. From the site:
Also, what if you can't install packages into the global site-packages directory? For instance, on a shared host.
This looks to be right up your alley.
A:
I am on Dreamhost's shared plan. Besides CGI, they also offer FastCGI which makes things much faster than CGI. You should check if your hosting provider offers that. Or maybe they provide Passenger for Ruby that you could piggyback your Python with.
If you compile Python yourself, keep in mind the UCS setting if you try to install precompiled packages and experience failures. See the StackOverflow article. Dreamhost's wiki has some advice on how you could build and deploy Python yourself on their servers; you might want to adapt to your needs.
|
Deploying a python CGI app
|
I have developed a python CGI application which works just fine on my development box. My hosting provider however gives me little control of its server: I use a lot of custom stuff in my python environment (like sqlalchemy and mako templating) and the servers python version is far too old to be used. My question is: how do I set up a isolated, complete, standalone python environment in my home directory and install my required modules to run my app? ...the easiest way ;)
|
[
"\nhow do I set up a isolated, complete, standalone python environment in my home directory\n\n\nmkdir /home/me/.local (if it doesn't already exist. You don't have to use .local but it is becoming the normal place to put this)\nmkdir /home/me/.local/src (ditto)\ncd /home/me/.local/src\nwget http://python.org/ftp/python/2.6.4/Python-2.6.4.tgz\ngzip -d Python-2.6.4.tgz\ntar xf Python-2.6.4.tar\ncd Python-2.6.4\n./configure --prefix=/home/me/.local\nmake\nmake install\n\nHopefully you can now run Python:\n\n/home/me/.local/bin/python\n\nInstall packages you need using the usual setup.py script, but with your version of Python:\n\n/home/me/.local/bin/python setup.py install\n\nSet hashbang on CGI files to use your version of Python:\n\n#!/home/me/.local/bin/python\n\nConsider migrating your application to WSGI if you can. You can of course still deploy WSGI apps through CGI using a wsgiref.handlers.CGIHandler for now, but in the future when you have a less woeful hosting environment you'll be able to deploy using a much less wasteful server interface such as mod_wsgi.\n",
"In your shoes, I'd use pyinstaller to bundle Python, my code, and all my dependencies into one installer executable, upload it, and run it. Just be sure to use the SVN trunk of pyinstaller -- the \"released\" version is WAY obsolete.\nBe aware that with SQLAlchemy and everything else, with CGI you may find out you're really slow, since you're paying the full startup price everytime the page gets visited. But if CGI is all you can afford, I guess that's the way I would try to cope!-)\n",
"This looks like a job for virtualenv. From the site:\n\nAlso, what if you can't install packages into the global site-packages directory? For instance, on a shared host.\n\nThis looks to be right up your alley.\n",
"I am on Dreamhost's shared plan. Besides CGI, they also offer FastCGI which makes things much faster than CGI. You should check if your hosting provider offers that. Or maybe they provide Passenger for Ruby that you could piggyback your Python with.\nIf you compile Python yourself, keep in mind the UCS setting if you try to install precompiled packages and experience failures. See the StackOverflow article. Dreamhost's wiki has some advice on how you could build and deploy Python yourself on their servers; you might want to adapt to your needs.\n"
] |
[
4,
1,
0,
0
] |
[] |
[] |
[
"cgi",
"hosting",
"linux",
"python"
] |
stackoverflow_0001759205_cgi_hosting_linux_python.txt
|
Q:
len(object) or hasattr(object, __iter__)?
(The following is python3-related (if that matter).)
This this the code I've written (simplified) :
class MyClass:
def __init__(self):
self.__some_var = []
@property
def some_var(self):
return self.__some__var
@some_var.setter
def some_var(self, new_value):
if hasattr(new_value, '__iter__'):
self.__some_var = new_value
else:
self.__some_var.append(new_value)
I want to replace when setting if their is several "values" (i.e if new_value is an iterable of, in my case, non-iterable objects) and appending if their is only one "value".
I'm concerned about the performance of hasattr so I wonder if I shouldn't use this setter instead :
@some_var.setter
def some_var(self, *args):
if len(args) > 1:
self.__some_var = args
else:
self.__some_var.append(args)
Thank for your attention !
A:
There's no "performance cost" of hasattr that matters. It's fast enough that you would have a hard time measuring it.
Please do not use __ (double underscore) for your own attributes. It's confusing to the rest of us.
It's usually best to use the collections Abstract Base Class membership for this kind of thing.
if isinstance( arg, collections.Sequence ):
self._some_var = list(arg)
else:
self._some_var.append( arg )
This gives you something that will likely work better because it expresses the semantics a little more clearly.
A:
An alternative might be duck typing:
Here I assume you want to evaluate (=make a list) out of the iterable, since it might be an iterator that you need to expand immediately to save.
@some_var.setter
def some_var(self, new_value):
try:
self.__some_var = list(new_value)
except TypeError:
self.__some_var.append(new_value)
Here we expect list() to raise ValueError if new_value is not iterable. As a response to your comment on S.Lott's answer, I don't think using hasattr is really duck typing style either.
A:
In terms of efficiency:
hasattr() would have a worst-case of O(1) (constant).
append() is also a worst-case of O(1) (constant).
|
len(object) or hasattr(object, __iter__)?
|
(The following is python3-related (if that matter).)
This this the code I've written (simplified) :
class MyClass:
def __init__(self):
self.__some_var = []
@property
def some_var(self):
return self.__some__var
@some_var.setter
def some_var(self, new_value):
if hasattr(new_value, '__iter__'):
self.__some_var = new_value
else:
self.__some_var.append(new_value)
I want to replace when setting if their is several "values" (i.e if new_value is an iterable of, in my case, non-iterable objects) and appending if their is only one "value".
I'm concerned about the performance of hasattr so I wonder if I shouldn't use this setter instead :
@some_var.setter
def some_var(self, *args):
if len(args) > 1:
self.__some_var = args
else:
self.__some_var.append(args)
Thank for your attention !
|
[
"There's no \"performance cost\" of hasattr that matters. It's fast enough that you would have a hard time measuring it.\nPlease do not use __ (double underscore) for your own attributes. It's confusing to the rest of us.\nIt's usually best to use the collections Abstract Base Class membership for this kind of thing.\nif isinstance( arg, collections.Sequence ):\n self._some_var = list(arg)\nelse:\n self._some_var.append( arg )\n\nThis gives you something that will likely work better because it expresses the semantics a little more clearly.\n",
"An alternative might be duck typing:\nHere I assume you want to evaluate (=make a list) out of the iterable, since it might be an iterator that you need to expand immediately to save.\n@some_var.setter\ndef some_var(self, new_value):\n try:\n self.__some_var = list(new_value)\n except TypeError:\n self.__some_var.append(new_value)\n\nHere we expect list() to raise ValueError if new_value is not iterable. As a response to your comment on S.Lott's answer, I don't think using hasattr is really duck typing style either.\n",
"In terms of efficiency:\n\nhasattr() would have a worst-case of O(1) (constant).\nappend() is also a worst-case of O(1) (constant).\n\n"
] |
[
4,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001763507_python.txt
|
Q:
Scanning Keypress in Python
I have paused a script for lets say 3500 seconds by using time module for ex time.sleep(3500).
Now, my aim is to scan for keypresses while the script is on sleep, i mean its on this line.
Its like I want to restart the script if a "keypress Ctrl+R" is pressed.
For ex.. consider
#!/usr/bin/python
import time
print "Hello.. again"
while True:
time.sleep(3500)
Now while the code is at last line, If i press Ctrl+R, i want to re-print "Hello.. again" line.
A:
I am aware that this does not fully answer your question, but you could do the following:
Put the program logic code in a function, say perform_actions. Call it when the program starts.
After the code has been run, start listening for an interrupt.
That is, the user must press ctrl+c instead of ctrl+r.
On receiving an interrupt, wait half a second; if ctrl+c is pressed again, then exit.
Otherwise, restart the code.
Thus one interrupt behaves as you want ctrl+r to behave. Two quick interrupts quit the program.
import time
def perform_actions():
print("Hello.. again")
try:
while True:
perform_actions()
try:
while True: time.sleep(3600)
except KeyboardInterrupt:
time.sleep(0.5)
except KeyboardInterrupt:
pass
A nice side-effect of using a signal (in this case SIGINT) is that you also restart the script through other means, e.g. by running kill -int <pid>.
A:
You may want to use Tkinter {needs X :(}
#!/usr/bin/env python
from Tkinter import * # needs python-tk
root = Tk()
def hello(*ignore):
print 'Hello World'
root.bind('<Control-r>', hello)
root.mainloop() # starts an X widget
This script prints Hello World to the console if you press ctrl+r
See also Tkinter keybindings. Another solution uses GTK can be found here
|
Scanning Keypress in Python
|
I have paused a script for lets say 3500 seconds by using time module for ex time.sleep(3500).
Now, my aim is to scan for keypresses while the script is on sleep, i mean its on this line.
Its like I want to restart the script if a "keypress Ctrl+R" is pressed.
For ex.. consider
#!/usr/bin/python
import time
print "Hello.. again"
while True:
time.sleep(3500)
Now while the code is at last line, If i press Ctrl+R, i want to re-print "Hello.. again" line.
|
[
"I am aware that this does not fully answer your question, but you could do the following:\n\nPut the program logic code in a function, say perform_actions. Call it when the program starts.\nAfter the code has been run, start listening for an interrupt.\n\n\nThat is, the user must press ctrl+c instead of ctrl+r.\n\nOn receiving an interrupt, wait half a second; if ctrl+c is pressed again, then exit.\nOtherwise, restart the code.\n\nThus one interrupt behaves as you want ctrl+r to behave. Two quick interrupts quit the program.\nimport time\n\ndef perform_actions():\n print(\"Hello.. again\")\n\ntry:\n while True:\n perform_actions()\n try:\n while True: time.sleep(3600)\n except KeyboardInterrupt:\n time.sleep(0.5)\nexcept KeyboardInterrupt:\n pass\n\nA nice side-effect of using a signal (in this case SIGINT) is that you also restart the script through other means, e.g. by running kill -int <pid>.\n",
"You may want to use Tkinter {needs X :(}\n#!/usr/bin/env python\n\nfrom Tkinter import * # needs python-tk\n\nroot = Tk()\n\ndef hello(*ignore):\n print 'Hello World'\n\nroot.bind('<Control-r>', hello)\nroot.mainloop() # starts an X widget\n\nThis script prints Hello World to the console if you press ctrl+r\nSee also Tkinter keybindings. Another solution uses GTK can be found here\n"
] |
[
4,
3
] |
[
"in a for loop sleep 3500 times for 1 second checking if a key was pressed each time\n# sleep for 3500 seconds unless ctrl+r is pressed\nfor i in range(3500):\n time.sleep(1)\n # check if ctrl+r is pressed\n # if pressed -> do something\n # otherwise go back to sleep\n\n"
] |
[
-2
] |
[
"linux",
"python",
"scripting"
] |
stackoverflow_0001762697_linux_python_scripting.txt
|
Q:
How to find unique starts of strings?
If I have a list of strings (eg 'blah 1', 'blah 2' 'xyz fg','xyz penguin'), what would be the best way of finding the unique starts of strings ('xyz' and 'blah' in this case)? The starts of strings can be multiple words.
A:
Your question is confusing, as it is not clear what you really want. So I'll give three answers and hope that one of them at least partially answers your question.
To get all unique prefixes of a given list of string, you can do:
>>> l = ['blah 1', 'blah 2', 'xyz fg', 'xyz penguin']
>>> set(s[:i] for s in l for i in range(len(s) + 1))
{'', 'xyz pe', 'xyz penguin', 'b', 'xyz fg', 'xyz peng', 'xyz pengui', 'bl', 'blah 2', 'blah 1', 'blah', 'xyz f', 'xy', 'xyz pengu', 'xyz p', 'x', 'blah ', 'xyz pen', 'bla', 'xyz', 'xyz '}
This code generates all initial slices of every string in the list and passes these to a set to remove duplicates.
To get all largest initial word sequences smaller than the full string, you could go with:
>>> l = ['a b', 'a c', 'a b c', 'b c']
>>> set(s.rsplit(' ', 1)[0] for s in l)
{'a', 'a b', 'b'}
This code creates a set by splitting all strings at their rightmost space, if available (otherwise the while string will be returned).
On the other hand, to get all unique initial word sequences without considering full strings, you could go for:
>>> l = ['a b', 'a c', 'a b c', 'b c']
>>> set(' '.join(w[:i]) for s in l for w in (s.split(),) for i in range(len(w)))
{'', 'a', 'b', 'a b'}
This code splits each word at any whitespace and concatenates all initial slices of the resulting list, except the largest one. This code has pitfall: it will e.g. convert tabs to spaces. This may or may not be an issue in your case.
A:
If you mean unique first words of strings (words being separated by space), this would be:
arr=['blah 1', 'blah 2' 'xyz fg','xyz penguin']
unique=list(set([x.split(' ')[0] for x in arr]))
|
How to find unique starts of strings?
|
If I have a list of strings (eg 'blah 1', 'blah 2' 'xyz fg','xyz penguin'), what would be the best way of finding the unique starts of strings ('xyz' and 'blah' in this case)? The starts of strings can be multiple words.
|
[
"Your question is confusing, as it is not clear what you really want. So I'll give three answers and hope that one of them at least partially answers your question.\n\nTo get all unique prefixes of a given list of string, you can do:\n>>> l = ['blah 1', 'blah 2', 'xyz fg', 'xyz penguin']\n>>> set(s[:i] for s in l for i in range(len(s) + 1))\n{'', 'xyz pe', 'xyz penguin', 'b', 'xyz fg', 'xyz peng', 'xyz pengui', 'bl', 'blah 2', 'blah 1', 'blah', 'xyz f', 'xy', 'xyz pengu', 'xyz p', 'x', 'blah ', 'xyz pen', 'bla', 'xyz', 'xyz '}\n\nThis code generates all initial slices of every string in the list and passes these to a set to remove duplicates.\nTo get all largest initial word sequences smaller than the full string, you could go with:\n>>> l = ['a b', 'a c', 'a b c', 'b c']\n>>> set(s.rsplit(' ', 1)[0] for s in l)\n{'a', 'a b', 'b'}\n\nThis code creates a set by splitting all strings at their rightmost space, if available (otherwise the while string will be returned).\nOn the other hand, to get all unique initial word sequences without considering full strings, you could go for:\n>>> l = ['a b', 'a c', 'a b c', 'b c']\n>>> set(' '.join(w[:i]) for s in l for w in (s.split(),) for i in range(len(w)))\n{'', 'a', 'b', 'a b'}\n\nThis code splits each word at any whitespace and concatenates all initial slices of the resulting list, except the largest one. This code has pitfall: it will e.g. convert tabs to spaces. This may or may not be an issue in your case.\n\n",
"If you mean unique first words of strings (words being separated by space), this would be:\narr=['blah 1', 'blah 2' 'xyz fg','xyz penguin']\nunique=list(set([x.split(' ')[0] for x in arr]))\n\n"
] |
[
4,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001763510_python.txt
|
Q:
Phonon VideoWidget error: "the video widget could not be initialized correctly"
I asked this question on the PyQt mailing list, and didn't get any responses, so I'll try my luck here.
I've encountered a frustrating issue (on Windows only): when trying to create a VideoWidget instance, I'm getting the error message "the video widget could not be initialized correctly". Oddly, this just surfaced in the code after several weeks of perfect operation, on two separate Windows boxes (one Vista, the other an XP image running via Parallels). I'm not aware of anything having changed in the environment that may have caused it.
I'm using Python 2.6 and the PyQt 4.5.4 Windows installer. I notice this issue was raised last November, but no solutions were offered:
http://www.riverbankcomputing.com/pipermail/pyqt/2008-November/021029.html
My Googling hasn't turned up any explanations of what may cause this. Can anyone clue me in?
A:
The code that generates that message is in 3rdparty/phonon/ds9/videorenderer_vmr9.cpp:
m_filter = Filter(CLSID_VideoMixingRenderer9, IID_IBaseFilter);
if (!m_filter) {
qWarning("the video widget could not be initialized correctly");
return;
}
Filter is type ComPointer<IBaseFilter> and its constructor makes the following failing call (an operator call returns m_t which is assigned to m_filter above):
::CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER, iid,
reinterpret_cast<void**>(&m_t));
Thus, it's failing in a Windows API call. You could modify the source code to find out what the return value of CoCreateInstance is in order to isolate the cause, but it looks like it's related to a change on your system and I don't know how to help further. Good luck.
A:
Hate to answer my own question, but if anyone else encounters this:
The solution to this ended up being hardware-specific. Phonon appears to have issues with the video drivers for particular virtual machines - Parallels in my case. Physical hardware doesn't exhibit the issue. There is no workaround I've been able to find.
|
Phonon VideoWidget error: "the video widget could not be initialized correctly"
|
I asked this question on the PyQt mailing list, and didn't get any responses, so I'll try my luck here.
I've encountered a frustrating issue (on Windows only): when trying to create a VideoWidget instance, I'm getting the error message "the video widget could not be initialized correctly". Oddly, this just surfaced in the code after several weeks of perfect operation, on two separate Windows boxes (one Vista, the other an XP image running via Parallels). I'm not aware of anything having changed in the environment that may have caused it.
I'm using Python 2.6 and the PyQt 4.5.4 Windows installer. I notice this issue was raised last November, but no solutions were offered:
http://www.riverbankcomputing.com/pipermail/pyqt/2008-November/021029.html
My Googling hasn't turned up any explanations of what may cause this. Can anyone clue me in?
|
[
"The code that generates that message is in 3rdparty/phonon/ds9/videorenderer_vmr9.cpp:\nm_filter = Filter(CLSID_VideoMixingRenderer9, IID_IBaseFilter);\nif (!m_filter) {\n qWarning(\"the video widget could not be initialized correctly\");\n return;\n }\n\nFilter is type ComPointer<IBaseFilter> and its constructor makes the following failing call (an operator call returns m_t which is assigned to m_filter above):\n::CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER, iid,\n reinterpret_cast<void**>(&m_t));\n\nThus, it's failing in a Windows API call. You could modify the source code to find out what the return value of CoCreateInstance is in order to isolate the cause, but it looks like it's related to a change on your system and I don't know how to help further. Good luck.\n",
"Hate to answer my own question, but if anyone else encounters this:\nThe solution to this ended up being hardware-specific. Phonon appears to have issues with the video drivers for particular virtual machines - Parallels in my case. Physical hardware doesn't exhibit the issue. There is no workaround I've been able to find.\n"
] |
[
3,
0
] |
[] |
[] |
[
"phonon",
"pyqt",
"python",
"qt"
] |
stackoverflow_0001291068_phonon_pyqt_python_qt.txt
|
Q:
How do I do a "for each" , starting at a certain index of a list (Python)?
Suppose I have this list:
thelist = ['apple','orange','banana','grapes']
for fruit in thelist:
This would go through all the fruits.
However, what if I wanted to start at orange? Instead of starting at apple?
Sure, I could do "if ...continue", but there must be a better way?
A:
for fruit in thelist[1:]:
...
this of course suppose you know at which index to start. but you can find the index easily:
for fruit in thelist[thelist.index('orange'):]:
...
A:
using python's elegant slices
>>> for fruit in thelist[1:]:
>>> print fruit
A:
As mentioned by Paul McGuire, slicing a list creates a copy in memory of the result. If you have a list with 500,000 elements then doing l[2:] is going to create a new 499,998 element list.
To avoid this, use itertools.islice:
>>> thelist = ['a', 'b', 'c']
>>> import itertools
>>> for i in itertools.islice(thelist, 1, None):
... print i
...
b
c
A:
for fruit in thelist [1:]:
will start at the second element in the list.
A:
for fruit in thelist[1:]:
print fruit
A:
Slices make copies of lists, so if there are many items, or if you don't want to separately search the list for the starting index, an iterator will let you search, and then continue from there:
>>> thelist = ['apple','orange','banana','grapes']
>>> fruit_iter = iter(thelist)
>>> target_value = 'orange'
>>> while fruit_iter.next() != target_value: pass
...
>>> # at this point, fruit_iter points to the entry after target_value
>>> print ','.join(fruit_iter)
banana,grapes
>>>
|
How do I do a "for each" , starting at a certain index of a list (Python)?
|
Suppose I have this list:
thelist = ['apple','orange','banana','grapes']
for fruit in thelist:
This would go through all the fruits.
However, what if I wanted to start at orange? Instead of starting at apple?
Sure, I could do "if ...continue", but there must be a better way?
|
[
"for fruit in thelist[1:]:\n ...\n\nthis of course suppose you know at which index to start. but you can find the index easily:\nfor fruit in thelist[thelist.index('orange'):]:\n ...\n\n",
"using python's elegant slices\n>>> for fruit in thelist[1:]:\n>>> print fruit\n\n",
"As mentioned by Paul McGuire, slicing a list creates a copy in memory of the result. If you have a list with 500,000 elements then doing l[2:] is going to create a new 499,998 element list.\nTo avoid this, use itertools.islice:\n>>> thelist = ['a', 'b', 'c']\n\n>>> import itertools\n\n>>> for i in itertools.islice(thelist, 1, None):\n... print i\n...\nb\nc\n\n",
"for fruit in thelist [1:]:\n\nwill start at the second element in the list.\n",
"for fruit in thelist[1:]:\n print fruit\n\n",
"Slices make copies of lists, so if there are many items, or if you don't want to separately search the list for the starting index, an iterator will let you search, and then continue from there:\n>>> thelist = ['apple','orange','banana','grapes']\n>>> fruit_iter = iter(thelist)\n>>> target_value = 'orange'\n>>> while fruit_iter.next() != target_value: pass\n...\n>>> # at this point, fruit_iter points to the entry after target_value\n>>> print ','.join(fruit_iter)\nbanana,grapes\n>>>\n\n"
] |
[
14,
11,
3,
2,
1,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001762571_list_python.txt
|
Q:
Python os.getcwd paths
I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. I'm going to use the txt file to import into access to generate hyperlinks. The problem I'm having is getting the correct path. So when the script is ran it uses whatever directory you are in. Here is an example. Right now it half works, it create links.txt, but there is nothing in the text file.
myDirectory = os.listdir("links")
f.open("links.txt", "w")
f.writelines([os.getcwd %s % (f) for f in myDirectory])
A:
This line of yours:
f.writelines([os.getcwd %s % (f) for f in myDirectory])
is invalid Python syntax and it's very hard to guess what you had in mind for it -- for example, why would you care about the current directory when myDirectory lists, not files in the current directory, but rather files in subdirectory "links"?
Trying to read your mind is always a difficult and generally unrewarding exercise, but assuming you do mean to use the current directory, you might want
f.writelines(os.path.join(os.getcwd(), f) for f in myDirectory)
A:
You have to call os.getcwd() with the trailing parens.
What you probably actually want here though is os.path.join()
A:
os.getcwd is a function you need to call... also I'm not sure what you're doing with the string escape % - but they only work inside strings... I'm guessing you want something like this:
f.writelines([os.path.join(os.getcwd(),f) for f in myDirectory])
[Edit: os.path.join from Alex Martelli's better answer]
|
Python os.getcwd paths
|
I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. I'm going to use the txt file to import into access to generate hyperlinks. The problem I'm having is getting the correct path. So when the script is ran it uses whatever directory you are in. Here is an example. Right now it half works, it create links.txt, but there is nothing in the text file.
myDirectory = os.listdir("links")
f.open("links.txt", "w")
f.writelines([os.getcwd %s % (f) for f in myDirectory])
|
[
"This line of yours:\nf.writelines([os.getcwd %s % (f) for f in myDirectory])\n\nis invalid Python syntax and it's very hard to guess what you had in mind for it -- for example, why would you care about the current directory when myDirectory lists, not files in the current directory, but rather files in subdirectory \"links\"?\nTrying to read your mind is always a difficult and generally unrewarding exercise, but assuming you do mean to use the current directory, you might want\n f.writelines(os.path.join(os.getcwd(), f) for f in myDirectory)\n\n",
"You have to call os.getcwd() with the trailing parens.\nWhat you probably actually want here though is os.path.join()\n",
"os.getcwd is a function you need to call... also I'm not sure what you're doing with the string escape % - but they only work inside strings... I'm guessing you want something like this:\nf.writelines([os.path.join(os.getcwd(),f) for f in myDirectory])\n\n[Edit: os.path.join from Alex Martelli's better answer]\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001764322_python.txt
|
Q:
String formatting expressions (Python)
String formatting expressions:
'This is %d %s example!' % (1, 'nice')
String formatting method calls:
'This is {0} {1} example!'.format(1, 'nice')
I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become deprecated over time. Which do you think is less likely to be deprecated?
A:
Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the dict based formatting:
d = { 'count': 1, 'txt': 'nice' }
'This is %(count)d %(txt)s example!' % d
It makes sure that the right parameter goes into the right place, allows to reuse the same parameter in several places, etc.
A:
I thought I read that the % operator is being deprecated in 3.1 already, so I'd stick with the format() function.
See PEP 3101: A New Approach To String Formatting
A:
The original idea was to gradually switch to str.format() approach while allowing both ways:
PEP 3101:
The new system does not collide with any of the method names of the existing string formatting techniques, so both systems can co-exist until it comes time to deprecate the older system.
The idea is still being pursued:
We are still encouraging people to use the new str.format().
Python Issue 7343
Since the original '%' approach is planned to be deprecated and removed at some point in the future, I would suggest writing new code with str.format(). Though at the moment, it is just a matter of personal preference. I personally prefer using dictionary-based formatting, which is supported by both '%' operator and str.format() method.
|
String formatting expressions (Python)
|
String formatting expressions:
'This is %d %s example!' % (1, 'nice')
String formatting method calls:
'This is {0} {1} example!'.format(1, 'nice')
I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become deprecated over time. Which do you think is less likely to be deprecated?
|
[
"Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the dict based formatting:\nd = { 'count': 1, 'txt': 'nice' }\n'This is %(count)d %(txt)s example!' % d\n\nIt makes sure that the right parameter goes into the right place, allows to reuse the same parameter in several places, etc.\n",
"I thought I read that the % operator is being deprecated in 3.1 already, so I'd stick with the format() function.\nSee PEP 3101: A New Approach To String Formatting\n",
"The original idea was to gradually switch to str.format() approach while allowing both ways:\n\nPEP 3101: \n The new system does not collide with any of the method names of the existing string formatting techniques, so both systems can co-exist until it comes time to deprecate the older system. \n\nThe idea is still being pursued:\n\nWe are still encouraging people to use the new str.format().\n Python Issue 7343\n\nSince the original '%' approach is planned to be deprecated and removed at some point in the future, I would suggest writing new code with str.format(). Though at the moment, it is just a matter of personal preference. I personally prefer using dictionary-based formatting, which is supported by both '%' operator and str.format() method.\n"
] |
[
8,
6,
5
] |
[] |
[] |
[
"deprecated",
"printf",
"python",
"string"
] |
stackoverflow_0001763184_deprecated_printf_python_string.txt
|
Q:
Width and Precision using *
I'm learning Python from a book and came across this example:
>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'
Don't quite understand what's happening here, especially the '4' in between.
A:
I think you meant something like this:
>>> '%f, %2.f, %.*f' % (1/3.0, 1.3, 4, 1/3.0)
'0.333333, 1, 0.3333'
4 is a wild card value that is used in place of asterisk *. When expanded it would be equivalent to:
>>> '%f, %2.f, %.4f' % (1/3.0, 1.3, 1/3.0)
A:
There are two syntax errors in the line you posted. 1.3.0 isn't a valid number, and the string isn't closed.
This is a valid version of said string format.
'%f, %2.f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
and outputs:
'0.333333, 0.33, 0.3333'
I couldn't find documentation on %.*f in the official docs. However, it appears that it's parsing the 4 to be how many decimal places you want to do the next argument at.
For example:
'%.*f' % (5, 1/3.0)
returns
'0.33333'
and
'%.*f' % (6, 1/3.0)
returns
'0.333333'
It seems to be a way to offer variable length precision, so you could allow your users to specify it.
|
Width and Precision using *
|
I'm learning Python from a book and came across this example:
>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'
Don't quite understand what's happening here, especially the '4' in between.
|
[
"I think you meant something like this:\n>>> '%f, %2.f, %.*f' % (1/3.0, 1.3, 4, 1/3.0)\n'0.333333, 1, 0.3333'\n\n4 is a wild card value that is used in place of asterisk *. When expanded it would be equivalent to:\n>>> '%f, %2.f, %.4f' % (1/3.0, 1.3, 1/3.0)\n\n",
"There are two syntax errors in the line you posted. 1.3.0 isn't a valid number, and the string isn't closed.\nThis is a valid version of said string format.\n'%f, %2.f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)\n\nand outputs: \n'0.333333, 0.33, 0.3333'\n\nI couldn't find documentation on %.*f in the official docs. However, it appears that it's parsing the 4 to be how many decimal places you want to do the next argument at. \nFor example:\n'%.*f' % (5, 1/3.0)\n\nreturns\n'0.33333'\n\nand \n'%.*f' % (6, 1/3.0)\n\nreturns\n'0.333333'\n\nIt seems to be a way to offer variable length precision, so you could allow your users to specify it. \n"
] |
[
3,
1
] |
[] |
[] |
[
"python",
"string_formatting"
] |
stackoverflow_0001764812_python_string_formatting.txt
|
Q:
Embedding a remote Python shell in an application
You can embed the IPython shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell?
Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated.
A:
Python includes a telnet client, but not a telnet server. You can implement a telnet server using Twisted. Here's an example. As for hooking these things together, that's up to you.
A:
Use Twisted Manhole. Docs are a bit lacking, but it's easy enough to set up a telnet-based remote server and it comes with a GTK-based GUI.
Main Twisted site
twisted.manhole API docs
A:
I think you should base your server class on the SocketServer class from the standard library. You'll need to write a RequestHandler to read and echo input but a lot of the heavy lifting is already done for you.
You can use the ThreadingMixIn to make the server multi-threaded very easily.
A:
Try to use xmlrpc namespace
|
Embedding a remote Python shell in an application
|
You can embed the IPython shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell?
Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated.
|
[
"Python includes a telnet client, but not a telnet server. You can implement a telnet server using Twisted. Here's an example. As for hooking these things together, that's up to you.\n",
"Use Twisted Manhole. Docs are a bit lacking, but it's easy enough to set up a telnet-based remote server and it comes with a GTK-based GUI.\n\nMain Twisted site\ntwisted.manhole API docs\n\n",
"I think you should base your server class on the SocketServer class from the standard library. You'll need to write a RequestHandler to read and echo input but a lot of the heavy lifting is already done for you.\nYou can use the ThreadingMixIn to make the server multi-threaded very easily. \n",
"Try to use xmlrpc namespace\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"networking",
"python"
] |
stackoverflow_0000048176_networking_python.txt
|
Q:
Is there an algorithm to find unique combinations of 2 lists? 5 lists?
I have N Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data structure (binary tree?) make a job like this more appropriate?
Given:
# 1 2
a = [1, 2]
b = [a, b]
The result would be:
c = [1a, 1b, 2a, 2b] # (4 unique combinations)
Given:
v = [1, a]
w = [1, b]
x = [1, c]
y = [1, d]
z = [1, e]
The result would be:
r = [11111, 1bcde, 11cde, 111de, 1111e, a1111, ab111, abc11, abcd1, abcde, 1b1d1, 1bc1e, 11c11, 11c1e, ... ]
A:
Perhaps you are looking for itertools.product:
#!/usr/bin/env python
import itertools
a=[1,2]
b=['a','b']
c=[str(s)+str(t) for s,t in itertools.product(a,b)]
print(c)
['1a', '1b', '2a', '2b']
v=[1,'a']
w=[1,'b']
x=[1,'c']
y=[1,'d']
z=[1,'e']
r=[''.join([str(elt) for elt in p]) for p in itertools.product(v,w,x,y,z)]
print(r)
# ['11111', '1111e', '111d1', '111de', '11c11', '11c1e', '11cd1', '11cde', '1b111', '1b11e', '1b1d1', '1b1de', '1bc11', '1bc1e', '1bcd1', '1bcde', 'a1111', 'a111e', 'a11d1', 'a11de', 'a1c11', 'a1c1e', 'a1cd1', 'a1cde', 'ab111', 'ab11e', 'ab1d1', 'ab1de', 'abc11', 'abc1e', 'abcd1', 'abcde']
Note that product yields 2**5 elements. Is this what you want?
itertools.product is in Python 2.6. For previous versions, you can use this:
def product(*args, **kwds):
'''
Source: http://docs.python.org/library/itertools.html#itertools.product
'''
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
Edit: As jellybean points out, the original question asks for unique sets. The above code will not produce unique sets if a,b,v,w,x,y, or z contain repeated elements. If this is an issue for you, then you can convert each list to a set before sending it to itertools.product:
r=[''.join([str(elt) for elt in p]) for p in itertools.product(*(set(elt) for elt in (v,w,x,y,z)))]
A:
I don't think the question asks for the powerset of the inputs, I think it asks for (part of) the Cartesian product of the input sets. I expect someone will correct me if I'm wrong.
And, as for an algorithm, well now that you know what it is you are looking for, Google will be your friend.
In your second example, you exclude entries such as 1b1de from your result set. Is this deliberate ? If it is deliberate, what is the rule by which the output is constructed?
A:
I think another answer is in order, to respond to this:
I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet.
There is a pattern.
Suppose you have just two lists to combine. You can find all the combinations by making a grid.
black blue
+------------+------------+
coat | black coat | blue coat |
+------------+------------+
hat | black hat | blue hat |
+------------+------------+
As you can see, there are 2*2 combinations. If there were 30 colors and 14 kinds of clothing, you would have 30 * 14 = 420 combinations.
The pattern continues as you add more lists. Instead of a 2-dimensional rectangle, you get an 3-dimensional array of boxes, or ultimately an n-dimensional hyperrectangle. Regardless, the total number of combinations is always the product of the lengths of all the lists.
If you know how many lists you have, nested loops are a natural way to make all combinations.
for color in colors:
for kind in kinds:
print color, kind # "black coat", "black hat", etc.
If the lists are in dictionary order to start with, and there are no duplicates, the output will also be in dictionary order.
A:
I'm assuming that you want the Cartesian product - all possible lists created by choosing exactly one element from each list. You can implement it recursively, like this:
def cartesian_product(l):
if l:
for b in cartesian_product(l[1:]):
for a in l[0]:
yield [a] + b
else:
yield []
l = [
[ 'a', 'b' ],
[ 'c', 'd', 'e' ],
[ 'f', 'g' ],
]
for x in cartesian_product(l):
print x
Update: ~unutbu's suggestion of itertools.product is better, but I'll leave this here anyway.
A:
Since you need a cartesian product, use that of itertools !
>>> import itertools
>>> v = [1, 'a']
>>> w = [1, 'b']
>>> x = [1, 'c']
>>> y = [1, 'd']
>>> z = [1, 'e']
>>> p = [''.join(str(x) for x in c) for c in itertools.product(v,w,x,y,z)]
>>> p
['11111', '1111e', '111d1', '111de', '11c11', '11c1e', '11cd1', '11cde', '1b111'
, '1b11e', '1b1d1', '1b1de', '1bc11', '1bc1e', '1bcd1', '1bcde', 'a1111', 'a111e
', 'a11d1', 'a11de', 'a1c11', 'a1c1e', 'a1cd1', 'a1cde', 'ab111', 'ab11e', 'ab1d
1', 'ab1de', 'abc11', 'abc1e', 'abcd1', 'abcde']
>>>
A:
Might that do the trick?
def getAllCombinations(listOfLists):
if len(listOfLists) == 1:
return [str(x) for x in listOfLists[0]]
result = set()
head, tail = listOfLists[0], listOfLists[1:]
tailCombs = getAllCombinations(tail)
for elem in head:
for tc in tailCombs:
result.add(str(elem) + tc)
return result
v = [1, 'a']
w = [1, 'b']
x = [1, 'c']
y = [1, 'd']
z = [1, 'e']
>>> print getAllCombinations([v, w, x, y, z])
set(['111de', 'abc11', 'a1c1e', 'a111e', '11c11', 'ab11e', '1bc11', 'ab1d1', 'a1cd1', '1b1de', 'a11d1', '11111', '1b111', '11cd1', 'abcd1', '1bcde', 'ab111', '1bc1e', 'abc1e', '111d1', 'a1111', '11c1e', 'a1c11', '11cde', '1b11e', '1bcd1', 'abcde', 'a1cde', '1b1d1', 'a11de', 'ab1de', '1111e'])
A:
You're looking for the Cartesian product. In Python, if you want tuples:
c = [(x, y) for x in a for y in b]
r = [(vv, ww, xx, yy, zz)
for vv in v for ww in w for xx in x for yy in y for zz in z]
|
Is there an algorithm to find unique combinations of 2 lists? 5 lists?
|
I have N Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data structure (binary tree?) make a job like this more appropriate?
Given:
# 1 2
a = [1, 2]
b = [a, b]
The result would be:
c = [1a, 1b, 2a, 2b] # (4 unique combinations)
Given:
v = [1, a]
w = [1, b]
x = [1, c]
y = [1, d]
z = [1, e]
The result would be:
r = [11111, 1bcde, 11cde, 111de, 1111e, a1111, ab111, abc11, abcd1, abcde, 1b1d1, 1bc1e, 11c11, 11c1e, ... ]
|
[
"Perhaps you are looking for itertools.product:\n#!/usr/bin/env python\nimport itertools\na=[1,2]\nb=['a','b']\nc=[str(s)+str(t) for s,t in itertools.product(a,b)]\nprint(c)\n['1a', '1b', '2a', '2b']\n\nv=[1,'a']\nw=[1,'b']\nx=[1,'c']\ny=[1,'d']\nz=[1,'e']\n\nr=[''.join([str(elt) for elt in p]) for p in itertools.product(v,w,x,y,z)]\nprint(r)\n# ['11111', '1111e', '111d1', '111de', '11c11', '11c1e', '11cd1', '11cde', '1b111', '1b11e', '1b1d1', '1b1de', '1bc11', '1bc1e', '1bcd1', '1bcde', 'a1111', 'a111e', 'a11d1', 'a11de', 'a1c11', 'a1c1e', 'a1cd1', 'a1cde', 'ab111', 'ab11e', 'ab1d1', 'ab1de', 'abc11', 'abc1e', 'abcd1', 'abcde']\n\nNote that product yields 2**5 elements. Is this what you want?\nitertools.product is in Python 2.6. For previous versions, you can use this:\ndef product(*args, **kwds):\n '''\n Source: http://docs.python.org/library/itertools.html#itertools.product\n '''\n # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy\n # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111\n pools = map(tuple, args) * kwds.get('repeat', 1)\n result = [[]]\n for pool in pools:\n result = [x+[y] for x in result for y in pool]\n for prod in result:\n yield tuple(prod)\n\nEdit: As jellybean points out, the original question asks for unique sets. The above code will not produce unique sets if a,b,v,w,x,y, or z contain repeated elements. If this is an issue for you, then you can convert each list to a set before sending it to itertools.product:\nr=[''.join([str(elt) for elt in p]) for p in itertools.product(*(set(elt) for elt in (v,w,x,y,z)))]\n\n",
"I don't think the question asks for the powerset of the inputs, I think it asks for (part of) the Cartesian product of the input sets. I expect someone will correct me if I'm wrong.\nAnd, as for an algorithm, well now that you know what it is you are looking for, Google will be your friend.\nIn your second example, you exclude entries such as 1b1de from your result set. Is this deliberate ? If it is deliberate, what is the rule by which the output is constructed?\n",
"I think another answer is in order, to respond to this:\n\nI've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet.\n\nThere is a pattern.\nSuppose you have just two lists to combine. You can find all the combinations by making a grid.\n black blue\n +------------+------------+\ncoat | black coat | blue coat |\n +------------+------------+\nhat | black hat | blue hat |\n +------------+------------+\n\nAs you can see, there are 2*2 combinations. If there were 30 colors and 14 kinds of clothing, you would have 30 * 14 = 420 combinations.\nThe pattern continues as you add more lists. Instead of a 2-dimensional rectangle, you get an 3-dimensional array of boxes, or ultimately an n-dimensional hyperrectangle. Regardless, the total number of combinations is always the product of the lengths of all the lists.\nIf you know how many lists you have, nested loops are a natural way to make all combinations.\nfor color in colors:\n for kind in kinds:\n print color, kind # \"black coat\", \"black hat\", etc.\n\nIf the lists are in dictionary order to start with, and there are no duplicates, the output will also be in dictionary order.\n",
"I'm assuming that you want the Cartesian product - all possible lists created by choosing exactly one element from each list. You can implement it recursively, like this:\ndef cartesian_product(l):\n if l:\n for b in cartesian_product(l[1:]):\n for a in l[0]:\n yield [a] + b\n else:\n yield [] \n\nl = [\n [ 'a', 'b' ],\n [ 'c', 'd', 'e' ],\n [ 'f', 'g' ],\n]\n\nfor x in cartesian_product(l):\n print x\n\nUpdate: ~unutbu's suggestion of itertools.product is better, but I'll leave this here anyway.\n",
"Since you need a cartesian product, use that of itertools !\n>>> import itertools\n>>> v = [1, 'a']\n>>> w = [1, 'b']\n>>> x = [1, 'c']\n>>> y = [1, 'd']\n>>> z = [1, 'e']\n\n>>> p = [''.join(str(x) for x in c) for c in itertools.product(v,w,x,y,z)]\n>>> p\n['11111', '1111e', '111d1', '111de', '11c11', '11c1e', '11cd1', '11cde', '1b111'\n, '1b11e', '1b1d1', '1b1de', '1bc11', '1bc1e', '1bcd1', '1bcde', 'a1111', 'a111e\n', 'a11d1', 'a11de', 'a1c11', 'a1c1e', 'a1cd1', 'a1cde', 'ab111', 'ab11e', 'ab1d\n1', 'ab1de', 'abc11', 'abc1e', 'abcd1', 'abcde']\n>>>\n\n",
"Might that do the trick?\ndef getAllCombinations(listOfLists):\n if len(listOfLists) == 1:\n return [str(x) for x in listOfLists[0]]\n\n result = set()\n head, tail = listOfLists[0], listOfLists[1:]\n\n tailCombs = getAllCombinations(tail)\n for elem in head:\n for tc in tailCombs:\n result.add(str(elem) + tc)\n return result\n\nv = [1, 'a']\nw = [1, 'b']\nx = [1, 'c']\ny = [1, 'd']\nz = [1, 'e']\n\n>>> print getAllCombinations([v, w, x, y, z])\nset(['111de', 'abc11', 'a1c1e', 'a111e', '11c11', 'ab11e', '1bc11', 'ab1d1', 'a1cd1', '1b1de', 'a11d1', '11111', '1b111', '11cd1', 'abcd1', '1bcde', 'ab111', '1bc1e', 'abc1e', '111d1', 'a1111', '11c1e', 'a1c11', '11cde', '1b11e', '1bcd1', 'abcde', 'a1cde', '1b1d1', 'a11de', 'ab1de', '1111e'])\n\n",
"You're looking for the Cartesian product. In Python, if you want tuples:\nc = [(x, y) for x in a for y in b]\nr = [(vv, ww, xx, yy, zz)\n for vv in v for ww in w for xx in x for yy in y for zz in z]\n\n"
] |
[
8,
2,
2,
1,
1,
1,
0
] |
[] |
[] |
[
"algorithm",
"php",
"python"
] |
stackoverflow_0001764464_algorithm_php_python.txt
|
Q:
List implemented using an inorder binary tree
For the new computer science assignment we are to implement a list/array using an inorder binary tree. I would just like a suggestion rather than a solution.
The idea is having a binary tree that has its nodes accessible via indexes, e.g.
t = ListTree()
t.insert(2,0) # 1st argument is the value, 2nd the index to insert at
t.get(0) # returns 2
The Node class that the values are stored in is not modifiable but has a property size which contains the total number of children below, along with left, right and value that point to children and store the value accordingly.
My chief problem at the moment keeping track of the index - as we're not allowed to store the index of the node in the node itself I must rely on traversing to track it. As I always start with the left node when traversing I haven't yet thought of a way to recursively figure out what index we are currently at.
Any suggestions would be welcome.
Thanks!
A:
You really wouldn't want to store it on the node itself, because then the index would have to be updated on inserts for all nodes with index less than insert index. I think the real question is how to do an in-order traversal. Try having your recursive function return the number of nodes to its left.
A:
I don't think you want to store the index, rather just the size of each subtree. For insance, if you wanted to look up the 10th element in the list, and the left and right subrees had 7 elements each, you would know that the root is the eight element (since it's in-order binary), and the first element of the right subree is 9th. armed with this knowledge, you would recurse into the right subree, looking for the 2nd element.
HTH
A:
Well, a node in a binary tree cannot have a value and an index. They can have multiple pieces of data but the tree can only be keyed/built on one.
Maybe your assignment wants you to use the index value as the key to the tree and attach the value to the node for quick retrieval of the value given an index.
A:
Does the tree have to be balanced? Does the algorithm need to be efficient?
If not, then the simplest thing to do is make a tree in which all the left children are null, i.e., a tree that devolves to a linked list.
To insert, recursively look go to the right child, and then update the size of the node on the way back out. Something like (pseudocode)
function insert(node, value, index, depth)
if depth < index
create the rightchild if necessary
insert( rightchild, value, index, depth + 1)
if depth == size
node.value = value
node.size = rightchild.size + 1
After you have this working, you can modify it to be more balanced. When increasing the length of the list, add nodes to the left or right child nodes depending on which currently has the least, and update the size on the way out of the recursion.
To generalize to be more efficient, you need to work on the index in terms of its binary representation.
For example, and empty list has one node, without children with value null and size 0.
Say you want to insert "hello" at index 1034. Then you want to end up with a tree whose root has two children, with sizes 1024 and 10. The left child has no actual children, but the right node has a right child of its own of size 2. (The left of size 8 is implied.) That node in turn, has one right child of size 0, with the value "hello". (This list has a 1-based index, but a 0-based index is similar.)
So you need to recursively break down the index into its binary parts, and add nodes as necessary. When searching the list, you need to take care when traversing a node with null children
A:
A very easy solution is to do GetFirst() to get the first node of the tree (this is simply finding the leftmost node of the tree). If your index N is 0, return the first node. Otherwise, call GetNodeNext() N times to get the appropriate node. This isn't super efficient though since accessing a node by index takes O(N Lg N) time.
Node *Tree::GetFirstNode()
{
Node *pN,*child;
pN=GetRootNode();
while(NOTNIL(child=GetNodeLeft(pN)))
{
pN=child;
}
return(pN);
}
Node *Tree::GetNodeNext(Node *pNode)
{
Node *temp;
temp=GetNodeRight(pNode);
if(NOTNIL(temp))
{
pNode=temp;
temp=GetNodeLeft(pNode);
while(NOTNIL(temp))
{
pNode=temp;
temp=GetNodeLeft(pNode);
}
return(pNode);
}
else
{
temp=GetNodeParent(pNode);
while( (NOTNIL(temp)) && (GetNodeRight(temp)==pNode) )
{
pNode=temp;
temp=GetNodeParent(pNode);
}
return(temp);
}
}
|
List implemented using an inorder binary tree
|
For the new computer science assignment we are to implement a list/array using an inorder binary tree. I would just like a suggestion rather than a solution.
The idea is having a binary tree that has its nodes accessible via indexes, e.g.
t = ListTree()
t.insert(2,0) # 1st argument is the value, 2nd the index to insert at
t.get(0) # returns 2
The Node class that the values are stored in is not modifiable but has a property size which contains the total number of children below, along with left, right and value that point to children and store the value accordingly.
My chief problem at the moment keeping track of the index - as we're not allowed to store the index of the node in the node itself I must rely on traversing to track it. As I always start with the left node when traversing I haven't yet thought of a way to recursively figure out what index we are currently at.
Any suggestions would be welcome.
Thanks!
|
[
"You really wouldn't want to store it on the node itself, because then the index would have to be updated on inserts for all nodes with index less than insert index. I think the real question is how to do an in-order traversal. Try having your recursive function return the number of nodes to its left. \n",
"I don't think you want to store the index, rather just the size of each subtree. For insance, if you wanted to look up the 10th element in the list, and the left and right subrees had 7 elements each, you would know that the root is the eight element (since it's in-order binary), and the first element of the right subree is 9th. armed with this knowledge, you would recurse into the right subree, looking for the 2nd element.\nHTH\n",
"Well, a node in a binary tree cannot have a value and an index. They can have multiple pieces of data but the tree can only be keyed/built on one.\nMaybe your assignment wants you to use the index value as the key to the tree and attach the value to the node for quick retrieval of the value given an index.\n",
"Does the tree have to be balanced? Does the algorithm need to be efficient?\nIf not, then the simplest thing to do is make a tree in which all the left children are null, i.e., a tree that devolves to a linked list.\nTo insert, recursively look go to the right child, and then update the size of the node on the way back out. Something like (pseudocode)\nfunction insert(node, value, index, depth)\n if depth < index\n create the rightchild if necessary\n insert( rightchild, value, index, depth + 1)\n if depth == size\n node.value = value\n node.size = rightchild.size + 1\n\nAfter you have this working, you can modify it to be more balanced. When increasing the length of the list, add nodes to the left or right child nodes depending on which currently has the least, and update the size on the way out of the recursion.\nTo generalize to be more efficient, you need to work on the index in terms of its binary representation.\nFor example, and empty list has one node, without children with value null and size 0.\nSay you want to insert \"hello\" at index 1034. Then you want to end up with a tree whose root has two children, with sizes 1024 and 10. The left child has no actual children, but the right node has a right child of its own of size 2. (The left of size 8 is implied.) That node in turn, has one right child of size 0, with the value \"hello\". (This list has a 1-based index, but a 0-based index is similar.)\nSo you need to recursively break down the index into its binary parts, and add nodes as necessary. When searching the list, you need to take care when traversing a node with null children\n",
"A very easy solution is to do GetFirst() to get the first node of the tree (this is simply finding the leftmost node of the tree). If your index N is 0, return the first node. Otherwise, call GetNodeNext() N times to get the appropriate node. This isn't super efficient though since accessing a node by index takes O(N Lg N) time.\nNode *Tree::GetFirstNode()\n{\n Node *pN,*child;\n pN=GetRootNode();\n while(NOTNIL(child=GetNodeLeft(pN)))\n {\n pN=child;\n }\n return(pN);\n}\n\n\nNode *Tree::GetNodeNext(Node *pNode)\n{\n Node *temp;\n\n temp=GetNodeRight(pNode);\n if(NOTNIL(temp))\n {\n pNode=temp;\n temp=GetNodeLeft(pNode);\n while(NOTNIL(temp))\n {\n pNode=temp;\n temp=GetNodeLeft(pNode);\n }\n return(pNode);\n }\n else\n {\n temp=GetNodeParent(pNode);\n while( (NOTNIL(temp)) && (GetNodeRight(temp)==pNode) )\n {\n pNode=temp;\n temp=GetNodeParent(pNode);\n }\n return(temp);\n }\n}\n\n"
] |
[
1,
1,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"binary_tree",
"python"
] |
stackoverflow_0001654947_algorithm_binary_tree_python.txt
|
Q:
python multiprocessing db access is very slow
I have GUI that will interact with a postgres database, using psycopg2. I have db connection in a multiprocessing process, and send SQL via a multiprocessing queue, and receive via another queue.
The problem is that the speed is very very slow. A simple select * from a small table (30 rows) can be 1/10th of a second, or can take over one second.
Does any one have any clues as to why it's so slow?
New Information: It works fine on winxp, exact same code, so the intermittent delay is only happening on my linux box (ubuntu 9.10)
More info: Having stubbed out the select it appears it's not the problem.
Here is the main part of the db class.
class DataBase(multiprocessing.Process):
def __init__(self, conn_data, in_queue, out_queue):
multiprocessing.Process.__init__(self)
self.in_queue = in_queue
self.out_queue = out_queue
self.conn_data = conn_data
self.all_ok = True
def run(self):
proc_name = self.name
self.conn = self.get_connection(self.conn_data)
print("Running ", self.name)
while True:
next_job = self.in_queue.get()
print("Next Job: ",next_job)
if next_job is None:
# Stop Process
break
SQL = next_job[0]
callback = next_job[1]
result = self.execute(SQL)
self.out_queue.put((result, callback))
print("Closing connection ", self.name)
self.conn.close()
return
And in the GUI I have this:
def recieve_data(self):
"Revived data on the queue. Data is a tuple of the actual data and a calback name."
if self.recieve_queue.empty() == False:
data = self.recieve_queue.get()
callback_name = data[1]
try:
callback = getattr(self, callback_name)
callback(data[0])
except AttributeError as e:
util.error_ui(err = e)
self.check_data_timeout = None
return False # Stop checking.
return True # Have the main loop keep checking for data.
def request_data(self, SQL, callback):
self.send_queue.put((SQL, callback))
self.check_data_timeout = gobject.timeout_add(50, self.recieve_data) # Poll the database recieved_queue
A:
Try to isolate what is taking the time - is it the multiprocessing or the database? For example try calling the database directly from the python interactive shell - the ipython shell has 'time' and 'timeit' commands for measuring things like this. Alternatively stub out DataBase.execute to return canned values, and see what difference it makes.
What about gobject.timeout_add? What is that doing? It is possible that the delay is in there rather than the database or the multiprocessing code.
A:
Have you tried opening new database connection for each of your processes? It seems to me that you are simply adding overhead trying to reuse them in different processes.
Also, I'm not sure (your sample is to small to deduce) but it looks like you're opening new DB connection for each query... Are you closing connection with self.conn.close() after each query? You're supposed to have one long-lasting connection.
A:
It seems to be problems or a bug specific to Ubuntu 9.10
All works fine on Ubuntu 9.04 and win32, even on win32 on a virtual machine hosted on Ubuntu 9.10.
Thanks for all the advice.
|
python multiprocessing db access is very slow
|
I have GUI that will interact with a postgres database, using psycopg2. I have db connection in a multiprocessing process, and send SQL via a multiprocessing queue, and receive via another queue.
The problem is that the speed is very very slow. A simple select * from a small table (30 rows) can be 1/10th of a second, or can take over one second.
Does any one have any clues as to why it's so slow?
New Information: It works fine on winxp, exact same code, so the intermittent delay is only happening on my linux box (ubuntu 9.10)
More info: Having stubbed out the select it appears it's not the problem.
Here is the main part of the db class.
class DataBase(multiprocessing.Process):
def __init__(self, conn_data, in_queue, out_queue):
multiprocessing.Process.__init__(self)
self.in_queue = in_queue
self.out_queue = out_queue
self.conn_data = conn_data
self.all_ok = True
def run(self):
proc_name = self.name
self.conn = self.get_connection(self.conn_data)
print("Running ", self.name)
while True:
next_job = self.in_queue.get()
print("Next Job: ",next_job)
if next_job is None:
# Stop Process
break
SQL = next_job[0]
callback = next_job[1]
result = self.execute(SQL)
self.out_queue.put((result, callback))
print("Closing connection ", self.name)
self.conn.close()
return
And in the GUI I have this:
def recieve_data(self):
"Revived data on the queue. Data is a tuple of the actual data and a calback name."
if self.recieve_queue.empty() == False:
data = self.recieve_queue.get()
callback_name = data[1]
try:
callback = getattr(self, callback_name)
callback(data[0])
except AttributeError as e:
util.error_ui(err = e)
self.check_data_timeout = None
return False # Stop checking.
return True # Have the main loop keep checking for data.
def request_data(self, SQL, callback):
self.send_queue.put((SQL, callback))
self.check_data_timeout = gobject.timeout_add(50, self.recieve_data) # Poll the database recieved_queue
|
[
"Try to isolate what is taking the time - is it the multiprocessing or the database? For example try calling the database directly from the python interactive shell - the ipython shell has 'time' and 'timeit' commands for measuring things like this. Alternatively stub out DataBase.execute to return canned values, and see what difference it makes.\nWhat about gobject.timeout_add? What is that doing? It is possible that the delay is in there rather than the database or the multiprocessing code.\n",
"Have you tried opening new database connection for each of your processes? It seems to me that you are simply adding overhead trying to reuse them in different processes.\nAlso, I'm not sure (your sample is to small to deduce) but it looks like you're opening new DB connection for each query... Are you closing connection with self.conn.close() after each query? You're supposed to have one long-lasting connection.\n",
"It seems to be problems or a bug specific to Ubuntu 9.10 \nAll works fine on Ubuntu 9.04 and win32, even on win32 on a virtual machine hosted on Ubuntu 9.10.\nThanks for all the advice.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"multiprocessing",
"python"
] |
stackoverflow_0001754438_multiprocessing_python.txt
|
Q:
To have two Pg queries in one Python method
Thank you for Denis who solves the first bug!
How can you have two Postgres queries in one Python method?
Example where the 2nd query is not run
def comp_func(pgmasi):
pgmasi.query("""CREATE TABLE courses (
course_id SERIAL PRIMARY KEY)""")
pgmasi.query("""CREATE TABLE files ( # not executed for some unknown reason
file_id SERIAL PRIMARY KEY""")
A:
Probably you missed closing parentheses in the line as error message says:
pgmasi.query("INSERT INTO files('binf','file_name') VALUES(file,file_name)"
|
To have two Pg queries in one Python method
|
Thank you for Denis who solves the first bug!
How can you have two Postgres queries in one Python method?
Example where the 2nd query is not run
def comp_func(pgmasi):
pgmasi.query("""CREATE TABLE courses (
course_id SERIAL PRIMARY KEY)""")
pgmasi.query("""CREATE TABLE files ( # not executed for some unknown reason
file_id SERIAL PRIMARY KEY""")
|
[
"Probably you missed closing parentheses in the line as error message says:\npgmasi.query(\"INSERT INTO files('binf','file_name') VALUES(file,file_name)\"\n\n"
] |
[
2
] |
[] |
[] |
[
"postgresql",
"python"
] |
stackoverflow_0001765630_postgresql_python.txt
|
Q:
Python: Binding method
In following example I am trying to bind a method object via types.MethodType(...). It does not seem to work. Any suggestions? Thanks in advance.
import types
class Base:
def payload(self, *args):
print "Base:payload"
class Drvd(Base):
def iter(self, func):
derived_func = types.MethodType(func, self, Drvd) # bind
print "drvd_func:", derived_func
derived_func() # result: calls Base:payload
# expected:calls Drvd:payload; why???
def payload(self, *args):
print "Drvd:payload"
derived = Drvd()
base_func = Base.payload
print "base_func:", base_func
derived.iter(base_func) # pass unbound method object
The output shows:
base_func: <unbound method Base.payload>
drvd_func: <bound method Drvd.payload of <main.Drvd instance at 0x00B51648>>
Base:payload
A:
You're specifically requesting the use of the underlying function (im_func) of Base.payload, with a fake im_class of Drvd. Add after the existing print in iter:
print "w/class:", derived_func.im_class
print "w/func:", derived_func.im_func
and you'll see the total output as:
$ python bou.py
base_func: <unbound method Base.payload>
drvd_func: <bound method Drvd.payload of <__main__.Drvd instance at 0x24a918>>
w/class: __main__.Drvd
w/func: <unbound method Base.payload>
Base:payload
i.e., as you've asked, the underlying code being used is indeed Base.payload -- which is also what you observe in the call.
From Base.payload there is no direct way to get to Drvd.payload except by getting the name and using it to do a getattr on self (a Drvd instance), or equivalent.
A:
Because you passed Base's payload (not Drvd's) to iter!
Hint:
print "%s: Base:payload"%repr(self)
Kudos for creating an accursed chimera of a thing, though!
A:
I don't really understand what you're trying to do - but to me it's working as I'd expect. You are binding Base.payload to Drvd - from your print out you can see it is binding correctly to your Drvd instance. I'm not sure why you are then expecting it to call Drvd.payload - you have bound the function object Base.payload. It is always going to be that function.
[edit: just to add - it might be helpful if you say what your trying to do in general terms. What you're doing at the moment doesn't make much sense - Python has inheritence so if you want to override the payload method you can just do it - you don't need to do any manual binding.]
|
Python: Binding method
|
In following example I am trying to bind a method object via types.MethodType(...). It does not seem to work. Any suggestions? Thanks in advance.
import types
class Base:
def payload(self, *args):
print "Base:payload"
class Drvd(Base):
def iter(self, func):
derived_func = types.MethodType(func, self, Drvd) # bind
print "drvd_func:", derived_func
derived_func() # result: calls Base:payload
# expected:calls Drvd:payload; why???
def payload(self, *args):
print "Drvd:payload"
derived = Drvd()
base_func = Base.payload
print "base_func:", base_func
derived.iter(base_func) # pass unbound method object
The output shows:
base_func: <unbound method Base.payload>
drvd_func: <bound method Drvd.payload of <main.Drvd instance at 0x00B51648>>
Base:payload
|
[
"You're specifically requesting the use of the underlying function (im_func) of Base.payload, with a fake im_class of Drvd. Add after the existing print in iter:\n print \"w/class:\", derived_func.im_class\n print \"w/func:\", derived_func.im_func\n\nand you'll see the total output as:\n$ python bou.py \nbase_func: <unbound method Base.payload>\ndrvd_func: <bound method Drvd.payload of <__main__.Drvd instance at 0x24a918>>\nw/class: __main__.Drvd\nw/func: <unbound method Base.payload>\nBase:payload\n\ni.e., as you've asked, the underlying code being used is indeed Base.payload -- which is also what you observe in the call.\nFrom Base.payload there is no direct way to get to Drvd.payload except by getting the name and using it to do a getattr on self (a Drvd instance), or equivalent.\n",
"Because you passed Base's payload (not Drvd's) to iter!\nHint:\nprint \"%s: Base:payload\"%repr(self)\n\nKudos for creating an accursed chimera of a thing, though!\n",
"I don't really understand what you're trying to do - but to me it's working as I'd expect. You are binding Base.payload to Drvd - from your print out you can see it is binding correctly to your Drvd instance. I'm not sure why you are then expecting it to call Drvd.payload - you have bound the function object Base.payload. It is always going to be that function.\n[edit: just to add - it might be helpful if you say what your trying to do in general terms. What you're doing at the moment doesn't make much sense - Python has inheritence so if you want to override the payload method you can just do it - you don't need to do any manual binding.]\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"bind",
"binding",
"methods",
"python",
"types"
] |
stackoverflow_0001765922_bind_binding_methods_python_types.txt
|
Q:
What are the differences in variable scoping between Python and Scheme?
Refering to Variable Scoping.
I'm trying to figure out what are the differences between those 2.
For example, Anonymous functions in a scheme function has access to the variables local to that function. Does python have this?
Thanks!
A:
In Python variable scope can be either global or function. In Scheme, the scope can be any block.
For example, in Scheme you could define a variable inside a loop, and it wouldn't be accessible from outside the loop. In Python, the scope being the whole function, this variable would 'leak' out of the loop into the rest of the function.
About your specific question: note that anonymous (lambda) functions in Python are horribly limited (just a single expression, no if/then statements, loops, etc.), so you usually define complete (named) inner functions. In this case the scope rules are similar to Scheme: the inner function can access the outer function's variables (creating a closure), and the outer function can't access variables defined inside the inner function.
In short: lexical scoping and closures work as expected; just remember that the scoping granularity is per function, not per block.
A:
Subtle question. Yes, Python lambdas close on variables in the enclosing function. Both languages have lexical scoping. But the details are quite different.
In Scheme, you usually introduce a variable with (let) or (letrec) or (lambda) and it's pretty explicit what the scope of the variable is. Also, whenever a variable is in scope, you can assign to it using (set!).
In Python, assigning to a name implicitly makes a local variable whose scope is the entire function. So even though you can access outer variables by name, if you want to assign to a variable in an outer scope, you must use a global declaration (or in Python 3.0 nonlocal).
Python also has classes. Class members aren't really lexical variables; methods do not close over them.
>>> def top(x):
... class C:
... x = 1 # foo does not close on this 'x'.
... def foo(self):
... return x # this refers to the argument of top
... return C().foo()
...
>>> top(2)
2
See the Python language reference for more: http://docs.python.org/reference/executionmodel.html#naming
A:
Yes, Python has the ability to access variables that are local to an anonymous function (in Python, this is called a lambda function) within that function.
I'm not entirely sure if that answered you question, so if it didn't, please post some more detail
A:
Scheme and Python are both lexically scoped, in the way that you seem to be asking.
def make_adder(n):
when = datetime.now()
def adder(k):
print "The adder you created at %s has been called!" % when
return k + n
return adder
|
What are the differences in variable scoping between Python and Scheme?
|
Refering to Variable Scoping.
I'm trying to figure out what are the differences between those 2.
For example, Anonymous functions in a scheme function has access to the variables local to that function. Does python have this?
Thanks!
|
[
"In Python variable scope can be either global or function. In Scheme, the scope can be any block.\nFor example, in Scheme you could define a variable inside a loop, and it wouldn't be accessible from outside the loop. In Python, the scope being the whole function, this variable would 'leak' out of the loop into the rest of the function.\nAbout your specific question: note that anonymous (lambda) functions in Python are horribly limited (just a single expression, no if/then statements, loops, etc.), so you usually define complete (named) inner functions. In this case the scope rules are similar to Scheme: the inner function can access the outer function's variables (creating a closure), and the outer function can't access variables defined inside the inner function.\nIn short: lexical scoping and closures work as expected; just remember that the scoping granularity is per function, not per block.\n",
"Subtle question. Yes, Python lambdas close on variables in the enclosing function. Both languages have lexical scoping. But the details are quite different.\nIn Scheme, you usually introduce a variable with (let) or (letrec) or (lambda) and it's pretty explicit what the scope of the variable is. Also, whenever a variable is in scope, you can assign to it using (set!).\nIn Python, assigning to a name implicitly makes a local variable whose scope is the entire function. So even though you can access outer variables by name, if you want to assign to a variable in an outer scope, you must use a global declaration (or in Python 3.0 nonlocal).\nPython also has classes. Class members aren't really lexical variables; methods do not close over them.\n>>> def top(x):\n... class C:\n... x = 1 # foo does not close on this 'x'.\n... def foo(self):\n... return x # this refers to the argument of top\n... return C().foo()\n... \n>>> top(2)\n2\n\nSee the Python language reference for more: http://docs.python.org/reference/executionmodel.html#naming\n",
"Yes, Python has the ability to access variables that are local to an anonymous function (in Python, this is called a lambda function) within that function.\nI'm not entirely sure if that answered you question, so if it didn't, please post some more detail\n",
"Scheme and Python are both lexically scoped, in the way that you seem to be asking.\ndef make_adder(n):\n when = datetime.now()\n def adder(k):\n print \"The adder you created at %s has been called!\" % when\n return k + n\n return adder\n\n"
] |
[
4,
3,
0,
0
] |
[] |
[] |
[
"python",
"scheme"
] |
stackoverflow_0001765560_python_scheme.txt
|
Q:
Pygame: Sprite changing due to direction of movement
I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make changing sprites for movement of up down left and right and how to cycle through animating images.
I've spent all today trying to get a sprite to display and be able to move around with up down left and right. But because of the simple script it uses a static image and refuses to change.
Can anyone give me some knowledge on how to change the sprites. Or send me to a tutorial that does?
Every reference and person experimenting with it ha always been using generated shapes so I'm never able to work with them.
Any help is very appreciated.
Added: before figuring out how to place complex animations in my scene I'd like to know how I can make my 'player' change to unmoving images in regards to my pressing up down left or right. maybe diagonal if people know its something really complicated.
Add: This is what I've put together so far. http://animania1.ca/ShowFriends/dev/dirmove.rar would there be a possibility of making the direction/action set the column of the action and have the little column setting code also make it cycle down in a loop to do the animation? (or would that be a gross miss use of efficiency?)
A:
Here is a dumb example which alernates between two first images of the spritesheet when you press left/right:
import pygame
quit = False
pygame.init()
display = pygame.display.set_mode((640,480))
sprite_sheet = pygame.image.load('sprite.bmp').convert()
# by default, display the first sprite
image_number = 0
while quit == False:
event = pygame.event.poll()
no_more_events = True if event == pygame.NOEVENT else False
# handle events (update game state)
while no_more_events == False:
if event.type == pygame.QUIT:
quit = True
break
elif event.type == pygame.NOEVENT:
no_more_events = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
image_number = 0
elif event.key == pygame.K_RIGHT:
image_number = 1
event = pygame.event.poll()
if quit == False:
# redraw the screen
display.fill(pygame.Color('white'))
area = pygame.Rect(image_number * 100, 0, 100, 150)
display.blit(sprite_sheet, (0,0), area)
pygame.display.flip()
I've never really used Pygame before so maybe this code shoudln't really be taken as an example. I hope it shows the basics though.
To be more complete I should wait some time before updating, e.g. control that I update only 60 times per second.
It would also be handy to write a sprite class which would simplify your work. You would pass the size of a sprite frame in the constructor, and you'd have methodes like update() and draw() which would automatically do the work of selecting the next frame, blitting the sprite and so on.
Pygame seems to provide a base class for that purpose: link text.
A:
dude the only thing you have to do is offcourse
import pygame and all the other stuff needed
type code and stuff..........then
when it comes to you making a spri
class .your class nam here. (pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.init(self)
self.image=pygame.image.load(your image and path)
self.rect=self.image.get_rect()
x=0
y=0
# any thing else is what you want like posistion and other variables
def update(self):
self.rect.move_ip((x,y))
and thats it!!!! but thats not the end. if you do this you will ony have made the sprite
to move it you need
A:
I don't know much about Pygame, but I've used SDL (on which Pygame is based).
If you use Surface.blit(): link text
You can use the optional area argument to select which part of the surface to draw.
So if you put all the images that are part of the animation inside a single file, you can select which image will be drawn.
It's called "clipping".
I guess you will have a game loop that will update the game state (changing the current image of the sprite if necessary), then draw the sprites using their state.
|
Pygame: Sprite changing due to direction of movement
|
I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make changing sprites for movement of up down left and right and how to cycle through animating images.
I've spent all today trying to get a sprite to display and be able to move around with up down left and right. But because of the simple script it uses a static image and refuses to change.
Can anyone give me some knowledge on how to change the sprites. Or send me to a tutorial that does?
Every reference and person experimenting with it ha always been using generated shapes so I'm never able to work with them.
Any help is very appreciated.
Added: before figuring out how to place complex animations in my scene I'd like to know how I can make my 'player' change to unmoving images in regards to my pressing up down left or right. maybe diagonal if people know its something really complicated.
Add: This is what I've put together so far. http://animania1.ca/ShowFriends/dev/dirmove.rar would there be a possibility of making the direction/action set the column of the action and have the little column setting code also make it cycle down in a loop to do the animation? (or would that be a gross miss use of efficiency?)
|
[
"Here is a dumb example which alernates between two first images of the spritesheet when you press left/right:\nimport pygame\n\nquit = False\npygame.init()\ndisplay = pygame.display.set_mode((640,480))\nsprite_sheet = pygame.image.load('sprite.bmp').convert()\n\n# by default, display the first sprite\nimage_number = 0\n\nwhile quit == False:\n event = pygame.event.poll()\n no_more_events = True if event == pygame.NOEVENT else False\n\n # handle events (update game state)\n while no_more_events == False:\n if event.type == pygame.QUIT:\n quit = True\n break\n elif event.type == pygame.NOEVENT:\n no_more_events = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n image_number = 0\n elif event.key == pygame.K_RIGHT:\n image_number = 1\n\n event = pygame.event.poll()\n\n if quit == False:\n # redraw the screen\n display.fill(pygame.Color('white'))\n area = pygame.Rect(image_number * 100, 0, 100, 150)\n display.blit(sprite_sheet, (0,0), area)\n pygame.display.flip()\n\nI've never really used Pygame before so maybe this code shoudln't really be taken as an example. I hope it shows the basics though.\nTo be more complete I should wait some time before updating, e.g. control that I update only 60 times per second.\nIt would also be handy to write a sprite class which would simplify your work. You would pass the size of a sprite frame in the constructor, and you'd have methodes like update() and draw() which would automatically do the work of selecting the next frame, blitting the sprite and so on.\nPygame seems to provide a base class for that purpose: link text.\n",
"dude the only thing you have to do is offcourse \nimport pygame and all the other stuff needed\ntype code and stuff..........then\nwhen it comes to you making a spri\nclass .your class nam here. (pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.init(self)\n self.image=pygame.image.load(your image and path)\n self.rect=self.image.get_rect()\n x=0\n y=0\n\n # any thing else is what you want like posistion and other variables\n\n def update(self):\n self.rect.move_ip((x,y))\n\nand thats it!!!! but thats not the end. if you do this you will ony have made the sprite\nto move it you need\n",
"I don't know much about Pygame, but I've used SDL (on which Pygame is based).\nIf you use Surface.blit(): link text\nYou can use the optional area argument to select which part of the surface to draw.\nSo if you put all the images that are part of the animation inside a single file, you can select which image will be drawn.\nIt's called \"clipping\".\nI guess you will have a game loop that will update the game state (changing the current image of the sprite if necessary), then draw the sprites using their state.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"2d",
"pygame",
"python",
"sprite"
] |
stackoverflow_0000733916_2d_pygame_python_sprite.txt
|
Q:
Python, removing the \'s before getting them processed
I'm making a program that asks for a path, and Windows' paths contain backslashes, which can be interpreted as an escape sequence by python if the letter right next is the wrong one. I tried string.replace() but it doesn't work as these backslashes get transformed into escape sequences before having the replace function executed.
Is there a way to remove them and maybe make them / instead of \?
A:
No, the backslash is not interpreted as an escape sequence except in Python source code. Unless you're eval()ing the path, which would be Wrong, I'm not sure why you'd have a problem.
A:
If you are asking for the user for input, then a \ will go into a string as a \ correctly. Only if you then eval the user's string in some way will the backslash count as an escape char. You really only need to worry about escaping when you are writing strings within the code.
A:
Use double \
str = 'c:\\dir\\file.txt'
print str.replace('\\','/')
print str
here us the output
c:/dir/file.txt
c:\dir\file.txt
|
Python, removing the \'s before getting them processed
|
I'm making a program that asks for a path, and Windows' paths contain backslashes, which can be interpreted as an escape sequence by python if the letter right next is the wrong one. I tried string.replace() but it doesn't work as these backslashes get transformed into escape sequences before having the replace function executed.
Is there a way to remove them and maybe make them / instead of \?
|
[
"No, the backslash is not interpreted as an escape sequence except in Python source code. Unless you're eval()ing the path, which would be Wrong, I'm not sure why you'd have a problem.\n",
"If you are asking for the user for input, then a \\ will go into a string as a \\ correctly. Only if you then eval the user's string in some way will the backslash count as an escape char. You really only need to worry about escaping when you are writing strings within the code.\n",
"Use double \\\nstr = 'c:\\\\dir\\\\file.txt'\n\nprint str.replace('\\\\','/')\nprint str\n\nhere us the output\nc:/dir/file.txt\nc:\\dir\\file.txt\n\n"
] |
[
6,
3,
3
] |
[] |
[] |
[
"backslash",
"escaping",
"python"
] |
stackoverflow_0001766510_backslash_escaping_python.txt
|
Q:
How to omit using python coverage lib?
I would like to omit some module that are in some particular directory : eggs and bin
coverage -r -i --omit=/usr/lib/,/usr/share/,eggs,bin
Name Stmts Exec Cover
-----------------------------------------------------------------------------------------
bin/test 5 5 100%
eggs/BeautifulSoup-3.0.7a-py2.6.egg/BeautifulSoup 1008 463 45%
eggs/Django-1.0.2_final-py2.6.egg/django/__init__ 15 12 80%
I have also try several variant of this without luck :
coverage -r -i --omit=/usr/lib/,/usr/share/,`pwd`/eggs,`pwd`/bin
or
coverage -r -i --omit=/usr/lib/,/usr/share/,django,BeautifulSoup
or
coverage -r -i --omit=/usr/lib/,/usr/share/,<absolute path>/eggs
It would be great if someone has a tip to get this working.
A:
To tell you the truth, I think this might just be a bug in coverage.py. I'll look into it soon.
UPDATED: OK, I've fixed this bug (I hope), and posted new kits: Coverage.py 3.2b2. Please let me know if it still is no good.
|
How to omit using python coverage lib?
|
I would like to omit some module that are in some particular directory : eggs and bin
coverage -r -i --omit=/usr/lib/,/usr/share/,eggs,bin
Name Stmts Exec Cover
-----------------------------------------------------------------------------------------
bin/test 5 5 100%
eggs/BeautifulSoup-3.0.7a-py2.6.egg/BeautifulSoup 1008 463 45%
eggs/Django-1.0.2_final-py2.6.egg/django/__init__ 15 12 80%
I have also try several variant of this without luck :
coverage -r -i --omit=/usr/lib/,/usr/share/,`pwd`/eggs,`pwd`/bin
or
coverage -r -i --omit=/usr/lib/,/usr/share/,django,BeautifulSoup
or
coverage -r -i --omit=/usr/lib/,/usr/share/,<absolute path>/eggs
It would be great if someone has a tip to get this working.
|
[
"To tell you the truth, I think this might just be a bug in coverage.py. I'll look into it soon.\nUPDATED: OK, I've fixed this bug (I hope), and posted new kits: Coverage.py 3.2b2. Please let me know if it still is no good.\n"
] |
[
6
] |
[] |
[] |
[
"code_coverage",
"coverage.py",
"python"
] |
stackoverflow_0001764806_code_coverage_coverage.py_python.txt
|
Q:
Automatic string length in recarray
If I create a recarray in this way:
In [29]: np.rec.fromrecords([(1,'hello'),(2,'world')],names=['a','b'])
The result looks fine:
Out[29]:
rec.array([(1, 'hello'), (2, 'world')],
dtype=[('a', '<i8'), ('b', '|S5')])
But if I want to specify the data types:
In [32]: np.rec.fromrecords([(1,'hello'),(2,'world')],dtype=[('a',np.int8),('b',np.str)])
The string is set to a length of zero:
Out[32]:
rec.array([(1, ''), (2, '')],
dtype=[('a', '|i1'), ('b', '|S0')])
I need to specify datatypes for all numerical types since I care about int8/16/32, etc, but I would like to benefit from the auto string length detection that works if I don't specify datatypes. I tried replacing np.str by None but no luck. I know I can specify '|S5' for example, but I don't know in advance what the string length should be set to.
A:
If you don't need to manipulate the strings as bytes, you may use the object data-type to represent them. This essentially stores a pointer instead of the actual bytes:
In [38]: np.array(data, dtype=[('a', np.uint8), ('b', np.object)])
Out[38]:
array([(1, 'hello'), (2, 'world')],
dtype=[('a', '|u1'), ('b', '|O8')])
Alternatively, Alex's idea would work well:
new_dt = []
# For each field of a given type and alignment, determine
# whether the field is an integer. If so, represent it as a byte.
for f, (T, align) in dt.fields.iteritems():
if np.issubdtype(T, int):
new_dt.append((f, np.uint8))
else:
new_dt.append((f, T))
new_dt = np.dtype(new_dt)
np.array(data, dtype=new_dt)
which should yield
array([(1, 'hello'), (2, 'world')],
dtype=[('f0', '|u1'), ('f1', '|S5')])
A:
I don't know how to ask numpy to determine for you some aspects of a dtype but not others, but couldn't you have, e.g.:
data = [(1,'hello'),(2,'world')]
dlen = max(len(s) for i, s in data)
st = '|S%d' % dlen
np.rec.fromrecords(data, dtype=[('a',np.int8), ('b',st)])
|
Automatic string length in recarray
|
If I create a recarray in this way:
In [29]: np.rec.fromrecords([(1,'hello'),(2,'world')],names=['a','b'])
The result looks fine:
Out[29]:
rec.array([(1, 'hello'), (2, 'world')],
dtype=[('a', '<i8'), ('b', '|S5')])
But if I want to specify the data types:
In [32]: np.rec.fromrecords([(1,'hello'),(2,'world')],dtype=[('a',np.int8),('b',np.str)])
The string is set to a length of zero:
Out[32]:
rec.array([(1, ''), (2, '')],
dtype=[('a', '|i1'), ('b', '|S0')])
I need to specify datatypes for all numerical types since I care about int8/16/32, etc, but I would like to benefit from the auto string length detection that works if I don't specify datatypes. I tried replacing np.str by None but no luck. I know I can specify '|S5' for example, but I don't know in advance what the string length should be set to.
|
[
"If you don't need to manipulate the strings as bytes, you may use the object data-type to represent them. This essentially stores a pointer instead of the actual bytes:\nIn [38]: np.array(data, dtype=[('a', np.uint8), ('b', np.object)])\nOut[38]: \narray([(1, 'hello'), (2, 'world')], \n dtype=[('a', '|u1'), ('b', '|O8')])\n\nAlternatively, Alex's idea would work well:\nnew_dt = []\n\n# For each field of a given type and alignment, determine\n# whether the field is an integer. If so, represent it as a byte.\n\nfor f, (T, align) in dt.fields.iteritems():\n if np.issubdtype(T, int):\n new_dt.append((f, np.uint8))\n else:\n new_dt.append((f, T))\n\nnew_dt = np.dtype(new_dt)\nnp.array(data, dtype=new_dt)\n\nwhich should yield\narray([(1, 'hello'), (2, 'world')], \n dtype=[('f0', '|u1'), ('f1', '|S5')])\n\n",
"I don't know how to ask numpy to determine for you some aspects of a dtype but not others, but couldn't you have, e.g.:\ndata = [(1,'hello'),(2,'world')]\ndlen = max(len(s) for i, s in data)\nst = '|S%d' % dlen\nnp.rec.fromrecords(data, dtype=[('a',np.int8), ('b',st)])\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0001664917_numpy_python.txt
|
Q:
Sphinx templating
I am using Sphinx. I want to template it. So after reading the docs, what I am trying is, in my conf.py,
I put a line like,
templates_path = ['_templates']
and I created a file
_templates/page.html
But this does not override the default template provided by sphinx. What more should I do, and where does this template need to go?
EDIT:
Directory structure from the comments:
conf.py
abc.txt
def.txt
makefile
_templates\
page.html
A:
Be sure you are using the theme name as an explicit directory in your template. e.g.:
{% extends "basic/layout.html" %}
see: HTML Theming Support
A:
The documentation https://www.sphinx-doc.org/en/master/templating.html#working-with-the-builtin-templates
says that the template it's looking for is layout.html.
Perhaps you should use that name.
A:
This works for me. Perhaps you need to force a rebuild for all files with the command sphinx-build -a? Sphinx only compiles HTML files that it detects as having changed. Another option is to just touch all your source files with touch *.rst.
|
Sphinx templating
|
I am using Sphinx. I want to template it. So after reading the docs, what I am trying is, in my conf.py,
I put a line like,
templates_path = ['_templates']
and I created a file
_templates/page.html
But this does not override the default template provided by sphinx. What more should I do, and where does this template need to go?
EDIT:
Directory structure from the comments:
conf.py
abc.txt
def.txt
makefile
_templates\
page.html
|
[
"Be sure you are using the theme name as an explicit directory in your template. e.g.: \n{% extends \"basic/layout.html\" %}\nsee: HTML Theming Support\n",
"The documentation https://www.sphinx-doc.org/en/master/templating.html#working-with-the-builtin-templates\nsays that the template it's looking for is layout.html.\nPerhaps you should use that name.\n",
"This works for me. Perhaps you need to force a rebuild for all files with the command sphinx-build -a? Sphinx only compiles HTML files that it detects as having changed. Another option is to just touch all your source files with touch *.rst.\n"
] |
[
6,
1,
0
] |
[] |
[] |
[
"python",
"python_sphinx",
"templates"
] |
stackoverflow_0001079417_python_python_sphinx_templates.txt
|
Q:
Django ajax formatting convention
What's the correct way to do an ajax request, I've seen people using a returning render_to_string so that they can do all their formatting within python using the template language. eg~
return render_to_string('calendar.html', {
'self' : self,
'month' : self.today.month,})
with this as the javascript:
$('#django_calendar_response').html(response)
But I've also seen people formatting their output within javascript using dom functions such as
return HttpResponse(serializers.serialize("json",
ilst, relations=('user',)), "application/json")
where the javascript is
items_display=function(items){
return LI(null,
A({'class':'userlink',
'href':'/url/user/'+items.fields.user.fields.name},
items.fields.user.fields.name),
is one of these correct and the other wrong? should I format my output in javascript or within python?
A:
I've been using JSON exclusively for AJAX, with simplejson returning whatever data is really easy, it looks like this:
from django.utils import simplejson
reply = simplejson.dumps({'comment_body': formatted_post, 'user_icon': request.user.profile.image.url })
return HttpResponse(reply, mimetype="application/json")
and on the client side, with jquery's .post method handling a json reply is really easy too, you can specify json as your datatype:
$.post("/postcomment/", { body: comment_body },
function(data){
alert(data.comment_body)
}, "json");
I'm not saying this is the best solution, but it's proven to be very robust and easy to handle...
Hope this helps,
Martin
A:
I do both. Sometimes I have short template snippets that I {% include %} in the big page template. It is often more DRY to render these and return the html to insert into the DOM (since the code is already set-up) than to have to write JS to do it (again). Other times, I just generate some JSON and inject that into the DOM.
Shortly, you can mix and match for the situation.
|
Django ajax formatting convention
|
What's the correct way to do an ajax request, I've seen people using a returning render_to_string so that they can do all their formatting within python using the template language. eg~
return render_to_string('calendar.html', {
'self' : self,
'month' : self.today.month,})
with this as the javascript:
$('#django_calendar_response').html(response)
But I've also seen people formatting their output within javascript using dom functions such as
return HttpResponse(serializers.serialize("json",
ilst, relations=('user',)), "application/json")
where the javascript is
items_display=function(items){
return LI(null,
A({'class':'userlink',
'href':'/url/user/'+items.fields.user.fields.name},
items.fields.user.fields.name),
is one of these correct and the other wrong? should I format my output in javascript or within python?
|
[
"I've been using JSON exclusively for AJAX, with simplejson returning whatever data is really easy, it looks like this:\nfrom django.utils import simplejson\nreply = simplejson.dumps({'comment_body': formatted_post, 'user_icon': request.user.profile.image.url })\nreturn HttpResponse(reply, mimetype=\"application/json\")\n\nand on the client side, with jquery's .post method handling a json reply is really easy too, you can specify json as your datatype:\n$.post(\"/postcomment/\", { body: comment_body },\n function(data){\n alert(data.comment_body)\n }, \"json\");\n\nI'm not saying this is the best solution, but it's proven to be very robust and easy to handle...\nHope this helps,\nMartin\n",
"I do both. Sometimes I have short template snippets that I {% include %} in the big page template. It is often more DRY to render these and return the html to insert into the DOM (since the code is already set-up) than to have to write JS to do it (again). Other times, I just generate some JSON and inject that into the DOM.\nShortly, you can mix and match for the situation.\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"dom",
"formatting",
"json",
"python"
] |
stackoverflow_0001760538_django_dom_formatting_json_python.txt
|
Q:
Python type long vs C 'long long'
I would like to represent a value as a 64bit signed long, such that values larger than (2**63)-1 are represented as negative, however Python long has infinite precision. Is there a 'quick' way for me to achieve this?
A:
You could use ctypes.c_longlong:
>>> from ctypes import c_longlong as ll
>>> ll(2 ** 63 - 1)
c_longlong(9223372036854775807L)
>>> ll(2 ** 63)
c_longlong(-9223372036854775808L)
>>> ll(2 ** 63).value
-9223372036854775808L
This is really only an option if you know for sure that a signed long long will be 64 bits wide on the target machine(s).
Edit: jorendorff's idea of defining a class for 64 bit numbers is appealing. Ideally you want to minimize the number of explicit class creations.
Using c_longlong, you could do something like this (note: Python 3.x only!):
from ctypes import c_longlong
class ll(int):
def __new__(cls, n):
return int.__new__(cls, c_longlong(n).value)
def __add__(self, other):
return ll(super().__add__(other))
def __radd__(self, other):
return ll(other.__add__(self))
def __sub__(self, other):
return ll(super().__sub__(other))
def __rsub__(self, other):
return ll(other.__sub__(self))
...
In this way the result of ll(2 ** 63) - 1 will indeed be 9223372036854775807. This construction may result in a performance penalty though, so depending on what you want to do exactly, defining a class such as the above may not be worth it. When in doubt, use timeit.
A:
Can you use numpy? It has an int64 type that does exactly what you want.
In [1]: import numpy
In [2]: numpy.int64(2**63-1)
Out[2]: 9223372036854775807
In [3]: numpy.int64(2**63-1)+1
Out[3]: -9223372036854775808
It's transparent to users, unlike the ctypes example, and it's coded in C so it'll be faster than rolling your own class in Python. Numpy may be bigger than the other solutions, but if you're doing numerical analysis, you will appreciate having it.
A:
The quickest thing is probably to truncate the result to 64 bits yourself:
def to_int64(n):
n = n & ((1 << 64) - 1)
if n > (1 << 63) - 1:
n -= 1 << 64
return n
You can of course define your own numeric type that automatically does this every time you do any sort of arithmetic operation:
class Int64:
def __init__(self, n):
if isinstance(n, Int64):
n = n.val
self.val = to_int64(n)
def __add__(self, other):
return Int64(self.val + other)
def __radd__(self, other):
return Int64(other + self.val)
def __sub__(self, other):
return Int64(self.val - other)
...
but that is not particularly "quick" to implement.
A:
Have a look at the ctypes module, it is used to call foreign DLLs/libraries from python.
There a some data types that correspond to C types, for example
class c_longlong
|
Python type long vs C 'long long'
|
I would like to represent a value as a 64bit signed long, such that values larger than (2**63)-1 are represented as negative, however Python long has infinite precision. Is there a 'quick' way for me to achieve this?
|
[
"You could use ctypes.c_longlong:\n>>> from ctypes import c_longlong as ll\n>>> ll(2 ** 63 - 1)\nc_longlong(9223372036854775807L)\n>>> ll(2 ** 63)\nc_longlong(-9223372036854775808L)\n>>> ll(2 ** 63).value\n-9223372036854775808L\n\nThis is really only an option if you know for sure that a signed long long will be 64 bits wide on the target machine(s).\nEdit: jorendorff's idea of defining a class for 64 bit numbers is appealing. Ideally you want to minimize the number of explicit class creations.\nUsing c_longlong, you could do something like this (note: Python 3.x only!):\nfrom ctypes import c_longlong\n\nclass ll(int):\n def __new__(cls, n):\n return int.__new__(cls, c_longlong(n).value)\n\n def __add__(self, other):\n return ll(super().__add__(other))\n\n def __radd__(self, other):\n return ll(other.__add__(self))\n\n def __sub__(self, other):\n return ll(super().__sub__(other))\n\n def __rsub__(self, other):\n return ll(other.__sub__(self))\n\n ...\n\nIn this way the result of ll(2 ** 63) - 1 will indeed be 9223372036854775807. This construction may result in a performance penalty though, so depending on what you want to do exactly, defining a class such as the above may not be worth it. When in doubt, use timeit.\n",
"Can you use numpy? It has an int64 type that does exactly what you want.\nIn [1]: import numpy\n\nIn [2]: numpy.int64(2**63-1)\nOut[2]: 9223372036854775807\n\nIn [3]: numpy.int64(2**63-1)+1\nOut[3]: -9223372036854775808\n\nIt's transparent to users, unlike the ctypes example, and it's coded in C so it'll be faster than rolling your own class in Python. Numpy may be bigger than the other solutions, but if you're doing numerical analysis, you will appreciate having it.\n",
"The quickest thing is probably to truncate the result to 64 bits yourself:\ndef to_int64(n):\n n = n & ((1 << 64) - 1)\n if n > (1 << 63) - 1:\n n -= 1 << 64\n return n\n\nYou can of course define your own numeric type that automatically does this every time you do any sort of arithmetic operation:\nclass Int64:\n def __init__(self, n):\n if isinstance(n, Int64):\n n = n.val\n self.val = to_int64(n)\n\n def __add__(self, other):\n return Int64(self.val + other)\n\n def __radd__(self, other):\n return Int64(other + self.val)\n\n def __sub__(self, other):\n return Int64(self.val - other)\n\n ...\n\nbut that is not particularly \"quick\" to implement.\n",
"Have a look at the ctypes module, it is used to call foreign DLLs/libraries from python.\nThere a some data types that correspond to C types, for example \n\nclass c_longlong\n\n"
] |
[
13,
13,
3,
1
] |
[] |
[] |
[
"64_bit",
"long_integer",
"python"
] |
stackoverflow_0001764548_64_bit_long_integer_python.txt
|
Q:
Python won't refresh URL to receive new forex ticker data
I am trying to save updated Forex ticker data from this website: http://forex.offers4u.biz/TickDBReadDB.php?p=EURUSD
just hit refresh to update the ticker.
when I use my little python script, it saves the text once, but if i run it again, it makes a new file with the same old data. How can I add a "cachebreaker" so that python can read the new data from the old URL?
import urllib2, time
filename = 'EURUSD ' + str(time.asctime()) + '.txt'
myfile = open(filename, 'w')
page = urllib2.urlopen("http://forex.offers4u.biz/TickDBReadDB.php?p=EURUSD?")
for line in page:
myfile.write(line)
myfile.close()
page.close()
A:
urllib2 doesn't do any caching. Are you going through a proxy? Or the server may be caching.
Try using a Cache-Control header described here, section 14.9
EDIT: Mind you, the most recent data on that page is from 2009.11.16 20:47:37. Are you sure it's still being actively updated?
|
Python won't refresh URL to receive new forex ticker data
|
I am trying to save updated Forex ticker data from this website: http://forex.offers4u.biz/TickDBReadDB.php?p=EURUSD
just hit refresh to update the ticker.
when I use my little python script, it saves the text once, but if i run it again, it makes a new file with the same old data. How can I add a "cachebreaker" so that python can read the new data from the old URL?
import urllib2, time
filename = 'EURUSD ' + str(time.asctime()) + '.txt'
myfile = open(filename, 'w')
page = urllib2.urlopen("http://forex.offers4u.biz/TickDBReadDB.php?p=EURUSD?")
for line in page:
myfile.write(line)
myfile.close()
page.close()
|
[
"urllib2 doesn't do any caching. Are you going through a proxy? Or the server may be caching.\nTry using a Cache-Control header described here, section 14.9\nEDIT: Mind you, the most recent data on that page is from 2009.11.16 20:47:37. Are you sure it's still being actively updated?\n"
] |
[
0
] |
[] |
[] |
[
"python",
"refresh",
"ticker",
"urllib"
] |
stackoverflow_0001767616_python_refresh_ticker_urllib.txt
|
Q:
how to insert a infomation on a table in Django
This is my form on models.py
class ItemForm(forms.Form):
itemname = forms.CharField(max_length=100)
itemwording = forms.CharField(max_length=100)
notes = forms.CharField()
abundance = forms.IntegerField(max_value=10)
collunit = forms.CharField(max_length=50)
litref = forms.CharField(max_length=100)
litkey = forms.IntegerField(max_value=10)
litrefdetail = forms.CharField()
collcode = forms.CharField(max_length=15)
specimenno = forms.CharField(max_length=20)
speciesid = forms.IntegerField(max_value=10)
sorder = forms.CharField(max_length=50)
disabled = forms.BooleanField(required = True)
This is my view.py
def additem(request):
from django.db import connection, transaction
cursor = connection.cursor()
if request.method == 'POST':
form = ItemForm(request.POST)
if form.is_valid():
itemnameNEW = form.cleaned_data['itemname']
itemwordingNEW = form.cleaned_data['itemwording']
notesNEW = form.cleaned_data['notes']
abundanceNEW = form.cleaned_data['abundance']
collunitNEW = form.cleaned_data['collunit']
litrefNEW = form.cleaned_data['litref']
litkeyNEW = form.cleaned_data['litkey']
litrefdetailNEW = form.cleaned_data['litrefdetail']
collcodeNEW = form.cleaned_data['collcode']
specimennoNEW = form.cleaned_data['specimenno']
speciesidNEW = form.cleaned_data['speciesid']
sorderNEW = form.cleaned_data['sorder']
disabledNEW = form.cleaned_data['disabled']
newitem = Item(itemname=itemnameNEW, itemwording=itemwordingNEW, notes=notesNEW, abundance=abundanceNEW, collunit=collunitNEW, litref=litrefNEW, litkey=litkeyNEW, litrefdetail=litrefdetailNEW, collcode=collcodeNEW,specimenno=specimennoNEW, speciesid=speciesidNEW,sorder=sorderNEW,disabled=disabledNEW )
newitem.save();
return HttpResponseRedirect('/jalo/')
else:
return HttpResponseRedirect('/nojalo/')
else:
form = ItemForm()
return render_to_response('tbl/additem.html', {'form': form})
When i submit the form i get
IntegrityError at /login/manageitem/additem/
duplicate key value violates unique constraint "tbl_item_pkey"
I just want to insert information on a table using django
A:
The data you've posted doesn't indicate the source of the problem. Did you clear your database and run syncdb when you last changed your models?
The error you're seeing relates to trying to introduce a duplicate value into a column which must be unique, constrained at the database level. You have an object that's trying to be saved with a duplicate pk value.
That said, your keyvalueNEW scheme is not at all the right way of going about doing that. You probably want to be using ModelForms instead.
http://docs.djangoproject.com/en/dev/topics/forms/modelforms/
|
how to insert a infomation on a table in Django
|
This is my form on models.py
class ItemForm(forms.Form):
itemname = forms.CharField(max_length=100)
itemwording = forms.CharField(max_length=100)
notes = forms.CharField()
abundance = forms.IntegerField(max_value=10)
collunit = forms.CharField(max_length=50)
litref = forms.CharField(max_length=100)
litkey = forms.IntegerField(max_value=10)
litrefdetail = forms.CharField()
collcode = forms.CharField(max_length=15)
specimenno = forms.CharField(max_length=20)
speciesid = forms.IntegerField(max_value=10)
sorder = forms.CharField(max_length=50)
disabled = forms.BooleanField(required = True)
This is my view.py
def additem(request):
from django.db import connection, transaction
cursor = connection.cursor()
if request.method == 'POST':
form = ItemForm(request.POST)
if form.is_valid():
itemnameNEW = form.cleaned_data['itemname']
itemwordingNEW = form.cleaned_data['itemwording']
notesNEW = form.cleaned_data['notes']
abundanceNEW = form.cleaned_data['abundance']
collunitNEW = form.cleaned_data['collunit']
litrefNEW = form.cleaned_data['litref']
litkeyNEW = form.cleaned_data['litkey']
litrefdetailNEW = form.cleaned_data['litrefdetail']
collcodeNEW = form.cleaned_data['collcode']
specimennoNEW = form.cleaned_data['specimenno']
speciesidNEW = form.cleaned_data['speciesid']
sorderNEW = form.cleaned_data['sorder']
disabledNEW = form.cleaned_data['disabled']
newitem = Item(itemname=itemnameNEW, itemwording=itemwordingNEW, notes=notesNEW, abundance=abundanceNEW, collunit=collunitNEW, litref=litrefNEW, litkey=litkeyNEW, litrefdetail=litrefdetailNEW, collcode=collcodeNEW,specimenno=specimennoNEW, speciesid=speciesidNEW,sorder=sorderNEW,disabled=disabledNEW )
newitem.save();
return HttpResponseRedirect('/jalo/')
else:
return HttpResponseRedirect('/nojalo/')
else:
form = ItemForm()
return render_to_response('tbl/additem.html', {'form': form})
When i submit the form i get
IntegrityError at /login/manageitem/additem/
duplicate key value violates unique constraint "tbl_item_pkey"
I just want to insert information on a table using django
|
[
"The data you've posted doesn't indicate the source of the problem. Did you clear your database and run syncdb when you last changed your models?\nThe error you're seeing relates to trying to introduce a duplicate value into a column which must be unique, constrained at the database level. You have an object that's trying to be saved with a duplicate pk value.\nThat said, your keyvalueNEW scheme is not at all the right way of going about doing that. You probably want to be using ModelForms instead.\nhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_forms",
"django_models",
"django_views",
"python"
] |
stackoverflow_0001767506_django_django_forms_django_models_django_views_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.