content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python reference count and ctypes
Hallo,
I have some troubles understanding the python reference count.
What I want to do is return a tuple from c++ to python using the ctypes module.
C++:
PyObject* foo(...)
{
...
return Py_BuildValue("(s, s)", value1, value2);
}
Python:
pointer = c_foo(...) # c_foo loaded with ctypes
obj = cast(pointer, py_object).value
I'm was not sure about the ref count of obj, so I tried sys.getrefcount()
and got 3. I think it should be 2 (the getrefcount functions makes one ref itself).
Now I can't make Py_DECREF() before the return in C++ because the object gets deleted. Can I decrease the ref count in python?
edit
What happens to the ref count when the cast function is called? I'm not really sure from the documentation below. http://docs.python.org/library/ctypes.html#ctypes.cast
ctypes.cast(obj, type)
This function is similar to the cast operator in C. It returns a new instance of type which points to the same memory block as obj. type must be a pointer type, and obj must be an object that can be interpreted as a pointer.
A:
On further research I found out that one can specify the return type of the function.
http://docs.python.org/library/ctypes.html#callback-functions
This makes the cast obsolete and the ref count is no longer a problem.
clib = ctypes.cdll.LoadLibrary('some.so')
c_foo = clib.c_foo
c_foo.restype = ctypes.py_object
As no additional answers were given I accept my new solution as the answer.
A:
Your c++ code seems to be a classic wrapper using the official C-API and it's a bit weird since ctypes is usually used for using classic c types in python (like int, float, etc...).
I use personnally the C-API "alone" (without ctypes) but on my personnal experience, you don't have to worry about the reference counter in this case since you are returning a native python type with Py_BuildValue. When a function returns an object, the ownership of the returned object is given to the calling function.
You have to worry about Py_XINCREF/Py_XDECREF (better than Py_INCREF/Py_DECREF because it accepts NULL pointers) only when you want to change ownership of the object :
For example, you have created a wrapper of a map in python (let's call the typed object py_map). The element are of c++ class Foo and you have created an other python wrapper for them (let's call it py_Foo). If you create a function that wrap the [] operator, you are going to return a py_Foo object in python :
F = py_Map["key"]
but since the ownership is given to the calling function, you will call the destructor when you delete F and the map in c++ contains a pointer to a deallocated objet !
The solution is to write in c++ in the wrapper of [] :
...
PyObject* result; // My py_Foo object
Py_XINCREF(result); // transfer the ownership
return result;
}
You should take a look at the notion of borrowed and owned reference in python. This is essential to understand properly the reference counter.
| Python reference count and ctypes | Hallo,
I have some troubles understanding the python reference count.
What I want to do is return a tuple from c++ to python using the ctypes module.
C++:
PyObject* foo(...)
{
...
return Py_BuildValue("(s, s)", value1, value2);
}
Python:
pointer = c_foo(...) # c_foo loaded with ctypes
obj = cast(pointer, py_object).value
I'm was not sure about the ref count of obj, so I tried sys.getrefcount()
and got 3. I think it should be 2 (the getrefcount functions makes one ref itself).
Now I can't make Py_DECREF() before the return in C++ because the object gets deleted. Can I decrease the ref count in python?
edit
What happens to the ref count when the cast function is called? I'm not really sure from the documentation below. http://docs.python.org/library/ctypes.html#ctypes.cast
ctypes.cast(obj, type)
This function is similar to the cast operator in C. It returns a new instance of type which points to the same memory block as obj. type must be a pointer type, and obj must be an object that can be interpreted as a pointer.
| [
"On further research I found out that one can specify the return type of the function.\nhttp://docs.python.org/library/ctypes.html#callback-functions\nThis makes the cast obsolete and the ref count is no longer a problem.\nclib = ctypes.cdll.LoadLibrary('some.so')\nc_foo = clib.c_foo\nc_foo.restype = ctypes.py_obje... | [
5,
4
] | [] | [] | [
"c",
"ctypes",
"python",
"reference_counting"
] | stackoverflow_0003931525_c_ctypes_python_reference_counting.txt |
Q:
os.path.exists not accepting variable input
Whenever I call os.path.exists(variable) it will return false but if I call os.path.exists('/this/is/my/path') it will return true.
import os
import sys
test = None
print("Test directory")
test= sys.stdin.readline()
test.strip('\n')
print(os.path.exists(test))
I know that os.path.exists can return false if there is a permissions error but the directories I reference have no restrictions. Sometimes my paths have spaces in them. I have tries passing the path as both '/this\ is/my/path' and '/this is/my/path with the same results.
A:
You have to do
test = test.strip("\n")
Strings are immutable, so strip() returns a new string.
(At least your code works for me then, if it is still not working for you, it must be something else.)
A:
strip() does not modify the string, it returns a new string. Try this:
import os
import sys
sys.stdout.write("Test directory: ")
test = sys.stdin.readline().strip('\n')
sys.stdout.write(str(os.path.exists(test)) + "\n")
(I'm using sys.stdout.write() instead of print() for Python-3 agnosticity.)
A:
what you would have to do is either:
test = test.strip('\n')
or
print(os.path.exists(test.strip('\n'))
for what they said above, strip() returns a new string so in order for test to have the new string you must reassign it to it. (or in the second case use the new string straight in path.exists())
| os.path.exists not accepting variable input | Whenever I call os.path.exists(variable) it will return false but if I call os.path.exists('/this/is/my/path') it will return true.
import os
import sys
test = None
print("Test directory")
test= sys.stdin.readline()
test.strip('\n')
print(os.path.exists(test))
I know that os.path.exists can return false if there is a permissions error but the directories I reference have no restrictions. Sometimes my paths have spaces in them. I have tries passing the path as both '/this\ is/my/path' and '/this is/my/path with the same results.
| [
"You have to do \ntest = test.strip(\"\\n\")\n\nStrings are immutable, so strip() returns a new string.\n(At least your code works for me then, if it is still not working for you, it must be something else.)\n",
"strip() does not modify the string, it returns a new string. Try this:\nimport os\nimport sys\nsys.s... | [
6,
1,
0
] | [] | [] | [
"immutability",
"python",
"string"
] | stackoverflow_0003954387_immutability_python_string.txt |
Q:
Current Status of PEP 8 Rules?
Are all PEP 8 rules still valid?
Are there any which are obsolete?
Isn't there a more explanatory cheat sheet that this one.
A:
Here is the current version of PEP 8. It was last updated 2010 August 29.
A:
PEP 8 is still the preferred style guide for Python code. Watching the changes to Django, for instance, I see edits for PEP 8 (such as "2 blank lines after the imports.)
They are still suggestions, though strong ones, and differences in house style are out there.
I didn't know about that cheat-sheet before; seems like having one like that is a good idea!
A:
I still go by the PEP 8 rules, as they are recommended in the Python tutorial. I assume all are still valid, but others may differ (Google for instance has different rules).
| Current Status of PEP 8 Rules? | Are all PEP 8 rules still valid?
Are there any which are obsolete?
Isn't there a more explanatory cheat sheet that this one.
| [
"Here is the current version of PEP 8. It was last updated 2010 August 29.\n",
"PEP 8 is still the preferred style guide for Python code. Watching the changes to Django, for instance, I see edits for PEP 8 (such as \"2 blank lines after the imports.)\nThey are still suggestions, though strong ones, and difference... | [
6,
2,
1
] | [] | [] | [
"coding_style",
"pep8",
"python"
] | stackoverflow_0003954593_coding_style_pep8_python.txt |
Q:
difficulties with python assignment
I am new to programing and am having difficulties writing a program dealing with files. The program is to read a file, calculate an employees pay and an updated YTD pay total. After calculations the program will write to a new file.
This is what I have so far:
empName = ""
prevYTD = 0.0
payRate = 0.0
hoursWorked = 0.0
recordCount = 0
def startUp():
global empFile
print "\n\n" + "PAYROLL REPORT".center(110)+"\n"
print "Employee Name".ljust(30) + "Previous YTD".ljust(18) + \
"Updated YTD".ljust(18) + "Pay Rate".ljust(13) + \
"Hours Worked".ljust(19) + "Current Pay".ljust(8)
print "-"* 109
jobInfo = open("payroll_Assignment#7.txt", "r")
def readFile():
global empName, prevYTD, payRate, hoursWorked, eof
empRec = jobInfo.readline()
if empRec == "":
eof = True
else:
empName = empRec[:25]
prevYTD = float(empRec[25:40])
payRate = float(empRec[40:55])
hoursWorked = float(empRec[55:])
eof = False
def processRecords():
global recordCount
while not eof:
recordCount +=1
printRecord()
readFile()
def printRecord():
print empName, prevYTD, payRate, hoursWorked
def closeUp():
jobInfo.close()
print "\nNumber of records in the file was",recordCount
startUp()
readFile()
processRecords()
printRecord()
closeUp()
My problem is making a new file. The program is suppose to write to a new file and I don't know how to do it. Sorry for being so clumsy with this, I'm very new to it.
A:
Not sure what the problem is but some idiom can make it easy for you.
You can avoid testing for EOF and the while loop.
File is iteratable hence you can iterate over it.
for line in open('myfile','r'):
doSomething(line)
See the details at : http://docs.python.org/tutorial/inputoutput.html
[Edit: Based on revised problem]
Opening a new file for writing should be easy in python
>>> logfile = open('test.log', 'w') # Opens a new file
>>> logfile = open('test.log', 'a') # Opens a existing file to append information
Look at the various modes of opening file in Python tutorial
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
http://docs.python.org/library/functions.html#open
A:
Thank you for your answers. The program is to read a file, calculate employee pay and update the YTD total. After the calculations the program is to write a new file. I can not figure out how to do the calculations, make, write, or save the updated file.
| difficulties with python assignment | I am new to programing and am having difficulties writing a program dealing with files. The program is to read a file, calculate an employees pay and an updated YTD pay total. After calculations the program will write to a new file.
This is what I have so far:
empName = ""
prevYTD = 0.0
payRate = 0.0
hoursWorked = 0.0
recordCount = 0
def startUp():
global empFile
print "\n\n" + "PAYROLL REPORT".center(110)+"\n"
print "Employee Name".ljust(30) + "Previous YTD".ljust(18) + \
"Updated YTD".ljust(18) + "Pay Rate".ljust(13) + \
"Hours Worked".ljust(19) + "Current Pay".ljust(8)
print "-"* 109
jobInfo = open("payroll_Assignment#7.txt", "r")
def readFile():
global empName, prevYTD, payRate, hoursWorked, eof
empRec = jobInfo.readline()
if empRec == "":
eof = True
else:
empName = empRec[:25]
prevYTD = float(empRec[25:40])
payRate = float(empRec[40:55])
hoursWorked = float(empRec[55:])
eof = False
def processRecords():
global recordCount
while not eof:
recordCount +=1
printRecord()
readFile()
def printRecord():
print empName, prevYTD, payRate, hoursWorked
def closeUp():
jobInfo.close()
print "\nNumber of records in the file was",recordCount
startUp()
readFile()
processRecords()
printRecord()
closeUp()
My problem is making a new file. The program is suppose to write to a new file and I don't know how to do it. Sorry for being so clumsy with this, I'm very new to it.
| [
"Not sure what the problem is but some idiom can make it easy for you.\n\nYou can avoid testing for EOF and the while loop.\n\nFile is iteratable hence you can iterate over it.\nfor line in open('myfile','r'):\n doSomething(line)\n\nSee the details at : http://docs.python.org/tutorial/inputoutput.html\n[Edit: Ba... | [
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003954671_file_python.txt |
Q:
Subclass/Child class
I had this class and subclass :
class Range:
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
def getStart(self):
return self.start
def setStart(self, s):
self.start = s
def getEnd(self):
return self.end
def setEnd(self, e):
self.end = e
def getLength(self):
return len(range(self.start, self.end))
def overlaps(self, r):
if (r.getStart() < self.getEnd() and r.getEnd() >= self.getEnd()) or \
(self.getStart() < r.getEnd() and self.getEnd() >= r.getEnd()) or \
(self.getStart() >= r.getStart() and self.getEnd() <= r.getEnd()) or \
(r.getStart() >= self.getStart() and r.getEnd() <= self.getEnd()):
return True
else:
return False
class DNAFeature(Range):
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
self.strand = none
self.sequencename = none
def getSeqName(self, s):
return self.SeqName
def setSeqName(self, s):
self.sequencename = s
def getStrand(self):
if self.SeqName == 'plus':
return 1
elif self.SeqName == 'minus':
return -1
else:
return 0
def setStrand(self, s):
self.strand = s
And here is what I have to do:
Create
a
new
class
–
GeneModel
‐
that
contains
a
group
of
DNAFeature
objects
representing
exons
and
is
a
child
class
of
DNAFeature.
It
should
implement
the
following
methods:
getFeats()
–
returns
a
list
of
DNAFeature
objects,
sorted
by
start
position
addFeat(feat)
–
accepts
a
DNAFeature
feat
and
adds
it
to
its
internal
group
of
DNAFeature
objects
setTranslStart(i)
–
accepts
a
non‐negative
int,
sets
the
start
position
of
the
initiating
ATG
codon
getTranslStart()
–
returns
an
int,
the
start
position
of
the
initiating
ATG
codon
setTranslStop(i)
–
accepts
a
positive
int,
sets
the
end
position
for
the
stop
codon
getTranslStop()
–
returns
an
int,
the
end
position
for
the
stop
codon
setDisplayId(s)
–
sets
the
name
of
the
gene
model;
s
is
a
string
getDisplayId()
–
return
the
name
of
the
gene
model,
returns
a
string,
e.g.,
AT1G10555.1
GeneModel
should
raise
appropriate
ValueError
and
TypeError
exceptions
when
users
pass
incorrect
types
and
values
to
constructors
and
“set”
methods.
I have tried to write whatever comes to my mind, and read the books as well as searching the way to put codes together, but I am so new to programming and hardly can understand how to write the codes correctly. To be honest, this is the first time I ever do a programming class. So if I make any funny mistake in my codes, please forgive me. I haven't finish my codes yet and still reading the books to see where I am doing wrong and right with my codes. However, I really need your help to guide me to the right path. Thank you guys very much. Below is my codes:
class GeneModel(DNAFeature):
def __init__(self, translstart, translend, displayid):
self.setTranslStart(translstart)
self.setTranslStop(translend)
setDisplayId(displayid)
def getFeats():
result = []
sort.self.getStart()
return result
def addFeat(feat):
self.addFeat = feat
return self.getStart+self.getEnd
def setTranslStart(i):
self.translstart = self.setStart
self.translstart = non-negative int
def getTranslStart():
return self.translstart
def setTranslStop(i):
self.translend = self.setEnd
self.translend = "+" int
def getTranslStop():
return self.translend
def setDisplayId(s):
self.displayid = re.compile('r'\AT1G[0-9]{5,5}\.[0-9]{,1}, IGNORECASE')
def getDisplayId():
return self.displayid
A:
First, a little bit of cleanup. I'm not completely convinced that your original class, DNAFeature, is actually correct. DNAFeature seems to be inheriting from some other class, named Range, that we're missing here so if you have that code please offer it as well. In that original class, you need to define the variable SeqName (also, its preferable to keep variables lower-cased) since otherwise self.SeqName will be meaningless. Additionally, unless they're inherited from the Range class, you should also define the methods "setStart" and "setEnd". You're getter should not any additional variables, so feel free to change it to "def getSeqName(self)" instead of adding "s". I'm not sure what else your code is really supposed to do, so I'll hold any further comment.
Additionally, though you stated otherwise in your comment, I have to believe from the naming conventions (and what little I remember from bio) that you actually want GeneModel to be a container for a set of DNAFeature instances. That's different from GeneModel subclassing DNAFeature. If I'm right, then you can try:
class GeneModel(object):
def __init__(dnafeatures):
self.dnafeatures = dnafeatures
def get_features(self):
return self.dnafeatures
def add_feature(self, feature):
self.dnafeatures.append(feature)
Here dnafeatures would just be a list of dnafeature instances. This would then allow you to write methods to access these features and do whatever fun stuff you need to do.
My advice would be to make sure your DNAFeature class is correct and that your model of how you want your problem solved (in terms of what your classes do) and try asking again when its a little clearer. Hope this helps!
A:
I don't understand what the name of the gene model is. I think it's subject specific, but I think this will work for you:
class GenoModel(DNAFeature):
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
self.strand = None
self.sequencename = None
self.exons = []
self.translStart = None
self.translStop = None
self.displayId = None
def getFeats(self):
self.exons.sort(cmp=self.start)
return self.exons
def addFeat(self, f):
if type(f) == DNAFeature:
self.exons.append(f)
else:
raise TypeError("Cannot add feature as it is not of type DNAFeature")
def setTranslStart(self, i):
if type(i) != int:
raise TypeError("Cannot set translStart as it is not of type int")
elif i < 0:
raise ValueError("Cannot set tanslStart to a negative int")
else:
self.translStart = i
def getTranslStart(self):
return self.translStart
def setTranslStop(self, i):
if type(i) != int:
raise TypeError("Cannot set translStop as it is not of type int")
elif i <= 0:
raise ValueError("Cannot set tanslStop to anything less than 1")
else:
self.translStop = i
def getTranslStop(self):
return self.translStop
def setDisplayId(self, s):
if type(s) != str:
raise TypeError("Cannot set desiplayId as it is not of type string")
else:
self.displayId = s
def getDisplayId(self):
return self.displayId
Hope this helps.
| Subclass/Child class | I had this class and subclass :
class Range:
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
def getStart(self):
return self.start
def setStart(self, s):
self.start = s
def getEnd(self):
return self.end
def setEnd(self, e):
self.end = e
def getLength(self):
return len(range(self.start, self.end))
def overlaps(self, r):
if (r.getStart() < self.getEnd() and r.getEnd() >= self.getEnd()) or \
(self.getStart() < r.getEnd() and self.getEnd() >= r.getEnd()) or \
(self.getStart() >= r.getStart() and self.getEnd() <= r.getEnd()) or \
(r.getStart() >= self.getStart() and r.getEnd() <= self.getEnd()):
return True
else:
return False
class DNAFeature(Range):
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
self.strand = none
self.sequencename = none
def getSeqName(self, s):
return self.SeqName
def setSeqName(self, s):
self.sequencename = s
def getStrand(self):
if self.SeqName == 'plus':
return 1
elif self.SeqName == 'minus':
return -1
else:
return 0
def setStrand(self, s):
self.strand = s
And here is what I have to do:
Create
a
new
class
–
GeneModel
‐
that
contains
a
group
of
DNAFeature
objects
representing
exons
and
is
a
child
class
of
DNAFeature.
It
should
implement
the
following
methods:
getFeats()
–
returns
a
list
of
DNAFeature
objects,
sorted
by
start
position
addFeat(feat)
–
accepts
a
DNAFeature
feat
and
adds
it
to
its
internal
group
of
DNAFeature
objects
setTranslStart(i)
–
accepts
a
non‐negative
int,
sets
the
start
position
of
the
initiating
ATG
codon
getTranslStart()
–
returns
an
int,
the
start
position
of
the
initiating
ATG
codon
setTranslStop(i)
–
accepts
a
positive
int,
sets
the
end
position
for
the
stop
codon
getTranslStop()
–
returns
an
int,
the
end
position
for
the
stop
codon
setDisplayId(s)
–
sets
the
name
of
the
gene
model;
s
is
a
string
getDisplayId()
–
return
the
name
of
the
gene
model,
returns
a
string,
e.g.,
AT1G10555.1
GeneModel
should
raise
appropriate
ValueError
and
TypeError
exceptions
when
users
pass
incorrect
types
and
values
to
constructors
and
“set”
methods.
I have tried to write whatever comes to my mind, and read the books as well as searching the way to put codes together, but I am so new to programming and hardly can understand how to write the codes correctly. To be honest, this is the first time I ever do a programming class. So if I make any funny mistake in my codes, please forgive me. I haven't finish my codes yet and still reading the books to see where I am doing wrong and right with my codes. However, I really need your help to guide me to the right path. Thank you guys very much. Below is my codes:
class GeneModel(DNAFeature):
def __init__(self, translstart, translend, displayid):
self.setTranslStart(translstart)
self.setTranslStop(translend)
setDisplayId(displayid)
def getFeats():
result = []
sort.self.getStart()
return result
def addFeat(feat):
self.addFeat = feat
return self.getStart+self.getEnd
def setTranslStart(i):
self.translstart = self.setStart
self.translstart = non-negative int
def getTranslStart():
return self.translstart
def setTranslStop(i):
self.translend = self.setEnd
self.translend = "+" int
def getTranslStop():
return self.translend
def setDisplayId(s):
self.displayid = re.compile('r'\AT1G[0-9]{5,5}\.[0-9]{,1}, IGNORECASE')
def getDisplayId():
return self.displayid
| [
"First, a little bit of cleanup. I'm not completely convinced that your original class, DNAFeature, is actually correct. DNAFeature seems to be inheriting from some other class, named Range, that we're missing here so if you have that code please offer it as well. In that original class, you need to define the vari... | [
1,
1
] | [] | [] | [
"bioinformatics",
"python"
] | stackoverflow_0003954356_bioinformatics_python.txt |
Q:
Python: How to use platform.win32_ver() on a remote machine?
So of course I'm new to Python and to programming in general...
I am trying to get OS version information from the network. For now I only care about the windows machines.
using PyWin32 I can get some basic information, but it's not very reliable. This is an example of what I am doing right now: win32net.NetWkstaGetInfo(myip, 100)
However, it appears as though this would provide me with more appropriate information: platform.win32_ver()
I have no idea how get the info from a remote machine using this. I need to specify an IP or a range of IP's... I intend on using Google's ipaddr to get a list of network ranges to scan. I will eventually need to scan a large network for this info.
Can someone provide an example?
A:
A good way is to use WMI. The following links from Microsoft contain enough information to write code for your purposes:
Connecting to WMI on a Remote Computer
WMI Tasks: Operating Systems
The missing piece is how to do this in Python. For that, consult Tim Golden's site:
WMI for Python
WMI Cookbook
By the way, if you're OK with using a command line program and parsing the output, then I would suggest the PsTools available freely. In particular, psinfo can do what you want.
A:
I had to use remote registry...
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
ProductName, EditionID, CurrentVersion, CurrentBuild
| Python: How to use platform.win32_ver() on a remote machine? | So of course I'm new to Python and to programming in general...
I am trying to get OS version information from the network. For now I only care about the windows machines.
using PyWin32 I can get some basic information, but it's not very reliable. This is an example of what I am doing right now: win32net.NetWkstaGetInfo(myip, 100)
However, it appears as though this would provide me with more appropriate information: platform.win32_ver()
I have no idea how get the info from a remote machine using this. I need to specify an IP or a range of IP's... I intend on using Google's ipaddr to get a list of network ranges to scan. I will eventually need to scan a large network for this info.
Can someone provide an example?
| [
"A good way is to use WMI. The following links from Microsoft contain enough information to write code for your purposes:\n\nConnecting to WMI on a Remote Computer\nWMI Tasks: Operating Systems\n\nThe missing piece is how to do this in Python. For that, consult Tim Golden's site:\n\nWMI for Python\nWMI Cookbook\n... | [
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003712992_python_windows.txt |
Q:
Twisted + Django + Reverse Proxy
I am deploying twisted as a web server for my site. I am looking into possibilities of reverse proxying.
I have the following code right now hooked up to my reactor for django. I am using comet, and I realize that I absolutely must use port 80 hence I am looking into possibilities of reverse proxying. On this site, I found the following example:
# Django setup
sys.path.append("shoout_web")
os.environ['DJANGO_SETTINGS_MODULE'] = 'shoout_web.settings'
def wrapper_WSGIRootWrapper():
# Build the wrapper first
generic = WSGIHandler()
def HandlerWrapper(environ, start_response):
environ['engine'] = engine
return generic(environ, start_response)
# Thread and Allowing Ctrl-C to get you out cleanly:
pool = threadpool.ThreadPool()
pool.start()
reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
return wsgi.WSGIResource(reactor, pool, HandlerWrapper)
WSGIRoot = wrapper_WSGIRootWrapper()
# Reverse Proxy
class Simple(Resource):
isLeaf = False
def getChild(self, name, request):
if name == "orbited":
print "orbited"
return proxy.ReverseProxyResource('localhost', 12345, "/"+name)
else:
return WSGIRoot.getChildWithDefault(name, request)
# Attaching proxy + django
log_dir = './.log'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
reactor.listenTCP(DJANGO_PORT, server.Site(Simple(), logPath=os.path.join(log_dir, '.django.log')))
My trouble is I don't really know what to fill in in the else part of that second code part. I looked at text_proxy on twisted-src and there weren't substantial examples for this. Any help?
A:
It is not clear to me why you want to use a reverse-proxy. I think you're trying to use the right tool for the wrong reasons.
Reverse proxy is useful because you can have a lightweight server like nginx handle thousands of http keep-alive connections with very little memory overhead. The connections between the reverse proxy and the real web server (twisted in your case) are fewer and short-lived by comparison, thus you can handle higher loads. Note that if you're using long-lived comet connections, there's no benefit here, because you need the connection open in both servers for the duration.
You seem to be wanting to use it to simply make the server on port 12345 available on port 80. This is not what a reverse-proxy is for. Why not just bind port 80 in the first place?
| Twisted + Django + Reverse Proxy | I am deploying twisted as a web server for my site. I am looking into possibilities of reverse proxying.
I have the following code right now hooked up to my reactor for django. I am using comet, and I realize that I absolutely must use port 80 hence I am looking into possibilities of reverse proxying. On this site, I found the following example:
# Django setup
sys.path.append("shoout_web")
os.environ['DJANGO_SETTINGS_MODULE'] = 'shoout_web.settings'
def wrapper_WSGIRootWrapper():
# Build the wrapper first
generic = WSGIHandler()
def HandlerWrapper(environ, start_response):
environ['engine'] = engine
return generic(environ, start_response)
# Thread and Allowing Ctrl-C to get you out cleanly:
pool = threadpool.ThreadPool()
pool.start()
reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
return wsgi.WSGIResource(reactor, pool, HandlerWrapper)
WSGIRoot = wrapper_WSGIRootWrapper()
# Reverse Proxy
class Simple(Resource):
isLeaf = False
def getChild(self, name, request):
if name == "orbited":
print "orbited"
return proxy.ReverseProxyResource('localhost', 12345, "/"+name)
else:
return WSGIRoot.getChildWithDefault(name, request)
# Attaching proxy + django
log_dir = './.log'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
reactor.listenTCP(DJANGO_PORT, server.Site(Simple(), logPath=os.path.join(log_dir, '.django.log')))
My trouble is I don't really know what to fill in in the else part of that second code part. I looked at text_proxy on twisted-src and there weren't substantial examples for this. Any help?
| [
"It is not clear to me why you want to use a reverse-proxy. I think you're trying to use the right tool for the wrong reasons.\nReverse proxy is useful because you can have a lightweight server like nginx handle thousands of http keep-alive connections with very little memory overhead. The connections between the r... | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003947432_python_twisted.txt |
Q:
Why does "python -mtimeit" show less time when the code contains some module imports?
On my single core 1.4 GHz computer, I ran the following 2 timeit codes:
suzan:~$ python -mtimeit "
def count(n):
while n > 0:
n -= 1
count(10000000)
"
10 loops, best of 3: 1.73 sec per loop
suzan:~$
suzan:~$ python -mtimeit "
import os
def count(n):
while n > 0:
n -= 1
count(10000000)
"
10 loops, best of 3: 1.18 sec per loop
suzan:~$
The second timeit command show lesser time than the first one, even when it contains one extra line of code "import os". Is this unusual behavior or the expected one ?
Any help is greatly appreciated.
A:
I get effectively (to within 0.4%) the same time with both snippets. Python imports the os module as part of the normal import
>>> import sys
>>> "os" in sys.modules
True
>>>
so the second bit of code, with the "import os", isn't even hitting the disk. All it does is a check against sys.modules.
You could check if import builtins gives the same reaction, but I'm really at a loss to explain what you see. You can enable the "-v" option(s) when starting Python to get a bit more diagnostics about what it's doing, and compare the results. They should be identical.
A:
The only possible reason I can think of that could explain such a behaviour, shouldn't really matter: L1 cache line misses, and I am referring to data cache (Python VM bytecodes are not executable code for your processor). The code of your count function is stored as a separate code object, and its start address or its speed shouldn't be affected by the setup code. This is very irregular behaviour.
What's your processor make? Your Python version? Your OS version? And are the test results repeatable?
| Why does "python -mtimeit" show less time when the code contains some module imports? | On my single core 1.4 GHz computer, I ran the following 2 timeit codes:
suzan:~$ python -mtimeit "
def count(n):
while n > 0:
n -= 1
count(10000000)
"
10 loops, best of 3: 1.73 sec per loop
suzan:~$
suzan:~$ python -mtimeit "
import os
def count(n):
while n > 0:
n -= 1
count(10000000)
"
10 loops, best of 3: 1.18 sec per loop
suzan:~$
The second timeit command show lesser time than the first one, even when it contains one extra line of code "import os". Is this unusual behavior or the expected one ?
Any help is greatly appreciated.
| [
"I get effectively (to within 0.4%) the same time with both snippets. Python imports the os module as part of the normal import\n>>> import sys\n>>> \"os\" in sys.modules\nTrue\n>>> \n\nso the second bit of code, with the \"import os\", isn't even hitting the disk. All it does is a check against sys.modules.\nYou c... | [
1,
1
] | [] | [] | [
"python",
"timeit"
] | stackoverflow_0003742655_python_timeit.txt |
Q:
Is it possible to use Python to measure response time?
I'm running some experiments and I need to precisely measure participants' response time to questions. I know there are some commercial software, but I was wondering if I can do this with Python. Does python provides suitable functionality to measure the response time in millisecond unit?
Thank you,
Joon
A:
Just do something like this:
from time import time
starttime = time()
askQuestion()
timetaken = time() - starttime
A:
You could measure the execution time between the options displayed and the input received.
http://docs.python.org/library/timeit.html
def whatYouWantToMeasure():
pass
if __name__=='__main__':
from timeit import Timer
t = Timer("whatYouWantToMeasure()", "from __main__ import test")
print t.timeit(number=1)
A:
You might want to look at the timeit module.
import timeit
| Is it possible to use Python to measure response time? | I'm running some experiments and I need to precisely measure participants' response time to questions. I know there are some commercial software, but I was wondering if I can do this with Python. Does python provides suitable functionality to measure the response time in millisecond unit?
Thank you,
Joon
| [
"Just do something like this:\nfrom time import time\nstarttime = time()\naskQuestion()\ntimetaken = time() - starttime\n\n",
"You could measure the execution time between the options displayed and the input received.\nhttp://docs.python.org/library/timeit.html\ndef whatYouWantToMeasure():\n pass\n\nif __name_... | [
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003954900_python.txt |
Q:
Why I can call 'print' from 'eval'
For code:
#!/usr/bin/python
src = """
print '!!!'
import os
"""
obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': False})
I get output:
!!!
Traceback (most recent call last):
File "./test.py", line 9, in <module>
eval(obj, {'__builtins__': False})
File "", line 3, in <module>
ImportError: __import__ not found
Both 'print' and 'import' are language construct. Why does 'eval' restrict using of 'import' but doesn't restrict 'print'?
P.S. I'm using python 2.6
UPDATE: Question is not "Why does import not work?" but "Why does print work?" Are there some architecture restrictions or something else?
A:
The __import__ method is invoked by the import keyword: python.org
If you want to be able to import a module you need to leave the __import__ method in the builtins:
src = """
print '!!!'
import os
"""
obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': {'__import__':__builtins__.__import__}})
A:
In your eval the call to import is made successfully however import makes use of the __import__ method in builtins which you have made unavailable in your exec. This is the reason why you are seeing
ImportError: __import__ not found
print doesn't depend on any builtins so works OK.
You could pass just __import__ from builtins with something like:
eval(obj, {'__builtins__' : {'__import__' :__builtins__.__import__}})
A:
print works because you specified 'exec' to the compile function call.
A:
import calls the global/builtin __import__ function; if there isn't one to be found, import fails.
print does not rely on any globals to do its work. That is why print works in your example, even though you do not use the available __builtins__.
| Why I can call 'print' from 'eval' | For code:
#!/usr/bin/python
src = """
print '!!!'
import os
"""
obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': False})
I get output:
!!!
Traceback (most recent call last):
File "./test.py", line 9, in <module>
eval(obj, {'__builtins__': False})
File "", line 3, in <module>
ImportError: __import__ not found
Both 'print' and 'import' are language construct. Why does 'eval' restrict using of 'import' but doesn't restrict 'print'?
P.S. I'm using python 2.6
UPDATE: Question is not "Why does import not work?" but "Why does print work?" Are there some architecture restrictions or something else?
| [
"The __import__ method is invoked by the import keyword: python.org\nIf you want to be able to import a module you need to leave the __import__ method in the builtins: \nsrc = \"\"\"\nprint '!!!'\nimport os\n\"\"\"\n\nobj = compile(src, '', 'exec')\neval(obj, {'__builtins__': {'__import__':__builtins__.__import__... | [
7,
2,
0,
0
] | [] | [] | [
"built_in",
"eval",
"import",
"printing",
"python"
] | stackoverflow_0003949727_built_in_eval_import_printing_python.txt |
Q:
Python string to integer value
I'd like to know how to convert strings in Python to their corresponding integer values, like so:
>>>print WhateverFunctionDoesThis('\x41\x42')
>>>16706
I've searched around but haven't been able to find an easy way to do this.
Thank you.
A:
>>> import struct
>>> struct.unpack(">h",'\x41\x42')
(16706,)
>>> struct.unpack(">h",'\x41\x42')[0]
16706
For other format chars see the documentation
A:
If '\x41\x42' is 16-based num, like AB. You can use string to convert it.
import string
agaga = '\x41\x42'
string.atoi(agaga, 16)
>>> 171
Sorry if i got you wrong...
A:
ugly way:
>>> s = '\x41\x42'
>>> sum([ord(x)*256**(len(s)-i-1) for i,x in enumerate(s)])
16706
or
>>> sum([ord(x)*256**i for i,x in enumerate(reversed(s))])
| Python string to integer value | I'd like to know how to convert strings in Python to their corresponding integer values, like so:
>>>print WhateverFunctionDoesThis('\x41\x42')
>>>16706
I've searched around but haven't been able to find an easy way to do this.
Thank you.
| [
">>> import struct\n>>> struct.unpack(\">h\",'\\x41\\x42')\n(16706,)\n>>> struct.unpack(\">h\",'\\x41\\x42')[0]\n16706\n\nFor other format chars see the documentation\n",
"If '\\x41\\x42' is 16-based num, like AB. You can use string to convert it.\nimport string\n\nagaga = '\\x41\\x42'\nstring.atoi(agaga, 16)\n>>... | [
7,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003955196_python.txt |
Q:
Python Bed module
I need to create a Bed module with these functions:
readBed(file)
–
read
a
BED
format
file
and
constructs
a
list
of
gene
model
objects
from
the
data
it
contains.
writeBed(models=models,fname=file)
–
writes
the
given
list
of
gene
model
objects
and
writes
them
to
a
file
named
fname.
For the readBed, I was thinking about readline function that I have wrote before, and add the codes for it to return a result as a list. For writeBed, I really am clueless. Here is my codes, please guide me everyone:
def ReadBed(file):
result = []
line = fh.readline()
if not line:
fh.close()
else:
return result
def writeBed(models=models, fname=file):
if file.ReadBed = result
return result in fname
Also, I had a Range class like this, and I want to raise TypeError and ValueError for my class, but not sure how to do it, can everyone please help me too. Thank you so much everyone:
class Range:
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
def getStart(self):
return self.start
def setStart(self, s):
self.start = s
def getEnd(self):
return self.end
def setEnd(self, e):
self.end = e
def getLength(self):
return len(range(self.start, self.end))
def overlaps(self, r):
if (r.getStart() < self.getEnd() and r.getEnd() >= self.getEnd()) or \
(self.getStart() < r.getEnd() and self.getEnd() >= r.getEnd()) or \
(self.getStart() >= r.getStart() and self.getEnd() <= r.getEnd()) or \
(r.getStart() >= self.getStart() and r.getEnd() <= self.getEnd()):
return True
else:
return False
A:
I'll start with the Range class. Firstly, you shouldn't use get/set methods, instead just use the variable. Get/set methods in python are almost always bad practice. Even if you need validation, you can use properties.
If you're using python 2.x, you need to inherit from object to get new-style classes. If you're using py3k, you don't need to declare it.
Method and function names in python should be like_this rather than likeThis (by convention).
Doing something like if bool: return True else: return False can always be simplified to just return bool, so that makes your overlap method a lot simpler. If you think about the logic of it a little bit too, your comparison becomes a lot easier: for two ranges to overlap, one must start before the other ends, and must also end after the other one starts.
For your BED functions, have you tried running them? What happened? Make sure to look at what variables you are using in your functions and where you define them. You should also have a look at the with statement, which is commonly used when opening files. It provides hooks for setup and tear-down, and filehandles are made so that they .close() on tear-down. Try using that and it should also make the logic a little more clear.
class Range(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __len__(self):
"""This allows you to do len(Range object)."""
return self.end - self.start + 1
def overlaps(self, other):
if self.start < other.end:
return self.end > other.start
if other.start < self.end:
return other.end > self.start
A:
Without knowing the format in which the data is saved to file, I can only assume that it is being pickled. With that assumption in mind, I can give you the following code:
import cPickle
def readBed(filepath):
with open(filepath, 'r') as f:
data = cPickle.load(f)
return data
def writeBed(models, filepath):
with open(filepath, 'w') as f:
cPickle.dump(models, f)
| Python Bed module | I need to create a Bed module with these functions:
readBed(file)
–
read
a
BED
format
file
and
constructs
a
list
of
gene
model
objects
from
the
data
it
contains.
writeBed(models=models,fname=file)
–
writes
the
given
list
of
gene
model
objects
and
writes
them
to
a
file
named
fname.
For the readBed, I was thinking about readline function that I have wrote before, and add the codes for it to return a result as a list. For writeBed, I really am clueless. Here is my codes, please guide me everyone:
def ReadBed(file):
result = []
line = fh.readline()
if not line:
fh.close()
else:
return result
def writeBed(models=models, fname=file):
if file.ReadBed = result
return result in fname
Also, I had a Range class like this, and I want to raise TypeError and ValueError for my class, but not sure how to do it, can everyone please help me too. Thank you so much everyone:
class Range:
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
def getStart(self):
return self.start
def setStart(self, s):
self.start = s
def getEnd(self):
return self.end
def setEnd(self, e):
self.end = e
def getLength(self):
return len(range(self.start, self.end))
def overlaps(self, r):
if (r.getStart() < self.getEnd() and r.getEnd() >= self.getEnd()) or \
(self.getStart() < r.getEnd() and self.getEnd() >= r.getEnd()) or \
(self.getStart() >= r.getStart() and self.getEnd() <= r.getEnd()) or \
(r.getStart() >= self.getStart() and r.getEnd() <= self.getEnd()):
return True
else:
return False
| [
"I'll start with the Range class. Firstly, you shouldn't use get/set methods, instead just use the variable. Get/set methods in python are almost always bad practice. Even if you need validation, you can use properties.\nIf you're using python 2.x, you need to inherit from object to get new-style classes. If you're... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003955120_python.txt |
Q:
Python Mechanize keeps giving me 'response_seek_wrapper' when I try to use .open
I'm not sure what's going on, as the script used to work (before I messed around with my python on my system...)
But when I try something along the lines of
import mechanize
browser = mechanize.Browser()
browser.open("http://google.com")
I get something like
<response_seek_wrapper at 0x10123fd88 whose wrapped object = <closeable_response at 0x101232170 whose fp = <socket._fileobject object at 0x1010bf5f0>>>
Does anyone know why this is and what the fix is?
thanks!
A:
it's not an exception, is it?
nothing wrong is happening, you just got a return value, which is esentially a response object, equivalent to br.response().
see
>>> r = browser.open("http://google.com")
>>> r
<response_seek_wrapper at 0x9bb116c whose wrapped object = <closeable_response at 0x9bb426c whose fp = <socket._fileobject object at 0x9ba306c>>>
>>> r.info().headers
# see the response headers
vs
>>> browser.open("http://google.com")
>>> browser.response()
<response_seek_wrapper at 0x9c229cc whose wrapped object = <closeable_response at 0x9bb426c whose fp = <socket._fileobject object at 0x9ba306c>>>
>>> browser.response().info().headers
# see the response headers
| Python Mechanize keeps giving me 'response_seek_wrapper' when I try to use .open | I'm not sure what's going on, as the script used to work (before I messed around with my python on my system...)
But when I try something along the lines of
import mechanize
browser = mechanize.Browser()
browser.open("http://google.com")
I get something like
<response_seek_wrapper at 0x10123fd88 whose wrapped object = <closeable_response at 0x101232170 whose fp = <socket._fileobject object at 0x1010bf5f0>>>
Does anyone know why this is and what the fix is?
thanks!
| [
"it's not an exception, is it?\nnothing wrong is happening, you just got a return value, which is esentially a response object, equivalent to br.response().\nsee\n>>> r = browser.open(\"http://google.com\")\n>>> r\n<response_seek_wrapper at 0x9bb116c whose wrapped object = <closeable_response at 0x9bb426c whose fp ... | [
5
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0003955301_mechanize_python.txt |
Q:
How to use Query.order() on string properties containing non-english characters?
How to use Query.order() on string properties containing non-english characters so entities where fetched in correct order?
Query.order is oddly putting any non-english characters on the end of the list, like this:
Dolnośląskie
Kujawsko-Pomorskie
Lubelskie
Lubuskie
Mazowieckie
Małopolskie <- incorrect order
Opolskie
Podkarpackie
Podlaskie
Pomorskie
Warmińsko-Mazurskie
Wielkopolskie
Zachodniopomorskie
Łódzkie <- incorrect order
Śląskie <- incorrect order
Świętokrzyskie <- incorrect order
Where the correct roder for this set shoul be:
Dolnośląskie
Kujawsko-Pomorskie
Łódzkie
Lubelskie
Lubuskie
Małopolskie
Mazowieckie
Opolskie
Podkarpackie
Podlaskie
Pomorskie
Śląskie
Świętokrzyskie
Warmińsko-Mazurskie
Wielkopolskie
Zachodniopomorskie
Is there a way around that? Other than putting another property with English normalized string values just for ordering?
A:
Normalizing the strings into a separate property is the only solution to what you want; they're sorted by unicode codepoints, and the letters that are part of ASCII have much lower values than non-ASCII characters.
| How to use Query.order() on string properties containing non-english characters? | How to use Query.order() on string properties containing non-english characters so entities where fetched in correct order?
Query.order is oddly putting any non-english characters on the end of the list, like this:
Dolnośląskie
Kujawsko-Pomorskie
Lubelskie
Lubuskie
Mazowieckie
Małopolskie <- incorrect order
Opolskie
Podkarpackie
Podlaskie
Pomorskie
Warmińsko-Mazurskie
Wielkopolskie
Zachodniopomorskie
Łódzkie <- incorrect order
Śląskie <- incorrect order
Świętokrzyskie <- incorrect order
Where the correct roder for this set shoul be:
Dolnośląskie
Kujawsko-Pomorskie
Łódzkie
Lubelskie
Lubuskie
Małopolskie
Mazowieckie
Opolskie
Podkarpackie
Podlaskie
Pomorskie
Śląskie
Świętokrzyskie
Warmińsko-Mazurskie
Wielkopolskie
Zachodniopomorskie
Is there a way around that? Other than putting another property with English normalized string values just for ordering?
| [
"Normalizing the strings into a separate property is the only solution to what you want; they're sorted by unicode codepoints, and the letters that are part of ASCII have much lower values than non-ASCII characters.\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003955617_google_app_engine_google_cloud_datastore_python.txt |
Q:
replace only one variable in web.py templates
I am passing variable to template in web.py and have the same condition in some places. Like this:
$if myvar=="string1":
$passed argument1
............
$if myvar =="striung2":
$passed argument2
If say myvar is "string1" and I pass passed = "AAA" then I have AAA argument1 on my page, but the other if statements get replaced by empty string?
How to avoid that? I.e. how to leave other statements intact?
A:
Your question is unclear. What are you trying to do? It sounds like you just need to use else:
if myvar == "string1":
print passed
else:
# something
But it's very hard to understand what you are asking.
| replace only one variable in web.py templates | I am passing variable to template in web.py and have the same condition in some places. Like this:
$if myvar=="string1":
$passed argument1
............
$if myvar =="striung2":
$passed argument2
If say myvar is "string1" and I pass passed = "AAA" then I have AAA argument1 on my page, but the other if statements get replaced by empty string?
How to avoid that? I.e. how to leave other statements intact?
| [
"Your question is unclear. What are you trying to do? It sounds like you just need to use else:\nif myvar == \"string1\":\n print passed\nelse:\n # something\n\nBut it's very hard to understand what you are asking.\n"
] | [
0
] | [] | [] | [
"python",
"templates",
"web.py"
] | stackoverflow_0002399289_python_templates_web.py.txt |
Q:
How to speed up string construction from characters in a doubly-nested list?
A common speedup for string concatenations is changing something like
s = ""
for x in list:
s += some_function(x)
to
slist = [some_function(elt) for elt in somelist]
s = "".join(slist)
However, how could this apply if your 'for' was doubly nested? For example...
s = ""
for x in list:
for y in x:
s += some_function(y)
A:
''.join(func(c) for s in somelist for c in s)
A:
string_list = []
for x in list:
for y in x:
string_list.append(some_function(y))
the_string = ''.join(string_list)
| How to speed up string construction from characters in a doubly-nested list? | A common speedup for string concatenations is changing something like
s = ""
for x in list:
s += some_function(x)
to
slist = [some_function(elt) for elt in somelist]
s = "".join(slist)
However, how could this apply if your 'for' was doubly nested? For example...
s = ""
for x in list:
for y in x:
s += some_function(y)
| [
"''.join(func(c) for s in somelist for c in s)\n\n",
"string_list = []\nfor x in list:\n for y in x:\n string_list.append(some_function(y))\n\nthe_string = ''.join(string_list)\n\n"
] | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003956181_python.txt |
Q:
Python: Convert this list into dictionary
I've got a problem , and do not know how to code in python.
I've got a list[10, 10, 10, 20, 20, 20, 30]
I want it be in a dictionary like this
{"10": 1, "20": 3, "30" : 1}
How could I achieve this?
A:
from collections import Counter
a = [10, 10, 10, 20, 20, 20, 30]
c = Counter(a)
# Counter({10: 3, 20: 3, 30: 1})
If you really want to convert the keys to strings, that's a separate step:
dict((str(k), v) for k, v in c.iteritems())
This class is new to Python 2.7; for earlier versions, use this implementation:
http://code.activestate.com/recipes/576611/
Edit: Dropping this here since SO won't let me paste code into comments,
from collections import defaultdict
def count(it):
d = defaultdict(int)
for j in it:
d[j] += 1
return d
A:
Another way that does not use set or Counter:
d = {}
x = [10, 10, 10, 20, 20, 20, 30]
for j in x:
d[j] = d.get(j,0) + 1
EDIT: For a list of size 1000000 with 100 unique items, this method runs on my laptop in 0.37 sec, while the answer using set takes 2.59 sec. For only 10 unique items, the former method takes 0.36 sec, while the latter method only takes 0.25 sec.
EDIT: The method using defaultdict takes 0.18 sec on my laptop.
A:
Like this
l = [10, 10, 10, 20, 20, 20, 30]
uniqes = set(l)
answer = {}
for i in uniques:
answer[i] = l.count(i)
answer is now the dictionary that you want
Hope this helps
A:
in Python >= 2.7 you can use dict comprehensions, like:
>>> l = [10, 10, 10, 20, 20, 20, 30]
>>> {x: l.count(x) for x in l}
{10: 3, 20: 3, 30: 1}
not the fastest way, but pretty suitable for small lists
UPDATE
or, inspired by inspectorG4dget, this is better:
{x: l.count(x) for x in set(l)}
| Python: Convert this list into dictionary | I've got a problem , and do not know how to code in python.
I've got a list[10, 10, 10, 20, 20, 20, 30]
I want it be in a dictionary like this
{"10": 1, "20": 3, "30" : 1}
How could I achieve this?
| [
"from collections import Counter\na = [10, 10, 10, 20, 20, 20, 30]\nc = Counter(a)\n# Counter({10: 3, 20: 3, 30: 1})\n\nIf you really want to convert the keys to strings, that's a separate step:\ndict((str(k), v) for k, v in c.iteritems())\n\nThis class is new to Python 2.7; for earlier versions, use this implement... | [
16,
4,
1,
1
] | [] | [] | [
"dictionary",
"formatting",
"list",
"python"
] | stackoverflow_0003956206_dictionary_formatting_list_python.txt |
Q:
Add new column on Elixir
I use Elixir as an ORM for a MySQL database. I want to add new column to my schema.
/
How can I keep the original data in MySQL and update the schema automatically? The concept is called migrate in Ruby on rails.
A:
You're looking for sqlalchemy-migrate. Elixir is a layer on top of SQLAlchemy, and sqlalchemy-migrate was inspired by RoR migrate.
| Add new column on Elixir | I use Elixir as an ORM for a MySQL database. I want to add new column to my schema.
/
How can I keep the original data in MySQL and update the schema automatically? The concept is called migrate in Ruby on rails.
| [
"You're looking for sqlalchemy-migrate. Elixir is a layer on top of SQLAlchemy, and sqlalchemy-migrate was inspired by RoR migrate.\n"
] | [
0
] | [] | [] | [
"migration",
"mysql",
"python",
"python_elixir"
] | stackoverflow_0003956388_migration_mysql_python_python_elixir.txt |
Q:
Submitting a form in mechanize
I'm having issues submitting the result of a form submission (I can submit a form, but I can't submit the form on the page that follows the first).
I have:
browser = mechanize.Browser()
browser.set_handle_robots(False)
browser.open('https://www.example.com/login')
browser.select_form(nr=0)
browser.form['j_username'] = 'username'
browser.form['j_password'] = 'password'
req = browser.submit()
This works, as print req results in
`
<body onload="document.forms[0].submit()">
<noscript>
<p>
<strong>Note:</strong> Since your browser does not support JavaScript,
you must press the Continue button once to proceed.
</p>
</noscript>
<form action="https://www.example.com/Shibboleth.sso/SAML2/POST" method="post">
<div>
<input type="hidden" name="RelayState" value="cookie:95ca495c"/>
<input type="hidden" name="SAMLResponse" value="really long encoded value"/>
</div>
<noscript>
<div>
<input type="submit" value="Continue"/>
</div>
</noscript>
</form>
</body>
`
But I get errors when I try to use req.select_form(nr=0)
I assume this is probably from something along the lines of how mechanize returns objects from submit() and that I'm going about this the wrong way.
Any input or guidance would be appreciated :)
A:
try again browser.select_form(nr=0) instead of req.select_form(nr=0). (after submitting or clicking a link or so, the new response is considered as an actual browser page - like in a browser :) )
| Submitting a form in mechanize | I'm having issues submitting the result of a form submission (I can submit a form, but I can't submit the form on the page that follows the first).
I have:
browser = mechanize.Browser()
browser.set_handle_robots(False)
browser.open('https://www.example.com/login')
browser.select_form(nr=0)
browser.form['j_username'] = 'username'
browser.form['j_password'] = 'password'
req = browser.submit()
This works, as print req results in
`
<body onload="document.forms[0].submit()">
<noscript>
<p>
<strong>Note:</strong> Since your browser does not support JavaScript,
you must press the Continue button once to proceed.
</p>
</noscript>
<form action="https://www.example.com/Shibboleth.sso/SAML2/POST" method="post">
<div>
<input type="hidden" name="RelayState" value="cookie:95ca495c"/>
<input type="hidden" name="SAMLResponse" value="really long encoded value"/>
</div>
<noscript>
<div>
<input type="submit" value="Continue"/>
</div>
</noscript>
</form>
</body>
`
But I get errors when I try to use req.select_form(nr=0)
I assume this is probably from something along the lines of how mechanize returns objects from submit() and that I'm going about this the wrong way.
Any input or guidance would be appreciated :)
| [
"try again browser.select_form(nr=0) instead of req.select_form(nr=0). (after submitting or clicking a link or so, the new response is considered as an actual browser page - like in a browser :) )\n"
] | [
9
] | [] | [] | [
"forms",
"mechanize",
"python"
] | stackoverflow_0003956280_forms_mechanize_python.txt |
Q:
Debug a module built with Boost.Python in QtCreator
I have a module built with Boost.Python and I want to debug it in QtCreator (or perhaps gdb). I prefer a visual environment if possible.
A:
http://leohart.wordpress.com/2010/10/18/debug-a-module-built-with-boost-python-within-qtcreator/
After a while, I finally figured out how to do it. I documented it in the link above so future searches can find it.
| Debug a module built with Boost.Python in QtCreator | I have a module built with Boost.Python and I want to debug it in QtCreator (or perhaps gdb). I prefer a visual environment if possible.
| [
"http://leohart.wordpress.com/2010/10/18/debug-a-module-built-with-boost-python-within-qtcreator/\nAfter a while, I finally figured out how to do it. I documented it in the link above so future searches can find it.\n"
] | [
1
] | [] | [] | [
"boost_python",
"c++",
"debugging",
"python",
"qt_creator"
] | stackoverflow_0003956365_boost_python_c++_debugging_python_qt_creator.txt |
Q:
Embedding Python on Windows: why does it have to be a DLL?
I'm trying to write a software plug-in that embeds Python. On Windows the plug-in is technically a DLL (this may be relevant). The Python Windows FAQ says:
1.Do not build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL’s. (This is the first key undocumented fact.) Instead, link to pythonNN.dll; it is typically installed in C:\Windows\System. NN is the Python version, a number such as “23” for Python 2.3.
My question is why exactly Python must be a DLL? If, as in my case, the host application is not an .exe, but also a DLL, could I build Python into it? Or, perhaps, this note means that third-party C extensions rely on pythonN.N.dll to be present and other DLL won't do? Assuming that I'd really want to have a single DLL, what should I do?
I see there's the dynload_win.c file, which appears to be the module to import C extensions on Windows and, as far as I can see, it scans the extension file to find which pythonX.X.dll it imports; but I'm not experienced with Windows and I don't quite understand all the code there.
A:
You need to link to pythonXY.dll as a DLL, instead of linking the relevant code directly into your executable, because otherwise the Python runtime can't load other DLLs (the extension modules it relies on.) If you make your own DLL you could theoretically link all the Python code in that DLL directly, since it doesn't end up in the executable but still in a DLL. You'll have to take care to do the linking correctly, however, as pretty much none of the standard tools (like distutils) will do this for you.
However, regardless of how you embed Python, you can't make do with just the DLL, nor can you make do with just any DLL. The ABI changes between Python versions, so if you compiled your code against Python 2.6, you need python26.dll; you can't use python25.dll or python27.dll. And Python isn't just a DLL; it also needs its standard library, which includes extension modules (which are DLLs themselves, although they have the .pyd extension.) The code in dynload_win.c you ran into is for loading those DLLs, and are not related to loading of pythonXY.dll.
In short, in order to embed Python in your plugin, you need to either ship Python with the plugin, or require that the right Python version is already installed.
A:
(Sorry, I did a stupid thing, I first wrote the question, and then registered, and now I cannot alter it or comment on the replies, because StackOverflow's engine doesn't think I'm the author. I cannot even properly thank those who replied :( So this is actually an update to the question and comments.)
Thanks for all the advice, it's very valuable. As far as I understand with some effort I can link Python statically into a custom DLL, provided that I compile other dynamically loaded extensions myself and link them against the same DLL. (I know I need to ship the standard library too; my plan was to append a zipped archive to the DLL file. As far as I understand, I will even be able to import pure Python modules from it.)
I also found an interesting place in dynload_win.c. (I understand it loads dynamic extensions that use Python C API, e.g. _ctypes.) As far as I can see it not only looks for init_ctypes symbol or whatever the extension name is, but also scans the .pyd file's import table looking for (regex) python\d+\. and then compares the found symbol with known pythonNN. string to make sure the extension was compiled for this version of Python. If the import table doesn't have such a symbol or it refers to another version, it raises an error.
For me it means that:
If I link an extension against pythonNN.dll and try to load it from my custom DLL that includes a statically linked Python, it will pass the check, but — well, here I'm not sure: will it fail because there's no pythonNN.dll (i.e. even before getting to the check) or it will happily load the symbols?
And if I link it against my custom DLL, it will find symbols, but won't pass the check :)
I guess I could rewrite this piece to suit my needs... Are there any other such places, I wonder.
A:
Python needs to be a dll (with a standard name) such that your application, and the plugin, can use the same instance of python.
Plugin dlls are already going to expect to be loading (and using python from) a python26.dll (or whichever version) - if your python is statically embedded in your exe, then two different instances of the python library would be managing the same data structures.
If the python libraries use no static variables at all, and the compile settings are exactly the same this should not be a problem. However, generally its far safer to simply ensure that only one instance of the python interpreter is being used.
A:
On *nix, all shared objects in a process, including the executable, contribute their exported names into a common pool; any of the shared objects can then pull any of the names from the pool and use them as they like. This allows e.g. cStringIO.so to pull the relevant Python library functions from the main executable when the Python library is statically-linked.
On Windows, each shared object has its own independent pool of names it can use. This means that it must read the relevant different shared objects it needs functions from. Since it is a lot of work to get all the names from the main executable, the Python functions are separated out into their own DLL.
| Embedding Python on Windows: why does it have to be a DLL? | I'm trying to write a software plug-in that embeds Python. On Windows the plug-in is technically a DLL (this may be relevant). The Python Windows FAQ says:
1.Do not build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL’s. (This is the first key undocumented fact.) Instead, link to pythonNN.dll; it is typically installed in C:\Windows\System. NN is the Python version, a number such as “23” for Python 2.3.
My question is why exactly Python must be a DLL? If, as in my case, the host application is not an .exe, but also a DLL, could I build Python into it? Or, perhaps, this note means that third-party C extensions rely on pythonN.N.dll to be present and other DLL won't do? Assuming that I'd really want to have a single DLL, what should I do?
I see there's the dynload_win.c file, which appears to be the module to import C extensions on Windows and, as far as I can see, it scans the extension file to find which pythonX.X.dll it imports; but I'm not experienced with Windows and I don't quite understand all the code there.
| [
"You need to link to pythonXY.dll as a DLL, instead of linking the relevant code directly into your executable, because otherwise the Python runtime can't load other DLLs (the extension modules it relies on.) If you make your own DLL you could theoretically link all the Python code in that DLL directly, since it do... | [
4,
2,
1,
1
] | [] | [] | [
"dll",
"python",
"windows"
] | stackoverflow_0003953039_dll_python_windows.txt |
Q:
Escaping unicode strings for MySQL in Python (avoiding exceptions.UnicodeEncodeError)
I am using Twisted to asynchronously access our database in Python. My code looks like this:
from twisted.enterprise import adbapi
from MySQLdb import _mysql as mysql
...
txn.execute("""
INSERT INTO users_accounts_data_snapshots (accountid, programid, fieldid, value, timestamp, jobid)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s')
""" % (accountid, programid, record, mysql.escape_string(newrecordslist[record]), ended, jobid))
This worked until I came across this character: ®, which caused the thread to throw an exception: `exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 7: ordinal not in range(128)
However, if I don't use MySQLdb_mysql.escape_string(), I get database errors when input contains quotes etc (of course). The exception is occurring before the database is accessed so the collation of the database doesn't seem to matter at all.
What's the best way to escape this content without throwing exceptions on unicode characters? The ideal solution is one where I can pass unicode characters that won't interfere with the query along to MySQL unmolested; however, stripping the string of unicode characters, replacing them with question marks, mangling them or anything else that will stop the crashes would be acceptable.
A:
Do not format strings like this. It is a massive security hole. It is not possible to do the quoting correctly by yourself. Do not try.
Use the second parameter to 'execute'. Simply put, instead of txn.execute("... %s, %s ..." % ("xxx", "yyy")), do txn.execute("... %s, %s ...", ("xxx", "yyy")). Notice the comma instead of the percent sign. In other databases or with a different database binding, you might use a different character instead of "%s", like ? or :1, :2, :3 or :foo:, :bar:, :baz: but the idea is the same. (You can see the documentation for paramstyle in the DB-API 2.0 documentation if you are curious about alternatives.)
I've written about this in the past. The discussion on that post may be of particular interest to you.
Please also let me emphasize that this is the only correct way to do it. You may have seen MySQL documentation talking about quoting strings in various ways. You may have written applications in PHP which lacks a proper facility for passing database parameters. I guarantee that all of these sources of information are incorrect and lead to serious and ongoing security problems: do not interpolate parameters into your SQL strings.
A:
You can try:
newrecordslist[record].decode("utf-8")
Glyph is right about http://www.python.org/dev/peps/pep-0249/.
| Escaping unicode strings for MySQL in Python (avoiding exceptions.UnicodeEncodeError) | I am using Twisted to asynchronously access our database in Python. My code looks like this:
from twisted.enterprise import adbapi
from MySQLdb import _mysql as mysql
...
txn.execute("""
INSERT INTO users_accounts_data_snapshots (accountid, programid, fieldid, value, timestamp, jobid)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s')
""" % (accountid, programid, record, mysql.escape_string(newrecordslist[record]), ended, jobid))
This worked until I came across this character: ®, which caused the thread to throw an exception: `exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 7: ordinal not in range(128)
However, if I don't use MySQLdb_mysql.escape_string(), I get database errors when input contains quotes etc (of course). The exception is occurring before the database is accessed so the collation of the database doesn't seem to matter at all.
What's the best way to escape this content without throwing exceptions on unicode characters? The ideal solution is one where I can pass unicode characters that won't interfere with the query along to MySQL unmolested; however, stripping the string of unicode characters, replacing them with question marks, mangling them or anything else that will stop the crashes would be acceptable.
| [
"Do not format strings like this. It is a massive security hole. It is not possible to do the quoting correctly by yourself. Do not try.\nUse the second parameter to 'execute'. Simply put, instead of txn.execute(\"... %s, %s ...\" % (\"xxx\", \"yyy\")), do txn.execute(\"... %s, %s ...\", (\"xxx\", \"yyy\")). N... | [
11,
2
] | [] | [] | [
"mysql",
"python",
"twisted"
] | stackoverflow_0003956906_mysql_python_twisted.txt |
Q:
how itertools.tee works, can type 'itertools.tee' be duplicated in order to save it's "status"?
Below are some tests about itertools.tee:
li = [x for x in range(10)]
ite = iter(li)
==================================================
it = itertools.tee(ite, 5)
>>> type(ite)
<type 'listiterator'>
>>> type(it)
<type 'tuple'>
>>> type(it[0])
<type 'itertools.tee'>
>>>
>>> list(ite)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0]) # here I got nothing after 'list(ite)', why?
[]
>>> list(it[1])
[]
====================play again===================
>>> ite = iter(li)
it = itertools.tee(ite, 5)
>>> list(it[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[2])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[3])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[4])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(ite)
[] # why I got nothing? and why below line still have the data?
>>> list(it[0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0])
[]
====================play again===================
>>> ite = iter(li)
itt = itertools.tee(it[0], 5) # tee the iter's tee[0].
>>> list(itt[0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(itt[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0])
[] # why this has no data?
>>> list(it[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(ite)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
My question is
How does tee work and why sometimes the original iter 'has data' and other time it doesn't?
Can I keep an iter deep copy as a "status seed" to keep the raw iterator status and tee it to use later?
Can I swap 2 iters or 2 itertools.tee?
Thanks!
A:
tee takes over the original iterator; once you tee an iterator, discard the original iterator since the tee owns it (unless you really know what you're doing).
You can make a copy of a tee with the copy module:
import copy, itertools
it = [1,2,3,4]
a, b = itertools.tee(it)
c = copy.copy(a)
... or by calling a.__copy__().
Beware that tee works by keeping track of all of the iterated values that have been consumed from the original iterator, which may still be consumed by copies.
For example,
a = [1,2,3,4]
b, c = itertools.tee(a)
next(b)
At this point, the tee object underlying b and c has read one value, 1. It's storing that in memory, since it has to remember it for when c is iterated. It has to keep every value in memory until it's consumed by all copies of the tee.
The consequence of this is that you need to be careful with "saving state" by copying a tee. If you don't actually consume any values from the "saved state" tee, you're going to cause the tee to keep every value returned by the iterator in memory forever (until the copied tee is discarded and collected).
| how itertools.tee works, can type 'itertools.tee' be duplicated in order to save it's "status"? | Below are some tests about itertools.tee:
li = [x for x in range(10)]
ite = iter(li)
==================================================
it = itertools.tee(ite, 5)
>>> type(ite)
<type 'listiterator'>
>>> type(it)
<type 'tuple'>
>>> type(it[0])
<type 'itertools.tee'>
>>>
>>> list(ite)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0]) # here I got nothing after 'list(ite)', why?
[]
>>> list(it[1])
[]
====================play again===================
>>> ite = iter(li)
it = itertools.tee(ite, 5)
>>> list(it[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[2])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[3])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[4])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(ite)
[] # why I got nothing? and why below line still have the data?
>>> list(it[0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0])
[]
====================play again===================
>>> ite = iter(li)
itt = itertools.tee(it[0], 5) # tee the iter's tee[0].
>>> list(itt[0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(itt[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0])
[] # why this has no data?
>>> list(it[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(ite)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
My question is
How does tee work and why sometimes the original iter 'has data' and other time it doesn't?
Can I keep an iter deep copy as a "status seed" to keep the raw iterator status and tee it to use later?
Can I swap 2 iters or 2 itertools.tee?
Thanks!
| [
"tee takes over the original iterator; once you tee an iterator, discard the original iterator since the tee owns it (unless you really know what you're doing).\nYou can make a copy of a tee with the copy module:\nimport copy, itertools\nit = [1,2,3,4]\na, b = itertools.tee(it)\nc = copy.copy(a)\n\n... or by callin... | [
16
] | [] | [] | [
"duplicates",
"iterator",
"python",
"tee"
] | stackoverflow_0003957270_duplicates_iterator_python_tee.txt |
Q:
What is the PHP equivalent to Python's Try: ... Except:
I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else.
This is what it would look like in Python:
try:
print "stuf"
except:
print "something else"
What would this be in PHP?
A:
http://php.net/manual/en/language.exceptions.php
try {
print 'stuff';
} catch (Exception $e) {
var_dump($e);
}
Note: this only works for exceptions, not errors.
See http://www.php.net/manual/en/function.set-error-handler.php for that.
A:
try {
// do stuff ...
} catch (Exception $e) {
print($e->getMessage());
}
See http://php.net/manual/en/language.exceptions.php
A:
PHP does not natively support error catching like Python does, unless you override the default behavior and set your own error handler. PHP's try - catch was only recently added to the language in version 5, and it can only catch exceptions you explicitly throw.
So basically, PHP distinguishes between errors and exceptions. Errors haven't been modularized and made available to the user like they have been in Python. I believe that's related to the fact that PHP began as a collection of dynamic web scripts, grew and gained more features over time, and only more recently offered improved OOP support (i.e., version 5); whereas Python fundamentally supports OOP and other meta-functionality. And exception handling from the beginning.
Here's an example usage (again, a throw is necessary, or else nothing will be caught):
function oops($a)
{
if (!$a) {
throw new Exception('empty variable');
}
return "oops, $a";
}
try {
print oops($b);
} catch (Exception $e) {
print "Error occurred: " . $e->getMessage();
}
A:
You can handle PHP errors like they were exceptions by using set_error_handler
In this error handler function you can throw various exception, according to error level for instance.
By doing this you can treat any error (including programming errors) in a common way.
A:
PHP 5 has the exception model:
try {
print 'stuff';
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
A:
Assuming you're trying to catch exceptions, take a look at http://php.net/manual/en/language.exceptions.php
You could try something like
try {
echo "Stuff";
} catch (Exception $e) {
echo "Something Else";
}
| What is the PHP equivalent to Python's Try: ... Except: | I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else.
This is what it would look like in Python:
try:
print "stuf"
except:
print "something else"
What would this be in PHP?
| [
"http://php.net/manual/en/language.exceptions.php\ntry {\n print 'stuff';\n} catch (Exception $e) {\n var_dump($e);\n}\n\nNote: this only works for exceptions, not errors.\nSee http://www.php.net/manual/en/function.set-error-handler.php for that.\n",
"try {\n\n // do stuff ...\n\n} catch (Exception $e) {... | [
7,
5,
1,
1,
0,
0
] | [] | [] | [
"exception",
"php",
"python",
"try_catch"
] | stackoverflow_0003956278_exception_php_python_try_catch.txt |
Q:
Is elixir out-dated?
My sqlalchemy is 0.6.3, and elixir is 0.7.1
I created a model class which extends Entity:
from elixir import *
class User(Entity):
pass
And save the a user as:
user = User()
user.save()
It reports Session has no attribute 'save'
I looked into the code of elixir, found it invokes sqlalchemy.org.session.Session#save(), but there is no save() method there.
So, is elixir outdated, and we should not use it any more?
A:
I am using the same versions of SQLAlchemy and Elixir so it is definitely compatible. Not sure what you are trying to do with the above code.
A:
Remember to call setup_all(True) before doing anything with session or query. This will do the necessary ORM mappings for the session and the query to work properly.
| Is elixir out-dated? | My sqlalchemy is 0.6.3, and elixir is 0.7.1
I created a model class which extends Entity:
from elixir import *
class User(Entity):
pass
And save the a user as:
user = User()
user.save()
It reports Session has no attribute 'save'
I looked into the code of elixir, found it invokes sqlalchemy.org.session.Session#save(), but there is no save() method there.
So, is elixir outdated, and we should not use it any more?
| [
"I am using the same versions of SQLAlchemy and Elixir so it is definitely compatible. Not sure what you are trying to do with the above code.\n",
"Remember to call setup_all(True) before doing anything with session or query. This will do the necessary ORM mappings for the session and the query to work properly.\... | [
1,
1
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0003668026_python_python_elixir_sqlalchemy.txt |
Q:
Pylons with Elixir
I would like to use Pylons with Elixir, however, I am not sure what is the best way to get about doing this. There are several blog posts (cleverdevil, beachcoder, adam hoscilo) and even an entire new framework about how to go about doing this; however, I am not certain about the differences between them. Which one is the best to use? Am I going to run into issues using one over the other?
I would prefer not to have to use SQLAlchemy directly because of its verbosity and repetitiveness.
A:
Personally, I'd go with beachcoder's recipe as updated here. That said, with the possible exception of Tesla (which I'm not familiar with), they're all lightweight enough that it should be easy to switch between them if you have any kind of trouble; all the hard work is in your model.
A:
Graham Higgins wrote about a pylon's template for this (do we call them templates ? you know, the packages that get installed depending on what arguments you give to paster create...). I used it and it worked fine.
You may also want to check this discussion on pylons list
| Pylons with Elixir | I would like to use Pylons with Elixir, however, I am not sure what is the best way to get about doing this. There are several blog posts (cleverdevil, beachcoder, adam hoscilo) and even an entire new framework about how to go about doing this; however, I am not certain about the differences between them. Which one is the best to use? Am I going to run into issues using one over the other?
I would prefer not to have to use SQLAlchemy directly because of its verbosity and repetitiveness.
| [
"Personally, I'd go with beachcoder's recipe as updated here. That said, with the possible exception of Tesla (which I'm not familiar with), they're all lightweight enough that it should be easy to switch between them if you have any kind of trouble; all the hard work is in your model.\n",
"Graham Higgins wrote a... | [
1,
1
] | [] | [] | [
"pylons",
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0000192345_pylons_python_python_elixir_sqlalchemy.txt |
Q:
Dependency injection in (Python) Google App Engine
I want to achieve maximum testability in my Google App Engine app which I'm writing in Python.
Basically what I'm doing is creating an all-purpose base handler which inherits the google.appengine.ext.webapp.RequestHandler. My base handler will expose common functionality in my app such as repository functions, a session object and the like.
When the WSGIApplication receives a request it will find the handler class that has been registered for the requested URL, and call its constructor and after that it will call a method called initialize passing in the request and response objects.
Now, for the sake of testability I want to be able to "mock" these objects (along with my own objects). So my question is how do I go about injecting these mocks? I can override the initialize method in my base handler and check for some global "test flag" and initialize some dummy request and response objects. But it seems wrong (in my mind at least). And how do I go about initializing my other objects (which may depend on the request and response objects)?
As you can probably tell I'm a little new to Python so any recommendations would be most welcome.
EDIT:
It has been pointed out to me that this question was a little hard to answer without some code, so here goes:
from google.appengine.ext import webapp
from ..utils import gmemsess
from .. import errors
_user_id_name = 'userid'
class Handler(webapp.RequestHandler):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
self.charset = 'utf8'
self._session = None
def _getsession(self):
if not self._session:
self._session = gmemsess.Session(self)
return self._session
def _get_is_logged_in(self):
return self.session.has_key(_user_id_name)
def _get_user_id(self):
if not self.is_logged_in:
raise errors.UserNotLoggedInError()
return self.session[_user_id_name]
session = property(_getsession)
is_logged_in = property(_get_is_logged_in)
user_id = property(_get_user_id)
As you can see, no dependency injection is going on here at all. The session object is created by calling gmemsess.Session(self). The Session class expects a class which has a request object on it (it uses this to read a cookie value). In this case, self does have such a property since it inherits from webapp.RequestHandler. It also only has the object on it because after calling (the empty) constructor, WSGIApplication calls a method called initialize which sets this object (and the response object). The initialize method is declared on the base class (webapp.RequestHandler).
It looks like this:
def initialize(self, request, response):
"""Initializes this request handler with the given Request and
Response."""
self.request = request
self.response = response
When a request is made, the WSGIApplication class does the following:
def __call__(self, environ, start_response):
"""Called by WSGI when a request comes in."""
request = self.REQUEST_CLASS(environ)
response = self.RESPONSE_CLASS()
WSGIApplication.active_instance = self
handler = None
groups = ()
for regexp, handler_class in self._url_mapping:
match = regexp.match(request.path)
if match:
handler = handler_class()
handler.initialize(request, response)
groups = match.groups()
break
self.current_request_args = groups
if handler:
try:
method = environ['REQUEST_METHOD']
if method == 'GET':
handler.get(*groups)
elif method == 'POST':
handler.post(*groups)
'''SNIP'''
The lines of interest are those that say:
handler = handler_class()
handler.initialize(request, response)
As you can see, it calls the empty constructor on my handler class. And this is a problem for me, because what I think I would like to do is to inject, at runtime, the type of my session object, such that my class would look like this instead (fragment showed):
def __init__(self, session_type):
'''
Constructor
'''
self.charset = 'utf8'
self._session = None
self._session_type = session_type
def _getsession(self):
if not self._session:
self._session = self._session_type(self)
return self._session
However I can't get my head around how I would achieve this, since the WSGIApplication only calls the empty constructor. I guess I could register the session_type in some global variable, but that does not really follow the philosophy of dependency injection (as I understand it), but as stated I'm new to Python, so maybe I'm just thinking about it the wrong way. In any event I would rather pass in a session object instead of it's type, but this looks kind of impossible here.
Any input is appreciated.
A:
The simplest way to achieve what you want would be to create a module-level variable containing the class of the session to create:
# myhandler.py
session_class = gmemsess.Session
class Handler(webapp.Request
def _getsession(self):
if not self._session:
self._session = session_class(self)
return self._session
then, wherever it is that you decide between testing and running:
import myhandler
if testing:
myhandler.session_class = MyTestingSession
This leaves your handler class nearly untouched, leaves the WSGIApplication completely untouched, and gives you the flexibility to do your testing as you want.
A:
Why not just test your handlers in isolation? That is, create your mock Request and Response objects, instantiate the handler you want to test, and call handler.initialize(request, response) with your mocks. There's no need for dependency injection here.
| Dependency injection in (Python) Google App Engine | I want to achieve maximum testability in my Google App Engine app which I'm writing in Python.
Basically what I'm doing is creating an all-purpose base handler which inherits the google.appengine.ext.webapp.RequestHandler. My base handler will expose common functionality in my app such as repository functions, a session object and the like.
When the WSGIApplication receives a request it will find the handler class that has been registered for the requested URL, and call its constructor and after that it will call a method called initialize passing in the request and response objects.
Now, for the sake of testability I want to be able to "mock" these objects (along with my own objects). So my question is how do I go about injecting these mocks? I can override the initialize method in my base handler and check for some global "test flag" and initialize some dummy request and response objects. But it seems wrong (in my mind at least). And how do I go about initializing my other objects (which may depend on the request and response objects)?
As you can probably tell I'm a little new to Python so any recommendations would be most welcome.
EDIT:
It has been pointed out to me that this question was a little hard to answer without some code, so here goes:
from google.appengine.ext import webapp
from ..utils import gmemsess
from .. import errors
_user_id_name = 'userid'
class Handler(webapp.RequestHandler):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
self.charset = 'utf8'
self._session = None
def _getsession(self):
if not self._session:
self._session = gmemsess.Session(self)
return self._session
def _get_is_logged_in(self):
return self.session.has_key(_user_id_name)
def _get_user_id(self):
if not self.is_logged_in:
raise errors.UserNotLoggedInError()
return self.session[_user_id_name]
session = property(_getsession)
is_logged_in = property(_get_is_logged_in)
user_id = property(_get_user_id)
As you can see, no dependency injection is going on here at all. The session object is created by calling gmemsess.Session(self). The Session class expects a class which has a request object on it (it uses this to read a cookie value). In this case, self does have such a property since it inherits from webapp.RequestHandler. It also only has the object on it because after calling (the empty) constructor, WSGIApplication calls a method called initialize which sets this object (and the response object). The initialize method is declared on the base class (webapp.RequestHandler).
It looks like this:
def initialize(self, request, response):
"""Initializes this request handler with the given Request and
Response."""
self.request = request
self.response = response
When a request is made, the WSGIApplication class does the following:
def __call__(self, environ, start_response):
"""Called by WSGI when a request comes in."""
request = self.REQUEST_CLASS(environ)
response = self.RESPONSE_CLASS()
WSGIApplication.active_instance = self
handler = None
groups = ()
for regexp, handler_class in self._url_mapping:
match = regexp.match(request.path)
if match:
handler = handler_class()
handler.initialize(request, response)
groups = match.groups()
break
self.current_request_args = groups
if handler:
try:
method = environ['REQUEST_METHOD']
if method == 'GET':
handler.get(*groups)
elif method == 'POST':
handler.post(*groups)
'''SNIP'''
The lines of interest are those that say:
handler = handler_class()
handler.initialize(request, response)
As you can see, it calls the empty constructor on my handler class. And this is a problem for me, because what I think I would like to do is to inject, at runtime, the type of my session object, such that my class would look like this instead (fragment showed):
def __init__(self, session_type):
'''
Constructor
'''
self.charset = 'utf8'
self._session = None
self._session_type = session_type
def _getsession(self):
if not self._session:
self._session = self._session_type(self)
return self._session
However I can't get my head around how I would achieve this, since the WSGIApplication only calls the empty constructor. I guess I could register the session_type in some global variable, but that does not really follow the philosophy of dependency injection (as I understand it), but as stated I'm new to Python, so maybe I'm just thinking about it the wrong way. In any event I would rather pass in a session object instead of it's type, but this looks kind of impossible here.
Any input is appreciated.
| [
"The simplest way to achieve what you want would be to create a module-level variable containing the class of the session to create:\n# myhandler.py\nsession_class = gmemsess.Session\n\nclass Handler(webapp.Request\n def _getsession(self):\n if not self._session:\n self._session = session_class... | [
2,
1
] | [] | [] | [
"dependency_injection",
"google_app_engine",
"python"
] | stackoverflow_0003949015_dependency_injection_google_app_engine_python.txt |
Q:
Is is possible to read a file from S3 in Google App Engine using boto?
I want to manipulate a pickled python object stored in S3 in Google App Engine's sandbox. I use the suggestion in boto's documentation:
from boto.s3.connection import S3Connection
from boto.s3.key import Key
conn = S3Connection(config.key, config.secret_key)
bucket = conn.get_bucket('bucketname')
key = bucket.get_key("picture.jpg")
fp = open ("picture.jpg", "w")
key.get_file (fp)
but this requires me to write to a file, which apparently is not kosher in the GAE sandbox.
How can I get around this?
Thanks much for any help
A:
You don't need to write to a file or a StringIO at all. You can call key.get_contents_as_string() to return the key's contents as a string. The docs for key are here.
A:
You can write into a blob and use the StringIO to retrieve the data
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from google.appengine.ext import db
class Data(db.Model)
image = db.BlobProperty(default=None)
conn = S3Connection(config.key, config.secret_key)
bucket = conn.get_bucket('bucketname')
key = bucket.get_key("picture.jpg")
fp = StringIO.StringIO()
key.get_file(fp)
data = Data(key_name="picture.jpg")
data.image = db.Blob(fp.getvalue())
data.put()
| Is is possible to read a file from S3 in Google App Engine using boto? | I want to manipulate a pickled python object stored in S3 in Google App Engine's sandbox. I use the suggestion in boto's documentation:
from boto.s3.connection import S3Connection
from boto.s3.key import Key
conn = S3Connection(config.key, config.secret_key)
bucket = conn.get_bucket('bucketname')
key = bucket.get_key("picture.jpg")
fp = open ("picture.jpg", "w")
key.get_file (fp)
but this requires me to write to a file, which apparently is not kosher in the GAE sandbox.
How can I get around this?
Thanks much for any help
| [
"You don't need to write to a file or a StringIO at all. You can call key.get_contents_as_string() to return the key's contents as a string. The docs for key are here.\n",
"You can write into a blob and use the StringIO to retrieve the data\nfrom boto.s3.connection import S3Connection\nfrom boto.s3.key import Key... | [
7,
3
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"boto",
"google_app_engine",
"python"
] | stackoverflow_0003948391_amazon_s3_amazon_web_services_boto_google_app_engine_python.txt |
Q:
unable to convert pdf to text using python script
i want to convert all my .pdf files from a specific directory to .txt format using the command pdftotext... but i wanna do this using a python script...
my script contains:
import glob
import os
fullPath = os.path.abspath("/home/eth1/Downloads")
for fileName in glob.glob(os.path.join(fullPath,'*.pdf')):
fullFileName = os.path.join(fullPath, fileName)
os.popen('pdftotext fullFileName')
but I am getting the following error:
Error: Couldn't open file 'fullFileName': No such file or directory.
A:
You are passing fullFileName literally to os.popen. You should do something like this instead (assuming that fullFileName does not have to be escaped):
os.popen('pdftotext %s' % fullFileName)
Also note that os.popen is considered deprecated, it's better to use the subprocess module instead:
import subprocess
retcode = subprocess.call(["/usr/bin/pdftotext", fullFileName])
It is also much safer as it handles spaces and special characters in fullFileName properly.
A:
Change the last line to
os.open('pdftotext {0}'.format(fullFileName))
This way the value of fullFileName will be passed, instead of the name.
| unable to convert pdf to text using python script | i want to convert all my .pdf files from a specific directory to .txt format using the command pdftotext... but i wanna do this using a python script...
my script contains:
import glob
import os
fullPath = os.path.abspath("/home/eth1/Downloads")
for fileName in glob.glob(os.path.join(fullPath,'*.pdf')):
fullFileName = os.path.join(fullPath, fileName)
os.popen('pdftotext fullFileName')
but I am getting the following error:
Error: Couldn't open file 'fullFileName': No such file or directory.
| [
"You are passing fullFileName literally to os.popen. You should do something like this instead (assuming that fullFileName does not have to be escaped):\nos.popen('pdftotext %s' % fullFileName)\n\nAlso note that os.popen is considered deprecated, it's better to use the subprocess module instead:\nimport subprocess\... | [
3,
1
] | [] | [] | [
"glob",
"python"
] | stackoverflow_0003958039_glob_python.txt |
Q:
What is the best way to detect and redirect a mobile browsser in AppEngine?
Specfically, I am working in Python.
A:
Check it out @mobiforge : http://mobiforge.com/developing/story/creating-mobile-web-sites-with-google-app-engine
A:
set your doctype to
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
| What is the best way to detect and redirect a mobile browsser in AppEngine? | Specfically, I am working in Python.
| [
"Check it out @mobiforge : http://mobiforge.com/developing/story/creating-mobile-web-sites-with-google-app-engine\n",
"set your doctype to\n<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.0//EN\" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\">\n\n"
] | [
3,
0
] | [] | [] | [
"google_app_engine",
"mobile_phones",
"mobile_website",
"python"
] | stackoverflow_0003957794_google_app_engine_mobile_phones_mobile_website_python.txt |
Q:
Prototype based object orientation. The good, the bad and the ugly?
I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.
The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.
In summary, what is the good, the bad and the ugly parts of such approach?
A:
Prototype-based OO lends itself poorly to static type checking, which some might consider a bad or ugly thing. Prototype-based OO does have a standard way of creating new objects, you clone and modify existing objects. You can also build factories, etc.
I think what people like most (the "good") is that prototype-based OO is very lightweight and flexible, offering a very high power-to-weight ratio.
For tips on how to use prototype-based OO, a great place to start is the original Self paper on The Power of Simplicity.
A:
To conserve the bandwidth here is the link to my answer on "How can I emulate “classes” in JavaScript? (with or without a third-party library)". It contains further references as well as examples.
The short answer: the heart of JavaScript's prototypal OO is delegation. In this style of OOP different objects of the same "class" can delegate the handling of methods and properties to the same prototype (usually some third object):
var foo = {
property: 42,
inc: function(){
++this.counter;
},
dec: function(){
--this.counter;
}
};
// Note: foo does not define `counter`.
Let's create a constructor for objects with foo as a prototype. Effectively, everything unhandled will be delegated to foo.
var Bar = function(){
this.counter = 0;
};
Bar.prototype = foo; // This is how we set up the delegation.
// Some people refer to Bar (a constructor function) as "class".
var bar = new Bar();
console.log(bar.counter); // 0 --- Comes from bar itself
console.log(bar.property); // 42 --- Not defined in bar, comes from foo
bar.inc(); // Not defined in bar => delegated to foo
bar.inc();
bar.dec(); // Not defined in bar => delegated to foo
// Note: foo.inc() and foo.dec() are called but this === bar
// that is why bar is modified, not foo.
console.log(bar.counter); // 1 --- Comes from bar itself
Let's define inc() directly on bar:
bar.inc = function(){
this.counter = 42;
};
bar.inc(); // Defined in bar => calling it directly.
// foo.inc() is not even called.
console.log(bar.counter); // 42 --- Comes from bar
Setting up the single inheritance chain:
var Baz = function(){
this.counter = 99;
};
Baz.protype = new Bar();
var baz = new Baz();
console.log(baz.counter); // 99
baz.inc();
console.log(baz.counter); // 100
console.log(baz instanceof Baz); // true
console.log(baz instanceof Bar); // true
console.log(baz instanceof Object); // true
Neat, eh?
A:
Before worrying about how to emulate class-based inheritance in JavaScript, have a quick read of Prototypal Inheritance in JavaScript.
A:
Classical inheritance is inherently flawed in terms of flexibility, in that we are saying "this object is of this type and no other". Some languages introduce multiple inheritance to alleviate this, but multiple inheritance has its own pitfalls, and so the benefits of pure composition over inheritance (which, in a statically typed language, is a runtime rather than a compile time mechanism) become clear.
Taking the concept of composition to this "pure" level, we can eliminate classical inheritance altogether along with static typing. By composing objects at runtime and using them as blueprints (the prototypal approach), we need never concern ourselves with boxing objects too tightly through inheritance, nor burden ourselves with the issues inherent in multiple inheritance approaches.
So prototypal means much more flexible development of modules.
Of course, it's quite another thing to say it's EASY to develop without static typing. IMO, it is not.
A:
Okay, first of all, the prototype model isn't all that different in reality; Smalltalk uses a similar sort of scheme; the class is an object with the classes methods.
Looked at from the class POV, a class is really the equivalence class of objects with the same data, and all the same methods; you can look at adding a method to a prototype as creating a new subclass.
The implementation is simple, but makes it very difficult to do effective typechecking.
| Prototype based object orientation. The good, the bad and the ugly? | I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.
The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.
In summary, what is the good, the bad and the ugly parts of such approach?
| [
"Prototype-based OO lends itself poorly to static type checking, which some might consider a bad or ugly thing. Prototype-based OO does have a standard way of creating new objects, you clone and modify existing objects. You can also build factories, etc.\nI think what people like most (the \"good\") is that proto... | [
13,
7,
2,
1,
0
] | [] | [] | [
"javascript",
"language_agnostic",
"lua",
"oop",
"python"
] | stackoverflow_0000385403_javascript_language_agnostic_lua_oop_python.txt |
Q:
Django Templates Variable Resolution
Hey there, it's been a week with Django back here so don't mind me if the question is stupid, though I searched over stackoverflow and google with no luck.
I've got a simple model called Term (trying to implement tags and categories for my news module) and I have a template tag called taxonomy_list which should output all the terms assigned to a post in a comma-separated list of links. Now, my Term model does not have a permalink field, but it gets there from within my view and is being passed on to the template. The permalink value looks fine inside the template, but doesn't load up into my template tag.
To illustrate this I got bits from my code. Here's my custom template tag called taxonomy_list:
from django import template
from juice.taxonomy.models import Term
from juice.news.models import Post
register = template.Library()
@register.tag
def taxonomy_list(parser, token):
tag_name, terms = token.split_contents()
return TaxonomyNode(terms)
class TaxonomyNode(template.Node):
def __init__(self, terms):
self.terms = template.Variable(terms)
def render(self, context):
terms = self.terms.resolve(context)
links = []
for term in terms.all():
links.append('<a href="%s">%s</a>' % (term.permalink, term.name))
return ", ".join(links)
Here's my single post view:
# single post view
def single(request, post_slug):
p = Post.objects.get(slug=post_slug)
p.tags = p.terms.filter(taxonomy='tag')
p.categories = p.terms.filter(taxonomy='category')
# set the permalinks
for c in p.categories:
c.permalink = make_permalink(c)
for t in p.tags:
t.permalink = make_permalink(t)
return render_to_response('news-single.html', {'post': p})
And this is what I do inside my template to illustrate two methods of accessing the categories:
Method1: {% taxonomy_list post.categories %}
Method2: {% for c in post.categories %}{{c.slug}} ({{c.permalink}}),{% endfor %}
What's interesting is that Method number 2 works fine, but Method number 1 says that my .permalink field is undefined, this probably means that the variable resolution is not done as I'm expecting, since the "extra" permalink field is left out.
I thought that maybe the variable is not recognizing the field as it is not defined in the model so I tried assigning it a "temporary" value inside the model, but that didn't help either. Method1 contained "temporary" in links, while method2 was working out correctly.
Any ideas?
Thanks!
A:
It's not really a question of variable resolution. The issue is how you're getting the terms from the Post object.
When, inside your template tag, you do for term in terms.all(), the all is telling Django to re-evaluate the queryset, which means querying the database again. So, your carefully-annotated terms are getting refreshed with new objects from the database, and the permalink attribute is getting overridden.
It will probably work if you just drop the all - so you just have for term in terms:. This will re-use the existing objects.
| Django Templates Variable Resolution | Hey there, it's been a week with Django back here so don't mind me if the question is stupid, though I searched over stackoverflow and google with no luck.
I've got a simple model called Term (trying to implement tags and categories for my news module) and I have a template tag called taxonomy_list which should output all the terms assigned to a post in a comma-separated list of links. Now, my Term model does not have a permalink field, but it gets there from within my view and is being passed on to the template. The permalink value looks fine inside the template, but doesn't load up into my template tag.
To illustrate this I got bits from my code. Here's my custom template tag called taxonomy_list:
from django import template
from juice.taxonomy.models import Term
from juice.news.models import Post
register = template.Library()
@register.tag
def taxonomy_list(parser, token):
tag_name, terms = token.split_contents()
return TaxonomyNode(terms)
class TaxonomyNode(template.Node):
def __init__(self, terms):
self.terms = template.Variable(terms)
def render(self, context):
terms = self.terms.resolve(context)
links = []
for term in terms.all():
links.append('<a href="%s">%s</a>' % (term.permalink, term.name))
return ", ".join(links)
Here's my single post view:
# single post view
def single(request, post_slug):
p = Post.objects.get(slug=post_slug)
p.tags = p.terms.filter(taxonomy='tag')
p.categories = p.terms.filter(taxonomy='category')
# set the permalinks
for c in p.categories:
c.permalink = make_permalink(c)
for t in p.tags:
t.permalink = make_permalink(t)
return render_to_response('news-single.html', {'post': p})
And this is what I do inside my template to illustrate two methods of accessing the categories:
Method1: {% taxonomy_list post.categories %}
Method2: {% for c in post.categories %}{{c.slug}} ({{c.permalink}}),{% endfor %}
What's interesting is that Method number 2 works fine, but Method number 1 says that my .permalink field is undefined, this probably means that the variable resolution is not done as I'm expecting, since the "extra" permalink field is left out.
I thought that maybe the variable is not recognizing the field as it is not defined in the model so I tried assigning it a "temporary" value inside the model, but that didn't help either. Method1 contained "temporary" in links, while method2 was working out correctly.
Any ideas?
Thanks!
| [
"It's not really a question of variable resolution. The issue is how you're getting the terms from the Post object.\nWhen, inside your template tag, you do for term in terms.all(), the all is telling Django to re-evaluate the queryset, which means querying the database again. So, your carefully-annotated terms are ... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003957977_django_python.txt |
Q:
Minimax explained for an idiot
I've wasted my entire day trying to use the minimax algorithm to make an unbeatable tictactoe AI. I missed something along the way (brain fried).
I'm not looking for code here, just a better explanation of where I went wrong.
Here is my current code (the minimax method always returns 0 for some reason):
from copy import deepcopy
class Square(object):
def __init__(self, player=None):
self.player = player
@property
def empty(self):
return self.player is None
class Board(object):
winning_combos = (
[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6],
)
def __init__(self, squares={}):
self.squares = squares
for i in range(9):
if self.squares.get(i) is None:
self.squares[i] = Square()
@property
def available_moves(self):
return [k for k, v in self.squares.iteritems() if v.empty]
@property
def complete(self):
for combo in self.winning_combos:
combo_available = True
for pos in combo:
if not pos in self.available_moves:
combo_available = False
if combo_available:
return self.winner is not None
return True
@property
def player_won(self):
return self.winner == 'X'
@property
def computer_won(self):
return self.winner == 'O'
@property
def tied(self):
return self.complete == True and self.winner is None
@property
def winner(self):
for player in ('X', 'O'):
positions = self.get_squares(player)
for combo in self.winning_combos:
win = True
for pos in combo:
if pos not in positions:
win = False
if win:
return player
return None
@property
def heuristic(self):
if self.player_won:
return -1
elif self.tied:
return 0
elif self.computer_won:
return 1
def get_squares(self, player):
return [k for k,v in self.squares.iteritems() if v.player == player]
def make_move(self, position, player):
self.squares[position] = Square(player)
def minimax(self, node, player):
if node.complete:
return node.heuristic
a = -1e10000
for move in node.available_moves:
child = deepcopy(node)
child.make_move(move, player)
a = max([a, -self.minimax(child, get_enemy(player))])
return a
def get_enemy(player):
if player == 'X':
return 'O'
return 'X'
A:
Step 1: Build your game tree
Starting from the current board generate all possible moves your opponent can make.
Then for each of those generate all the possible moves you can make.
For Tic-Tac-Toe simply continue until no one can play. In other games you'll generally stop after a given time or depth.
This looks like a tree, draw it yourself on a piece of paper, current board at top, all opponent moves one layer below, all your possible moves in response one layer below etc.
Step 2: Score all boards at the bottom of the tree
For a simple game like Tic-Tac-Toe make the score 0 if you lose, 50 tie, 100 win.
Step 3: Propagate the score up the tree
This is where the min-max come into play. The score of a previously unscored board depends on its children and who gets to play. Assume both you and your opponent always choose the best possible move at the given state. The best move for the opponent is the move that gives you the worst score. Likewise, your best move is the move that gives you the highest score. In case of the opponent's turn, you choose the child with the minimum score (that maximizes his benefit). If it is your turn you assume you'll make the best possible move, so you choose the maximum.
Step 4: Pick your best move
Now play the move that results in the best propagated score among all your possible plays from the current position.
Try it on a piece of paper, if starting from a blank board is too much for you start from some advanced Tic-Tac-Toe position.
Using recursion:
Very often this can be simplified by using recursion. The "scoring" function is called recursively at each depth and depending on whether or not the depth is odd or even it select max or min respectively for all possible moves. When no moves are possible it evaluates the static score of the board. Recursive solutions (e.g. the example code) can be a bit trickier to grasp.
A:
As you already know the idea of Minimax is to deep search for the best value, assuming the opponent will always play the move with the worst value (worst for us, so best for them).
The idea is, you will try to give a value to each position. The position where you lose is negative (we don't want that) and the position where you win is positive. You assume you will always try for the highest-value position, but you also assume the opponent will always aim at the lowest-value position, which has the worst outcome for us, and the best for them (they win, we lose). So you put yourself in their shoes, try to play as good as you can as them, and assume they will do that.
So if you find out you have possible two moves, one giving them the choice to win or to lose, one resulting in a draw anyway, you assume they will go for the move that will have them win if you let them do that. So it's better to go for the draw.
Now for a more "algorithmic" view.
Imagine your grid is nearly full except for two possible positions.
Consider what happens when you play the first one :
The opponent will play the other one. It's their only possible move so we don't have to consider other moves from them. Look at the result, associate a resulting value (+∞ if won, 0 if draw, -∞ if lost : for tic tac toe you can represent those as +1 0 and -1).
Now consider what happens when you play the second one :
(same thing here, opponent has only one move, look at the resulting position, value the position).
You need to choose between the two moves. It's our move, so we want the best result (this is the "max" in minimax). Choose the one with the higher result as our "best" move. That's it for the "2 moves from end" example.
Now imagine you have not 2 but 3 moves left.
The principle is the same, you want to assign a value to each of your 3 possible moves, so that you can choose the best.
So you start by considering one of the three moves.
You are now in the situation above, with only 2 possible moves, but it's the opponent's turn. Then you start considering one of the possible moves for the opponent, like we did above. Likewise, you look at each of the possible moves, and you find an outcome value for both of them. It's the opponent move, so we assume they will play the "best" move for them, the one with the worst turnout for us, so it's the one with the lesser value (this is the "min" in minimax). Ignore the other one ; assume they will play what you found was best for them anyway. This is what your move will yield, so it's the value you assign to the first of your three moves.
Now you consider each of your other possible 2 moves. You give them a value in the same manner. And from your three moves, you choose the one with the max value.
Now consider what happens with 4 moves. For each of your 4 moves, you look what happens for the 3 moves of your opponent, and for each of them you assume they will choose the one that gives you the worst possible outcome of the best of the 2 remaining moves for you.
You see where this is headed. To evaluate a move n steps from the end, you look at what may happen for each of the n possible moves, trying to give them a value so that you can pick the best. In the process, you will have to try to find the best move for the player that plays at n-1 : the opponent, and choose the step with the lesser value. In the process of evaluating the n-1 move, you have to choose between the possible n-2 moves, which will be ours, and assume we will play as well as we can at this step. Etc.
This is why this algorithm is inherently recursive. Whatever n, at step n you evaluate all possible steps at n-1. Rinse and repeat.
For tic-tac-toe todays machines are far powerful enough to compute all possible outcomes right off from the start of the game, because there are only a few hundred of them. When you look to implement it for a more complex game, you will have to stop computing at some point because it will take too long. So for a complex game, you will also have to write code that decides whether to continue looking for all possible next moves or to try to give a value to the position now and return early. It means you will also have to compute a value for position that is not final - for example for chess you would take into account how much material each opponent has on the board, the immediate possibilities of check without mate, how many tiles you control and all, which makes it not trivial.
A:
Your complete function is not working as expected, causing games to be declared tied before anything can happen. For instance, consider this setup:
>> oWinning = {
1: Square('X'),
3: Square('O'), 4: Square('X'),
6: Square('O'), 8: Square('X'),
}
>> nb = Board(oWinning)
>> nb.complete
True
>> nb.tied
True
This should be a win for the computer on the next move. Instead, it says the game is tied.
The problem is that your logic in complete, right now, checks to see if all of the squares in a combo are free. If any of them are not, it presumes that that combo can't be won with. What it needs to do is check if any positions in that combo are occupied, and so long as all of those combos are either None or the same player, that combo should be considered still available.
e.g.
def available_combos(self, player):
return self.available_moves + self.get_squares(player)
@property
def complete(self):
for player in ('X', 'O'):
for combo in self.winning_combos:
combo_available = True
for pos in combo:
if not pos in self.available_combos(player):
combo_available = False
if combo_available:
return self.winner is not None
return True
Now that I properly tested this with the updated code I'm getting the expected result on this test case:
>>> nb.minimax(nb, 'O')
-1
>>> nb.minimax(nb, 'X')
1
| Minimax explained for an idiot | I've wasted my entire day trying to use the minimax algorithm to make an unbeatable tictactoe AI. I missed something along the way (brain fried).
I'm not looking for code here, just a better explanation of where I went wrong.
Here is my current code (the minimax method always returns 0 for some reason):
from copy import deepcopy
class Square(object):
def __init__(self, player=None):
self.player = player
@property
def empty(self):
return self.player is None
class Board(object):
winning_combos = (
[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6],
)
def __init__(self, squares={}):
self.squares = squares
for i in range(9):
if self.squares.get(i) is None:
self.squares[i] = Square()
@property
def available_moves(self):
return [k for k, v in self.squares.iteritems() if v.empty]
@property
def complete(self):
for combo in self.winning_combos:
combo_available = True
for pos in combo:
if not pos in self.available_moves:
combo_available = False
if combo_available:
return self.winner is not None
return True
@property
def player_won(self):
return self.winner == 'X'
@property
def computer_won(self):
return self.winner == 'O'
@property
def tied(self):
return self.complete == True and self.winner is None
@property
def winner(self):
for player in ('X', 'O'):
positions = self.get_squares(player)
for combo in self.winning_combos:
win = True
for pos in combo:
if pos not in positions:
win = False
if win:
return player
return None
@property
def heuristic(self):
if self.player_won:
return -1
elif self.tied:
return 0
elif self.computer_won:
return 1
def get_squares(self, player):
return [k for k,v in self.squares.iteritems() if v.player == player]
def make_move(self, position, player):
self.squares[position] = Square(player)
def minimax(self, node, player):
if node.complete:
return node.heuristic
a = -1e10000
for move in node.available_moves:
child = deepcopy(node)
child.make_move(move, player)
a = max([a, -self.minimax(child, get_enemy(player))])
return a
def get_enemy(player):
if player == 'X':
return 'O'
return 'X'
| [
"Step 1: Build your game tree\nStarting from the current board generate all possible moves your opponent can make.\nThen for each of those generate all the possible moves you can make.\nFor Tic-Tac-Toe simply continue until no one can play. In other games you'll generally stop after a given time or depth.\nThis lo... | [
20,
7,
3
] | [] | [] | [
"minimax",
"python",
"tic_tac_toe"
] | stackoverflow_0003956258_minimax_python_tic_tac_toe.txt |
Q:
determing file object size before using file object
I am attempting to determine the size of a downloaded file in python before parsing and manipulating it with BeautifulSoup. (I intend to update to ElementTree soon, but having briefly played with it, it does not solve the problem I am posing here, as far as I can see).
import urllib2, BeautifulSoup
query = 'http://myexample.file.com/file.xml'
f = urllib2.urlopen(query)
print len(f.read())
soup = BeautifulSoup.BeautifulStoneSoup(f.read())
This code falters because when I read() the file the first time in len(), it naturally reaches an EOF and so the file object is then empty by the time I want to access it with BeautifulSoup.
My inital thought was simply to copy the object with a fcopy = f line, but this led me to learn I'm merely referencing the underlying object and gain nothing.
I then thought that fcopy = copy.copy(f) would create a true copy of the object, but apparently not as reading f still results in fcopy being an empty file object.
I even read about passing objects as parameters to functions in order to get round this, and tried the following code
import urllib2, BeautifulSoup
def get_bytes(file):
return len(file.read())
query = 'http://myexample.file.com/file.xml'
f = urllib2.urlopen(query)
print(get_bytes(f))
soup = BeautifulSoup.BeautifulStoneSoup(f.read())
But I had the same problem. How can I determine the file size of this object without effectively destroying the file?
A:
Copy the content of the file into a variable and work with it:
import urllib2, BeautifulSoup
query = 'http://myexample.file.com/file.xml'
f = urllib2.urlopen(query)
content = f.read()
print len(content)
soup = BeautifulSoup.BeautifulStoneSoup(content)
| determing file object size before using file object | I am attempting to determine the size of a downloaded file in python before parsing and manipulating it with BeautifulSoup. (I intend to update to ElementTree soon, but having briefly played with it, it does not solve the problem I am posing here, as far as I can see).
import urllib2, BeautifulSoup
query = 'http://myexample.file.com/file.xml'
f = urllib2.urlopen(query)
print len(f.read())
soup = BeautifulSoup.BeautifulStoneSoup(f.read())
This code falters because when I read() the file the first time in len(), it naturally reaches an EOF and so the file object is then empty by the time I want to access it with BeautifulSoup.
My inital thought was simply to copy the object with a fcopy = f line, but this led me to learn I'm merely referencing the underlying object and gain nothing.
I then thought that fcopy = copy.copy(f) would create a true copy of the object, but apparently not as reading f still results in fcopy being an empty file object.
I even read about passing objects as parameters to functions in order to get round this, and tried the following code
import urllib2, BeautifulSoup
def get_bytes(file):
return len(file.read())
query = 'http://myexample.file.com/file.xml'
f = urllib2.urlopen(query)
print(get_bytes(f))
soup = BeautifulSoup.BeautifulStoneSoup(f.read())
But I had the same problem. How can I determine the file size of this object without effectively destroying the file?
| [
"Copy the content of the file into a variable and work with it:\nimport urllib2, BeautifulSoup\n\nquery = 'http://myexample.file.com/file.xml'\nf = urllib2.urlopen(query)\ncontent = f.read()\nprint len(content)\nsoup = BeautifulSoup.BeautifulStoneSoup(content)\n\n"
] | [
2
] | [] | [] | [
"file_copying",
"filesize",
"python"
] | stackoverflow_0003959356_file_copying_filesize_python.txt |
Q:
Uploading images from a django application to a Google AppEngine application
I am not running Django on AppEngine. I just want to use AppEngine as a content delivery network, basically a place I can host and serve images for free. It's for a personal side project.
The situation is this: I have the URL of an image hosted on another server/provider. Instead of hotlinking to that image its better to save it on AppEngine and serve it from there - this applies mostly for thumbnails.
My questions are these:
How do I authenticate from my Django app (let's say A) to my AppEngine app (B), so that only I can upload images
How do I make a request from A to B saying "Fetch the image on this URL, create a thumbnail and save it."
How do I tell B that "For this url return that image"
How can I handle errors or timeouts? And how can this be done asynchronously?
A:
Afaik you can not store files in App Engine programmatically. You can just store them, when uploading your app.
You can however store information in its data store. So you would need to deploy an app, that authenticates your user and then writs the image to the gae's data store
A:
In my application, i use a third part server to upload a picture more than 1Mega into GAE.
So, for that; The formulaire posts all data into the third part server.
The server resizes the image and repost it to GAE.
I use a pattern iframe for the userfriendly.
The sourcecode is on github http://github.com/sahid/up2gae maybe you can you inspired by them.
| Uploading images from a django application to a Google AppEngine application | I am not running Django on AppEngine. I just want to use AppEngine as a content delivery network, basically a place I can host and serve images for free. It's for a personal side project.
The situation is this: I have the URL of an image hosted on another server/provider. Instead of hotlinking to that image its better to save it on AppEngine and serve it from there - this applies mostly for thumbnails.
My questions are these:
How do I authenticate from my Django app (let's say A) to my AppEngine app (B), so that only I can upload images
How do I make a request from A to B saying "Fetch the image on this URL, create a thumbnail and save it."
How do I tell B that "For this url return that image"
How can I handle errors or timeouts? And how can this be done asynchronously?
| [
"Afaik you can not store files in App Engine programmatically. You can just store them, when uploading your app.\nYou can however store information in its data store. So you would need to deploy an app, that authenticates your user and then writs the image to the gae's data store \n",
"In my application, i use a ... | [
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003958224_google_app_engine_python.txt |
Q:
Unpack BinaryString sent from JavaScript FileReader API to Python
I'm trying to unpack a binary string sent via Javascript's FileReader readAsBinaryString method in my python app. It seems I could use the struct module for this. I'm unsure what to provide as as the format for the unpack exactly.
Can someone confirm this is the right approach, and if so, what format I should specify?
According to the JS documentation:
The result will contain the file's data
as a binary string. Every byte is
represented by an integer in the range
[0..255].
A:
It sounds as if you just have an ordinary string (or bytes object in Python 3), so I'm not sure what you need to unpack.
One method of accessing the byte data is to use a bytearray; this lets you index the byte data easily:
>>> your_data = b'\x00\x12abc'
>>> b = bytearray(your_data)
>>> b[0]
0
>>> b[1]
18
If you have it as a string and don't want to use a bytearray (which need Python 2.6 or later) then use ord to convert the character to an integer.
>>> ord(your_data[1])
18
If your binary data has a particular interpretation in terms of groups of bytes representing integers or floats with particular endianness then the struct module is certainly your friend, but you don't need it just to examine the byte data.
| Unpack BinaryString sent from JavaScript FileReader API to Python | I'm trying to unpack a binary string sent via Javascript's FileReader readAsBinaryString method in my python app. It seems I could use the struct module for this. I'm unsure what to provide as as the format for the unpack exactly.
Can someone confirm this is the right approach, and if so, what format I should specify?
According to the JS documentation:
The result will contain the file's data
as a binary string. Every byte is
represented by an integer in the range
[0..255].
| [
"It sounds as if you just have an ordinary string (or bytes object in Python 3), so I'm not sure what you need to unpack.\nOne method of accessing the byte data is to use a bytearray; this lets you index the byte data easily:\n>>> your_data = b'\\x00\\x12abc'\n>>> b = bytearray(your_data)\n>>> b[0]\n0\n>>> b[1]\n18... | [
3
] | [] | [] | [
"filereader",
"html",
"javascript",
"python"
] | stackoverflow_0003959380_filereader_html_javascript_python.txt |
Q:
Python: getting an object's “attribute/method/property” either as a parameter to a method or as a property
In the WMI module (yeah, my boss wants me to program in Windows — but at least it’s not in COBOL), it seems that you can access a WMI value either by passing it’s name as a string parameter of a method,
blabla=wmithingy().getvalue('nameOfValue')
or as a property/method:
blabla=wmithingy().nameOfValue()
Am I dreaming, smoking bad weed, or can it effectively be done (and how)?
A:
Either the getvalue() method uses getattr(), or the __getattr__() method defers to the getvalue() method.
| Python: getting an object's “attribute/method/property” either as a parameter to a method or as a property | In the WMI module (yeah, my boss wants me to program in Windows — but at least it’s not in COBOL), it seems that you can access a WMI value either by passing it’s name as a string parameter of a method,
blabla=wmithingy().getvalue('nameOfValue')
or as a property/method:
blabla=wmithingy().nameOfValue()
Am I dreaming, smoking bad weed, or can it effectively be done (and how)?
| [
"Either the getvalue() method uses getattr(), or the __getattr__() method defers to the getvalue() method.\n"
] | [
2
] | [] | [] | [
"properties",
"python",
"windows",
"wmi"
] | stackoverflow_0003959589_properties_python_windows_wmi.txt |
Q:
Using Microsoft Access SQL operators in Python ODBC
Short version: When I try to use Access's DatePart function via ODBC, it cannot be resolved.
Longer version:
I have a Microsoft Access query which returns rows with a timestamp and a score. I want to sort it by day and then by score - effectively a high-score table for the day.
For want of a better function, I used the DatePart function to extract each of the Year, Month and Day from the timestamp, and ORDER BY them followed by Score.
In Microsoft Access, the query works beautifully.
However, when I use pyodbc to access the same query, the ODBC driver is stumped by the DatePart function, and thinks it is the name of a missing parameter.
What astonished me was that even if I hid the DatePart function, by creating a new HighScore query, and then SELECT * FROM HighScore, it still complained that it couldn't find the parameter. Apparently, the query's SQL is being resolved fairly late in the process.
My question is either:
How do I resolve the DatePart function in the SQL to allow Access to run it, or
What is a right way to sort by the day part of a timestamp over ODBC?
Added additional info:
Seems like overkill, but here's some code:
import pyodbc
access_db_path = r"<ellided>"
connection_string = 'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+access_db_path
connection = pyodbc.connect(connection_string, autocommit = True)
print "First query"
connection.cursor().execute('SELECT ScoreTime FROM SplitExtendedP1')
print "Worked"
print "Second query"
print connection.cursor().execute('SELECT DatePart("yyyy",ScoreTime) FROM SplitExtendedP1')
print "Doesn't get here."
Here are the results:
First query
Worked
Second query
Traceback (most recent call last):
File "<ellided>.py", line 16, in <module>
print connection.cursor().execute('SELECT DatePart("yyyy", ScoreTime) FROM SplitExtendedP1')
pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1. (-3010) (SQLExecDirectW)')
A:
Are you sure that using quotes "yyyy" instead of apostrophes 'yyyy' is valid in that dialect of SQL?
A:
Datetimes are stored in access as floating point numbers. The number to the left of the decimal point is the date, the fractional part to the right of the decimal point is the time (expressed in terms of a fraction of a day; ie, .5 = Noon).
If you want to sort by the day, you can simply use the Int() function to return the integer portion of the datetime field.
| Using Microsoft Access SQL operators in Python ODBC | Short version: When I try to use Access's DatePart function via ODBC, it cannot be resolved.
Longer version:
I have a Microsoft Access query which returns rows with a timestamp and a score. I want to sort it by day and then by score - effectively a high-score table for the day.
For want of a better function, I used the DatePart function to extract each of the Year, Month and Day from the timestamp, and ORDER BY them followed by Score.
In Microsoft Access, the query works beautifully.
However, when I use pyodbc to access the same query, the ODBC driver is stumped by the DatePart function, and thinks it is the name of a missing parameter.
What astonished me was that even if I hid the DatePart function, by creating a new HighScore query, and then SELECT * FROM HighScore, it still complained that it couldn't find the parameter. Apparently, the query's SQL is being resolved fairly late in the process.
My question is either:
How do I resolve the DatePart function in the SQL to allow Access to run it, or
What is a right way to sort by the day part of a timestamp over ODBC?
Added additional info:
Seems like overkill, but here's some code:
import pyodbc
access_db_path = r"<ellided>"
connection_string = 'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+access_db_path
connection = pyodbc.connect(connection_string, autocommit = True)
print "First query"
connection.cursor().execute('SELECT ScoreTime FROM SplitExtendedP1')
print "Worked"
print "Second query"
print connection.cursor().execute('SELECT DatePart("yyyy",ScoreTime) FROM SplitExtendedP1')
print "Doesn't get here."
Here are the results:
First query
Worked
Second query
Traceback (most recent call last):
File "<ellided>.py", line 16, in <module>
print connection.cursor().execute('SELECT DatePart("yyyy", ScoreTime) FROM SplitExtendedP1')
pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1. (-3010) (SQLExecDirectW)')
| [
"Are you sure that using quotes \"yyyy\" instead of apostrophes 'yyyy' is valid in that dialect of SQL?\n",
"Datetimes are stored in access as floating point numbers. The number to the left of the decimal point is the date, the fractional part to the right of the decimal point is the time (expressed in terms of ... | [
2,
2
] | [] | [] | [
"ms_access",
"odbc",
"pyodbc",
"python",
"sql"
] | stackoverflow_0003956778_ms_access_odbc_pyodbc_python_sql.txt |
Q:
Multiple communication channels with Twisted Python
I am currently researching the Twisted framework as a way of implementing a network-based backup application, and I would like to achieve something that I cannot find any examples of on the net.
I plan to implement the system using the Perspective Broker, but I will also need a way of transferring binary files from the client to the server. I would like to be able to call a method on the PB, and then use some sort of UID to send the file over a separate data channel.
The reason for having these two separate communication channels is down to the fact that I would like to make the client multi-threaded (one thread scanning the directory tree, while another thread transfers the changed files to the server).
Is this possible with Twisted? I have read that having multiple threads calling methods on a reactor is bad news, so is this architecture doomed to failure?
I would appreciate any pointers in the right direction, as I mentioned I am still researching the possibilities - but I plan to use Django for this project, so Python is a must.
A:
The reason for having these two separate communication channels is down to the fact that I would like to make the client multi-threaded (one thread scanning the directory tree, while another thread transfers the changed files to the server).
This reasoning doesn't follow. You can use a single protocol running over a single socket just fine, even if you have a thread wandering the filesystem looking for work to do.
There may be other reasons to want to send file data differently than you send metadata or other structured data between the client and server, though. However, the main one that comes to mind is that you might not want to force commands to wait for files to be completed, and this issue is relieved by PB's FilePager class.
The main thing to remember if you're going to have threads in a Twisted-using application is that whenever you want to invoke a Twisted API from any thread ''except'' the thread in which the reactor is running you must use reactor.callFromThread (or an API built solely on that method, such as twisted.internet.threads.blockingCallFromThread).
callFromThread sends some work (in the form of an object to call) to the reactor thread where the reactor will arrange to call it "soon". Any other Twisted API you invoke from the wrong thread will have undefined results.
| Multiple communication channels with Twisted Python | I am currently researching the Twisted framework as a way of implementing a network-based backup application, and I would like to achieve something that I cannot find any examples of on the net.
I plan to implement the system using the Perspective Broker, but I will also need a way of transferring binary files from the client to the server. I would like to be able to call a method on the PB, and then use some sort of UID to send the file over a separate data channel.
The reason for having these two separate communication channels is down to the fact that I would like to make the client multi-threaded (one thread scanning the directory tree, while another thread transfers the changed files to the server).
Is this possible with Twisted? I have read that having multiple threads calling methods on a reactor is bad news, so is this architecture doomed to failure?
I would appreciate any pointers in the right direction, as I mentioned I am still researching the possibilities - but I plan to use Django for this project, so Python is a must.
| [
"\nThe reason for having these two separate communication channels is down to the fact that I would like to make the client multi-threaded (one thread scanning the directory tree, while another thread transfers the changed files to the server).\n\nThis reasoning doesn't follow. You can use a single protocol runnin... | [
2
] | [] | [] | [
"python",
"tcp",
"twisted"
] | stackoverflow_0003959863_python_tcp_twisted.txt |
Q:
How do I re-route network traffic using Python?
Small apps like Freedom and Anti-social have created quite a stir lately. They cut you off from the internet either entirely or just block social networking sites in order to discourage procrastination and help you exert self control when you really want to get some work done.
I looked at the available options and also at some Google Chrome extensions and decided that none of them is exactly doing what I want, so I'm planning to write my own little Python tool to do that. My first impulse was to simply modify /etc/hosts to re-route requests to certain servers back to localhost. However, this can only block entire domains. I'd need to block addresses based on regular expressions or simple string matching to block something like google.com/reader (yes, this one in particular), but not the entire google.com domain.
Which Python framework can I use to monitor my network traffic and block blacklisted addresses and what is the basic design to achieve what I want to do? Do I use the socket library? I'm very comfortable with Python, but I'm very new to network programming.
A:
Since you're comfortable with python, I'd directly recommend twisted. It is slightly harder than some other libraries, but it is well-tested, has great performance and many features. You would just implement a small HTTP proxy and do your regexp filtering on the URLs.
| How do I re-route network traffic using Python? | Small apps like Freedom and Anti-social have created quite a stir lately. They cut you off from the internet either entirely or just block social networking sites in order to discourage procrastination and help you exert self control when you really want to get some work done.
I looked at the available options and also at some Google Chrome extensions and decided that none of them is exactly doing what I want, so I'm planning to write my own little Python tool to do that. My first impulse was to simply modify /etc/hosts to re-route requests to certain servers back to localhost. However, this can only block entire domains. I'd need to block addresses based on regular expressions or simple string matching to block something like google.com/reader (yes, this one in particular), but not the entire google.com domain.
Which Python framework can I use to monitor my network traffic and block blacklisted addresses and what is the basic design to achieve what I want to do? Do I use the socket library? I'm very comfortable with Python, but I'm very new to network programming.
| [
"Since you're comfortable with python, I'd directly recommend twisted. It is slightly harder than some other libraries, but it is well-tested, has great performance and many features. You would just implement a small HTTP proxy and do your regexp filtering on the URLs.\n"
] | [
2
] | [] | [] | [
"network_programming",
"networking",
"python",
"social_networking",
"tcp"
] | stackoverflow_0003960294_network_programming_networking_python_social_networking_tcp.txt |
Q:
How to migrate a CSV file to Sqlite3 (or MySQL)? - Python
I'm using Python in order to save the data row by row... but this is extremely slow!
The CSV contains 70million lines, and with my script I can just store 1thousand a second.
This is what my script looks like
reader = csv.reader(open('test_results.csv', 'r'))
for row in reader:
TestResult(type=row[0], name=row[1], result=row[2]).save()
I reckon that for testing I might have to consider MySQL or PostgreSQL.
Any idea or tips? This is the first time I deal with such massive volumes of data. :)
A:
For MySQL imports:
mysqlimport [options] db_name textfile1 [textfile2 ...]
For SQLite3 imports:
ref How to import load a .sql or .csv file into SQLite?
A:
I don't know if this will make a big enough difference, but since you're dealing with the Django ORM I can suggest the following:
Ensure that DEBUG is False in your Django settings file, since otherwise you're storing every single query in memory.
Put your logic in a main function, and wrap that in the django.db.transactions.commit_on_success decorator. That will prevent each row from needing it's own transaction, which will substantially speed up the process.
If you know that all of the rows in the file do not exist in the database, add force_insert=True to your call to the save() method. This will halve the number of calls to sqlite needed.
These suggestions will probably make an even bigger difference if you do find yourself using a client-server DBMS.
| How to migrate a CSV file to Sqlite3 (or MySQL)? - Python | I'm using Python in order to save the data row by row... but this is extremely slow!
The CSV contains 70million lines, and with my script I can just store 1thousand a second.
This is what my script looks like
reader = csv.reader(open('test_results.csv', 'r'))
for row in reader:
TestResult(type=row[0], name=row[1], result=row[2]).save()
I reckon that for testing I might have to consider MySQL or PostgreSQL.
Any idea or tips? This is the first time I deal with such massive volumes of data. :)
| [
"For MySQL imports:\nmysqlimport [options] db_name textfile1 [textfile2 ...]\n\nFor SQLite3 imports: \nref How to import load a .sql or .csv file into SQLite?\n",
"I don't know if this will make a big enough difference, but since you're dealing with the Django ORM I can suggest the following:\n\nEnsure that DEBUG... | [
4,
3
] | [] | [] | [
"csv",
"django",
"mysql",
"python",
"sqlite"
] | stackoverflow_0003958750_csv_django_mysql_python_sqlite.txt |
Q:
Django Forms validation error - TypeError 'str' object is not callable
so...i've been banging my head on this for a bit. I'm getting the most bizarre error when attempting to validate a form. I pass input to the form wanting to test behavior when the form fails validation, i.e. i expect it to fail validation.
i've got this code for a form:
class CTAForm(forms.Form):
first_name = forms.CharField(max_length=50)
email = forms.EmailField()
phone = forms.CharField(max_length=15, required=False, label='Phone (optional)')
And i make this call somewhere in a view in order to process the form data.
if cta_form.is_valid():
and i get:
Exception Type: TypeError
Exception Value: 'str' object is not callable
Exception Location: /usr/lib/pymodules/python2.6/django/forms/forms.py in full_clean, line 246
Traceback shows this:
/usr/lib/pymodules/python2.6/django/forms/forms.py
in full_clean:
except ValidationError, e:
self._errors[name] = self.error_class(e.messages) ...
▼ Local vars
Variable Value
e: ValidationError()
field: django.forms.fields.EmailField object at <0x225c4d0c>
name: 'email'
self: blah.views.CTAForm object at <0x2245b42c>
value: u' '
I'm feeling quite stupid. Anyone provide me with guidance on this issue? thanks.
edit: more complete view code as requested
def cta_add(request):
context_dict = {'categories': Category.objects.all().order_by('order'),}
# we always expect to receive data via post
if request.method =='POST':
# get the current vid based on the parameter
current_vid = Video.objects.get(slug=request.POST['current_vid'])
# use this video to create our dynamic form so we get the valid cta values based on that video
cta_form_class = make_cta_form(current_vid.cta_set.all().order_by('order'))
# instantiate our new dynamic form based on the post data
cta_form = cta_form_class(request.POST, error_class='error')
# if we got this far, we were able to generate a form to validate the user's input against.
# If form validates, than process and take user to success screen
if cta_form.is_valid():
helper function make_cta_form below
def make_cta_form(cta_set):
cta_list =[]
if not cta_set is None:
for cta in cta_set:
cta_list.append((cta.text, cta.text))
class CTAForm(forms.Form):
cta = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=cta_list, label='', required=False)
first_name = forms.CharField(max_length=50)
email = forms.EmailField()
phone = forms.CharField(max_length=15, required=False, label='Phone (optional)')
return CTAForm
A:
You get an error about a string not being callable, but your errorclass for your form is a string, not an error class.
cta_form = cta_form_class(request.POST, error_class='error')
Now the only reference in the docs I can find for error_class is as a list of strings, so you may just try
cta_form = cta_form_class(request.POST, error_class=['error'])
Though it seems to make more sense to do something like
import forms
[...]
cta_form = cta_form_class(request.POST, error_class=forms.ValidationError("error"))
or possibly:
cta_form = cta_form_class(request.POST, error_class=forms.ValidationError)
A:
In your views.py file. When you get the form (after the user fills up). Is this what you do?
from your_app.forms import *
def process_form(request):
cta_form = CTAForm(request.POST)
if cta_form.is_valid():
# your code.
You need to pass in the POST for your form as an initializer for the constructor.
| Django Forms validation error - TypeError 'str' object is not callable | so...i've been banging my head on this for a bit. I'm getting the most bizarre error when attempting to validate a form. I pass input to the form wanting to test behavior when the form fails validation, i.e. i expect it to fail validation.
i've got this code for a form:
class CTAForm(forms.Form):
first_name = forms.CharField(max_length=50)
email = forms.EmailField()
phone = forms.CharField(max_length=15, required=False, label='Phone (optional)')
And i make this call somewhere in a view in order to process the form data.
if cta_form.is_valid():
and i get:
Exception Type: TypeError
Exception Value: 'str' object is not callable
Exception Location: /usr/lib/pymodules/python2.6/django/forms/forms.py in full_clean, line 246
Traceback shows this:
/usr/lib/pymodules/python2.6/django/forms/forms.py
in full_clean:
except ValidationError, e:
self._errors[name] = self.error_class(e.messages) ...
▼ Local vars
Variable Value
e: ValidationError()
field: django.forms.fields.EmailField object at <0x225c4d0c>
name: 'email'
self: blah.views.CTAForm object at <0x2245b42c>
value: u' '
I'm feeling quite stupid. Anyone provide me with guidance on this issue? thanks.
edit: more complete view code as requested
def cta_add(request):
context_dict = {'categories': Category.objects.all().order_by('order'),}
# we always expect to receive data via post
if request.method =='POST':
# get the current vid based on the parameter
current_vid = Video.objects.get(slug=request.POST['current_vid'])
# use this video to create our dynamic form so we get the valid cta values based on that video
cta_form_class = make_cta_form(current_vid.cta_set.all().order_by('order'))
# instantiate our new dynamic form based on the post data
cta_form = cta_form_class(request.POST, error_class='error')
# if we got this far, we were able to generate a form to validate the user's input against.
# If form validates, than process and take user to success screen
if cta_form.is_valid():
helper function make_cta_form below
def make_cta_form(cta_set):
cta_list =[]
if not cta_set is None:
for cta in cta_set:
cta_list.append((cta.text, cta.text))
class CTAForm(forms.Form):
cta = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=cta_list, label='', required=False)
first_name = forms.CharField(max_length=50)
email = forms.EmailField()
phone = forms.CharField(max_length=15, required=False, label='Phone (optional)')
return CTAForm
| [
"You get an error about a string not being callable, but your errorclass for your form is a string, not an error class.\n cta_form = cta_form_class(request.POST, error_class='error')\n\nNow the only reference in the docs I can find for error_class is as a list of strings, so you may just try\n cta_form = cta... | [
1,
0
] | [] | [] | [
"django",
"django_forms",
"python",
"validation"
] | stackoverflow_0003952408_django_django_forms_python_validation.txt |
Q:
Read to right of specific symbol in file from Python
I'm going to separate over 1000 virus signatures and the virus names. I have them all in a text file, and would like to do this with python.
Here is the format:
virus=signature
I need to be able to take 'virus' and write it to one file, then take 'signature' and write it to another.
This is what I've tied so far:
h = open("FILEWITHSIGS")
j = h.read()
k = h.split('=')
And that is basically where I got stuck. No matter what I tried, it printed (or writed) both to the same place.
A:
with open(fname) as inputf, open(virf, 'w') as viruses, open(sigs, 'w') as signatures:
for line in inputf:
virus, _, sig = line.partition('=')
viruses.write(virus + '\n')
signatures.write(sig)
A:
f1=open("first.txt","a")
f2=open("second.txt","a")
for line in open("file"):
s=line.split("=",1)
f1.write(s[0]+"\n")
f2.write(s[-1])
f1.close()
f2.close()
| Read to right of specific symbol in file from Python | I'm going to separate over 1000 virus signatures and the virus names. I have them all in a text file, and would like to do this with python.
Here is the format:
virus=signature
I need to be able to take 'virus' and write it to one file, then take 'signature' and write it to another.
This is what I've tied so far:
h = open("FILEWITHSIGS")
j = h.read()
k = h.split('=')
And that is basically where I got stuck. No matter what I tried, it printed (or writed) both to the same place.
| [
"with open(fname) as inputf, open(virf, 'w') as viruses, open(sigs, 'w') as signatures:\n for line in inputf:\n virus, _, sig = line.partition('=')\n viruses.write(virus + '\\n')\n signatures.write(sig)\n\n",
"f1=open(\"first.txt\",\"a\")\nf2=open(\"second.txt\",\"a\")\nfor line in open(\"... | [
4,
1
] | [] | [] | [
"file",
"python",
"string"
] | stackoverflow_0003960571_file_python_string.txt |
Q:
easiest way to make a live 3d scene, a bit like a simple game (for simulator visualisation purposes)
I am building a ship simulator that will produce accurate position and orientation values for a prototype hull design in some defined sea-state.
In terms of programming, I have 2 arrays (vectors) in MATLAB containing the position and acceleration values for x, y, z, yaw, pitch and roll. Because the visualisations in MATLAB are a bit crude, I am planning to write a simple server within MATLAB to send these values (at 200Hz) using sockets to another program. The sea is modelled as an array of vertices (think of amplitude snapshots at different timesteps on a sine wave).
So my question is, what's the easiest way to animate a 3D boat and some textured water on screen?
I am only interested in the graphics engine. I have no need for sound, physics, collisions, interface (keyboard, joystick, etc). It should be able to run primarily on Windows, but it would be nice if it could run on Linux and Mac OS too (depending on the additional complexity involved).
A:
Not an expert, but few leads are
vtk, portable and integrates, regarding complexity look at sample code
comparison of engines in a related so question (and online database it links to)
The above might be called complex and bloated if compared to low level API such as OpenGL, but you have to define what kind of simplicity are you looking for.
For example, "easiest way to animate a 3D boat and some textured water" could mean that you write a clean low level interface directly on top OpenGL API; but as with anything graphics, and especially 3D, I do think that it will not be long before you will start thinking about lights, camera movement, interface, etc... and then you will probably wish for a richer environment.
So, the question is also if you want something really slim and then handle all sort of low level tasks or something that might include much more then you will ever need, but have lot of resources and shortcuts available.
Now, that my rant is finished - I am sure that you'll be able to find an exact example of animation that would take two mesh objects (sea and ship) in OpenGL and display them on screen in any decent OpenGL tutorial.
A:
The easiest way would be to use PANDA3D. it uses python and is quite complete.
A:
I've found OpenGL pretty easy to use in the past, or if you're on a Windows environment there's Direct3D too.
| easiest way to make a live 3d scene, a bit like a simple game (for simulator visualisation purposes) | I am building a ship simulator that will produce accurate position and orientation values for a prototype hull design in some defined sea-state.
In terms of programming, I have 2 arrays (vectors) in MATLAB containing the position and acceleration values for x, y, z, yaw, pitch and roll. Because the visualisations in MATLAB are a bit crude, I am planning to write a simple server within MATLAB to send these values (at 200Hz) using sockets to another program. The sea is modelled as an array of vertices (think of amplitude snapshots at different timesteps on a sine wave).
So my question is, what's the easiest way to animate a 3D boat and some textured water on screen?
I am only interested in the graphics engine. I have no need for sound, physics, collisions, interface (keyboard, joystick, etc). It should be able to run primarily on Windows, but it would be nice if it could run on Linux and Mac OS too (depending on the additional complexity involved).
| [
"Not an expert, but few leads are\n\nvtk, portable and integrates, regarding complexity look at sample code\ncomparison of engines in a related so question (and online database it links to)\n\nThe above might be called complex and bloated if compared to low level API such as OpenGL, but you have to define what kind... | [
1,
1,
0
] | [] | [] | [
"3d",
"c#",
"java",
"opengl",
"python"
] | stackoverflow_0003958772_3d_c#_java_opengl_python.txt |
Q:
Python timeit problem
I'm trying to use the timeit module but I don't know how.
I have a main:
from Foo import Foo
if __name__ == '__main__':
...
foo = Foo(arg1, arg2)
t = Timer("foo.runAlgorithm()")
print t.timeit(2)
and my Class Foo has a method named as runAlgorithm()
the error is this:
NameError: global name 'foo' is not defined
What am I doing wrong?
Can I take the time from a class method?
A:
Instead of using the necessary setup parameter for setting up the timeit environment, you can simply pass the method (or anything that is callable):
t = Timer(foo.runAlgorithm)
From the documentation:
Changed in version 2.6: The stmt and setup parameters can now also take objects that are callable without arguments.
If you need to pass some arguments, you can use function currying with functools.partial, for example:
class C:
def printargs(self, a, b):
print a, b
from functools import partial
foo = C()
t = Timer(partial(foo.printargs, 1, 2))
A:
as docs example show you need to pass setup statements:
t = Timer("foo.runAlgorithm()", 'from __main__ import foo')
| Python timeit problem | I'm trying to use the timeit module but I don't know how.
I have a main:
from Foo import Foo
if __name__ == '__main__':
...
foo = Foo(arg1, arg2)
t = Timer("foo.runAlgorithm()")
print t.timeit(2)
and my Class Foo has a method named as runAlgorithm()
the error is this:
NameError: global name 'foo' is not defined
What am I doing wrong?
Can I take the time from a class method?
| [
"Instead of using the necessary setup parameter for setting up the timeit environment, you can simply pass the method (or anything that is callable):\nt = Timer(foo.runAlgorithm)\n\nFrom the documentation:\n\nChanged in version 2.6: The stmt and setup parameters can now also take objects that are callable without a... | [
16,
2
] | [] | [] | [
"python",
"timeit"
] | stackoverflow_0003960834_python_timeit.txt |
Q:
Basic Python file searching and I/O
I'm trying to complete a simple task in Python and I'm new to the language (I'm C++). I hope someone might be able to point me in the right direction.
Problem:
I have an XML file (12mb) full of data and within the file there are start tags 'xmltag' and end tags '/xmltag' that represent the start and end of the data sections I would like to pull out.
I would like to navigate through this open file with a loop and for each instance locate a start tag and copy the data within the section to a new file until the end tag. I would then like to repeat this to the end of the file.
I'm happy with the file I/O but not the most efficient looping, searching and extracting of the data.
I really like the look of the language and hopefully I'm going to get more involved so I can give back to the community.
Big thanks!
A:
Check BeautifulSoup
from BeautifulSoup import BeautifulSoup
with open('bigfile.xml', 'r') as xml:
soup = BeautifulSoup(xml):
for xmltag in soup('xmltag'):
print xmltag.contents
A:
Dive Into Python 3 have a great chapter about this:
http://diveintopython3.org/xml.html#xml-parse
It'a great free book about python, worth reading !
A:
The BeautifulSoup answer is good but this executes faster and doesn't require an external library:
import xml.etree.cElementTree as ET
tree = ET.parse('xmlfile.xml')
results = (elem for elem in tree.getiterator('xmltag'))
# in Python 2.7+, getiterator() is deprecated; use tree.iter('xmltag')
A:
No need to install BeautifulSoup, Python includes the ElementTree parser in its standard library.
from xml.etree import cElementTree as ET
tree = ET.parse('myfilename')
new_tree = ET('new_root_element')
for element in tree.findall('.//xmltag'):
new_tree.append(tree.element)
print ET.tostring(new_tree)
| Basic Python file searching and I/O | I'm trying to complete a simple task in Python and I'm new to the language (I'm C++). I hope someone might be able to point me in the right direction.
Problem:
I have an XML file (12mb) full of data and within the file there are start tags 'xmltag' and end tags '/xmltag' that represent the start and end of the data sections I would like to pull out.
I would like to navigate through this open file with a loop and for each instance locate a start tag and copy the data within the section to a new file until the end tag. I would then like to repeat this to the end of the file.
I'm happy with the file I/O but not the most efficient looping, searching and extracting of the data.
I really like the look of the language and hopefully I'm going to get more involved so I can give back to the community.
Big thanks!
| [
"Check BeautifulSoup\nfrom BeautifulSoup import BeautifulSoup\n\nwith open('bigfile.xml', 'r') as xml:\n soup = BeautifulSoup(xml):\n for xmltag in soup('xmltag'):\n print xmltag.contents\n\n",
"Dive Into Python 3 have a great chapter about this:\n\nhttp://diveintopython3.org/xml.html#xml-parse\n\nIt... | [
4,
2,
1,
0
] | [
"xml=open(\"xmlfile\").read()\nx=xml.split(\"</xmltag>\")\nfor block in x:\n if \"<xmltag>\" in block:\n print block.split(\"<xmltag>\")[-1]\n\n"
] | [
-2
] | [
"file",
"python",
"search",
"text",
"xml"
] | stackoverflow_0003959989_file_python_search_text_xml.txt |
Q:
Get current system time of a machine on the network
I understand that I can query system time of my machine like this:
from datetime import datetime
datetime.now()
Is there a way to query the system time of another machine on the windows network?
Eg of \\mynetworkpc.
A:
on a Windows machine there is net time \\<remote-ip address> to get the time of a remote machine but I don't know if it is portable.
>>> import subprocess
>>> subprocess.call(r"net time \\172.21.5.135")
Current time at \\172.21.5.135 is 10/18/2010 12:32 PM
The command completed successfully.
0
>>>
A:
You could combine a Python WMI module with the answers to this question: get-remote-pcs-date-time
| Get current system time of a machine on the network | I understand that I can query system time of my machine like this:
from datetime import datetime
datetime.now()
Is there a way to query the system time of another machine on the windows network?
Eg of \\mynetworkpc.
| [
"on a Windows machine there is net time \\\\<remote-ip address> to get the time of a remote machine but I don't know if it is portable.\n>>> import subprocess\n>>> subprocess.call(r\"net time \\\\172.21.5.135\")\nCurrent time at \\\\172.21.5.135 is 10/18/2010 12:32 PM\n\nThe command completed successfully.\n\n0\n>>... | [
6,
0
] | [] | [] | [
"networking",
"python",
"system",
"time"
] | stackoverflow_0003960829_networking_python_system_time.txt |
Q:
Python function prints None
I have the following exercise:
The parameter weekday is True if it is
a weekday, and the parameter vacation
is True if we are on vacation. We
sleep in if it is not a weekday or
we're on vacation. Return True if we
sleep in.
Here's what I've done, but the second print function only prints 'None'.
def sleep_in(weekday, vacation):
if(not weekday or vacation):
return True
print(sleep_in(False, False))
print(sleep_in(True, False))
print(sleep_in(False, True))
Output:
True
None
True
A:
Functions in python return None unless explicitly instructed to do otherwise.
In your function above, you don't take into account the case in which weekday is True. The interpreter reaches the end of the function without reading a return statement (since the condition predecing yours evaluates to False), and returns None.
Edit:
def sleep_in(weekday, vacation):
return (not weekday or vacation)
There you go =)
| Python function prints None | I have the following exercise:
The parameter weekday is True if it is
a weekday, and the parameter vacation
is True if we are on vacation. We
sleep in if it is not a weekday or
we're on vacation. Return True if we
sleep in.
Here's what I've done, but the second print function only prints 'None'.
def sleep_in(weekday, vacation):
if(not weekday or vacation):
return True
print(sleep_in(False, False))
print(sleep_in(True, False))
print(sleep_in(False, True))
Output:
True
None
True
| [
"Functions in python return None unless explicitly instructed to do otherwise.\nIn your function above, you don't take into account the case in which weekday is True. The interpreter reaches the end of the function without reading a return statement (since the condition predecing yours evaluates to False), and retu... | [
6
] | [] | [] | [
"function",
"python",
"return_value"
] | stackoverflow_0003961099_function_python_return_value.txt |
Q:
I'm new to python and having trouble with this looping code
I'm trying to copy sections in a file within a set of XML tags
> <tag>I want to copy the data here</tag>`
Please note I found out the data around the tags is not valid XML so I can't import a normal library and have to find it via string comparison :( *
There are multiple sections of text I want to extract in the file so I'm trying to loop through the file to find each one. I just wanted to do this on a line-by-line basis till I figured out how to parse the lines of unwanted text and created the following code:
InputFile=open('xml_input_File.xml','r')
OutputFile=open('xml_output_file.xml', 'w')
check = 0
for line in InputFile.readlines():
if line.find("<STARTTAG>"):
check = 1
elif line.find(r"<//STARTTAG>"):
check = 0
if check == 1:
OutputFile.write(line)
The problem I'm having is it simply copies the whole file and not just the sections I would like.
I know the code is not very pretty but I'm still learning and its going to be a "d'oh!" moment but thanks for your help!!
Cheers
A:
There's a few issues with your code:
If input is really in the format of "<STARTTAG> ... </STARTTAG>", capturing lines isn't going to cut it as you're going to grab at least the <STARTTAG> instance.
You're using a literal string prefix (r"<//STARTTAG>") but you're using two forward slashes. From your example above, it looks like the closing tags only have one forward slash. I'm not sure why you need to use the literal string prefix at all here. If this is incorrect, that's probably why the check variable is never set to 0 (hence, the code copies the whole file).
Edit: the point other posters have made about the return value of find() is very valid as well. Using the in keyword is likely a better bet.
You need to look into splitting up your input (parsing), either manually (via split()) or by some regular expressions. Alternatively, you could try and groom your input into a compliant XML format and then use one of the many freely available libraries to handle this sort of thing.
Hope this helps!
A:
Help on method_descriptor:
find(...)
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within s[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
-1 is also a True value.
try:
if "<STARTTAG>" in line:
etc.
Also, forward slash doesn't need to be escaped (even less in raw strings!).
A:
find returns index of substring in the line. Probably that starttag is on the beginning of the line (index is zero) so if doesn't work as it should.
Try:
if line.find("<STARTTAG>") != -1:
or even better
if "<starttag>" in line:
or use some XML parser for python.
| I'm new to python and having trouble with this looping code | I'm trying to copy sections in a file within a set of XML tags
> <tag>I want to copy the data here</tag>`
Please note I found out the data around the tags is not valid XML so I can't import a normal library and have to find it via string comparison :( *
There are multiple sections of text I want to extract in the file so I'm trying to loop through the file to find each one. I just wanted to do this on a line-by-line basis till I figured out how to parse the lines of unwanted text and created the following code:
InputFile=open('xml_input_File.xml','r')
OutputFile=open('xml_output_file.xml', 'w')
check = 0
for line in InputFile.readlines():
if line.find("<STARTTAG>"):
check = 1
elif line.find(r"<//STARTTAG>"):
check = 0
if check == 1:
OutputFile.write(line)
The problem I'm having is it simply copies the whole file and not just the sections I would like.
I know the code is not very pretty but I'm still learning and its going to be a "d'oh!" moment but thanks for your help!!
Cheers
| [
"There's a few issues with your code:\n\nIf input is really in the format of \"<STARTTAG> ... </STARTTAG>\", capturing lines isn't going to cut it as you're going to grab at least the <STARTTAG> instance.\nYou're using a literal string prefix (r\"<//STARTTAG>\") but you're using two forward slashes. From your exam... | [
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003961227_python_string.txt |
Q:
call remote programs by URL with python
I am developing a GUI in python with wxPython framework to launch several subprocess programs. Now I could do it for the local files, e.g. if we have a compiled .out file under the path "/AAA/BBB/xxx.out", I could do with command like this:
subprocess.Popen("/AAA/BBB/xxx.out", stdout=subprocess.PIPE)
Now, I am thinking to develop the following two URL-related remote features, still calling them as subprocesses (because the main process is the GUI), but I do not know how to do it in python.
1) how to launch the program, given the url of the .out file? e.g. given http://www.ABC.com/xxx.out
2) how to launch the program, given the url of the source code of this .out file (e.g. http://www.ABC.com/xxx/src/ contains the C++ source code and the makefile of the program)
what kind of python module could be used and what potential problems might be envolved? Usually what is the right way to implement these two features?
Thanks a lot for any suggestions or sample code (that will be very helpful)!!
A:
For loading this online file as subprocess from within your program, you are going to have to download it for a temporary location. Just use urllib2 module to download the file together with http://docs.python.org/library/tempfile.html to create a temporary placeholder for it. They you can execute it.
A:
There's two very separate parts to your question: how to get a file from a remote URL, and how to execute it.
You seem to have the first part covered, so just google how to download files with Python. You can also use an already existing file downloader for the task (you already have the executing subprocesses part done), or better still, an existing Python module.
Now, given the URL of a source code,... source code of what? I mean, if it's python, you can run it in an interpreter, but you may need to compile source code in other languages, and that may have dependencies, and other complications.
| call remote programs by URL with python | I am developing a GUI in python with wxPython framework to launch several subprocess programs. Now I could do it for the local files, e.g. if we have a compiled .out file under the path "/AAA/BBB/xxx.out", I could do with command like this:
subprocess.Popen("/AAA/BBB/xxx.out", stdout=subprocess.PIPE)
Now, I am thinking to develop the following two URL-related remote features, still calling them as subprocesses (because the main process is the GUI), but I do not know how to do it in python.
1) how to launch the program, given the url of the .out file? e.g. given http://www.ABC.com/xxx.out
2) how to launch the program, given the url of the source code of this .out file (e.g. http://www.ABC.com/xxx/src/ contains the C++ source code and the makefile of the program)
what kind of python module could be used and what potential problems might be envolved? Usually what is the right way to implement these two features?
Thanks a lot for any suggestions or sample code (that will be very helpful)!!
| [
"For loading this online file as subprocess from within your program, you are going to have to download it for a temporary location. Just use urllib2 module to download the file together with http://docs.python.org/library/tempfile.html to create a temporary placeholder for it. They you can execute it.\n",
"There... | [
0,
0
] | [] | [] | [
"python",
"url"
] | stackoverflow_0003961507_python_url.txt |
Q:
Need help understanding ReferenceProperty
Say I have two classes:
class A(db.Model):
class B(db.Model):
a_reference = ReferenceProperty(A)
I can now do the following:
a = A()
a.put()
b = B();
b.a_reference = a.key()
b.put()
The documentation states the following two things:
The ReferenceProperty value can be used as if it were a model instance, and the datastore entity will be fetched and the model instance created when it is first used in this way.
And later also states:
An application can explicitly db.get() the value of a ReferenceProperty (which is a Key) to test whether the referenced entity exists.
So what does that mean? The value is a key but it can be used a model instance?
If I do:
a2 = b.a_reference
a2 will be of type A, not key. Does this mean that the variable a_reference will behave like a model instance until that instance is deleted, whereafter it will return a key (pointing to a non-existing instance)?
A:
A ReferenceProperty will always try to return an instance of the class that the stored key points to. If the referenced object has been deleted, I believe that you get back None. From the docs:
obj1 = obj2.reference
if not obj1:
# Referenced entity was deleted.
If you want to get the key that was originally stored, you can use get_value_for_datastore:
a = A()
a.put()
b = B();
b.a_reference = a.key()
b.put()
orginial_key = b.a_reference.get_value_for_datastore()
| Need help understanding ReferenceProperty | Say I have two classes:
class A(db.Model):
class B(db.Model):
a_reference = ReferenceProperty(A)
I can now do the following:
a = A()
a.put()
b = B();
b.a_reference = a.key()
b.put()
The documentation states the following two things:
The ReferenceProperty value can be used as if it were a model instance, and the datastore entity will be fetched and the model instance created when it is first used in this way.
And later also states:
An application can explicitly db.get() the value of a ReferenceProperty (which is a Key) to test whether the referenced entity exists.
So what does that mean? The value is a key but it can be used a model instance?
If I do:
a2 = b.a_reference
a2 will be of type A, not key. Does this mean that the variable a_reference will behave like a model instance until that instance is deleted, whereafter it will return a key (pointing to a non-existing instance)?
| [
"A ReferenceProperty will always try to return an instance of the class that the stored key points to. If the referenced object has been deleted, I believe that you get back None. From the docs:\nobj1 = obj2.reference\n\nif not obj1:\n # Referenced entity was deleted.\n\nIf you want to get the key that was origi... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"referenceproperty"
] | stackoverflow_0003961449_google_app_engine_python_referenceproperty.txt |
Q:
What does this Python code mean?
__author__="Sergio.Tapia"
__date__ ="$18-10-2010 12:03:29 PM$"
if __name__ == "__main__":
print("Hello")
print(__author__)
Where does it get __main__ and __name__?
Thanks for the help
A:
The __name__ variable is made available by the runtime. It's the name of the current module, the name under which it was imported. "__main__" is a string. It's not special, it's just a string. It also happens to be the name of the main script when it is executed.
The if __name__ == "__main__": mechanism is the common way of doing something when a .py file is executed directly, but not when it is imported as a module.
A:
Python modules can also be run as standalone scripts. As such, code within the if __name__ == "__main__": block will only run if the module is executed as the "main" file.
Example:
#foo.py
def msg():
print("bar")
if __name__ == "__main__":
msg()
Running this module will output
$ python foo.py
bar
where as importing it will output nothing.
>>> import foo
>>> foo.msg()
bar
Reference
| What does this Python code mean? | __author__="Sergio.Tapia"
__date__ ="$18-10-2010 12:03:29 PM$"
if __name__ == "__main__":
print("Hello")
print(__author__)
Where does it get __main__ and __name__?
Thanks for the help
| [
"The __name__ variable is made available by the runtime. It's the name of the current module, the name under which it was imported. \"__main__\" is a string. It's not special, it's just a string. It also happens to be the name of the main script when it is executed. \nThe if __name__ == \"__main__\": mechanism is t... | [
9,
2
] | [] | [] | [
"python",
"python_datamodel"
] | stackoverflow_0003960958_python_python_datamodel.txt |
Q:
Nested Dictionaries in Python, with implicit creation of non-existing intermediate containers?
I want to create a polymorphic structure that can be created on the fly with minimum typing effort and be very readable. For example:
a.b = 1
a.c.d = 2
a.c.e = 3
a.f.g.a.b.c.d = cucu
a.aaa = bau
I do not want to create an intermediate container such as:
a.c = subobject()
a.c.d = 2
a.c.e = 3
My question is similar to this one:
What is the best way to implement nested dictionaries?
But I am not happy with the solution there because I think there is a bug:
Items will be created even when you don't want: suppose you want to compare 2 polymorphic structures: it will create in the 2nd structure any attribute that exists in the first and is just checked in the other. e.g:
a = {1:2, 3: 4}
b = {5:6}
# now compare them:
if b[1] == a[1]
# whoops, we just created b[1] = {} !
I also want to get the simplest possible notation
a.b.c.d = 1
# neat
a[b][c][d] = 1
# yuck
I did try to derive from the object class... but I couldn't avoid to leave the same bug as above where attributes were born just by trying to read them: a simple dir() would try to create attributes like "methods"... like in this example, which is obviously broken:
class KeyList(object):
def __setattr__(self, name, value):
print "__setattr__ Name:", name, "value:", value
object.__setattr__(self, name, value)
def __getattribute__(self, name):
print "__getattribute__ called for:", name
return object.__getattribute__(self, name)
def __getattr__(self, name):
print "__getattr__ Name:", name
try:
ret = object.__getattribute__(self, name)
except AttributeError:
print "__getattr__ not found, creating..."
object.__setattr__(self, name, KeyList())
ret = object.__getattribute__(self, name)
return ret
>>> cucu = KeyList()
>>> dir(cucu)
__getattribute__ called for: __dict__
__getattribute__ called for: __members__
__getattr__ Name: __members__
__getattr__ not found, creating...
__getattribute__ called for: __methods__
__getattr__ Name: __methods__
__getattr__ not found, creating...
__getattribute__ called for: __class__
Thanks, really!
p.s.: the best solution I found so far is:
class KeyList(dict):
def keylset(self, path, value):
attr = self
path_elements = path.split('.')
for i in path_elements[:-1]:
try:
attr = attr[i]
except KeyError:
attr[i] = KeyList()
attr = attr[i]
attr[path_elements[-1]] = value
# test
>>> a = KeyList()
>>> a.keylset("a.b.d.e", "ferfr")
>>> a.keylset("a.b.d", {})
>>> a
{'a': {'b': {'d': {}}}}
# shallow copy
>>> b = copy.copy(a)
>>> b
{'a': {'b': {'d': {}}}}
>>> b.keylset("a.b.d", 3)
>>> b
{'a': {'b': {'d': 3}}}
>>> a
{'a': {'b': {'d': 3}}}
# complete copy
>>> a.keylset("a.b.d", 2)
>>> a
{'a': {'b': {'d': 2}}}
>>> b
{'a': {'b': {'d': 2}}}
>>> b = copy.deepcopy(a)
>>> b.keylset("a.b.d", 4)
>>> b
{'a': {'b': {'d': 4}}}
>>> a
{'a': {'b': {'d': 2}}}
A:
I think at a minimum you need to do a check in __getattr__ that the requested attrib doesn't start and end with __. Attributes which match that description implement established Python APIs, so you shouldn't be instantiating those attributes. Even so you'll still end up implementing some API attribs, like for example next. In that case you would end up with an exception being thrown if you pass the object to some function that uses duck typing to see if it's an iterator.
It would really be better to create a "whitelist" of valid attrib names, either as a literal set, or with a simple formula: e.g. name.isalpha() and len(name) == 1 would work for the one-letter attribs you're using in the example. For a more realistic implementation you'd probably want to define a set of names appropriate to the domain your code is working in.
I guess the alternative is to make sure that you're not dynamically creating any of the various attribute names that are part of some protocol, as next is part of the iteration protocol. The methods of the ABCs in the collections module comprise a partial list, but I don't know where to find a full one.
You are also going to have to keep track of whether or not the object has created any such child nodes, so that you will know how to do comparisons against other such objects.
If you want comparisons to avoid autovivification, you will have to implement a __cmp__ method, or rich comparison methods, in the class that checks the __dict__s of the objects being compared.
I have a sneaking feeling that there's a few complications I didn't think of, which wouldn't be surprising since this is not really how Python is supposed to work. Tread carefully, and think about whether the added complexity of this approach is worth what it will get you.
A:
If you're looking for something that's not as dynamic as your original post, but more like your best solution so far, you might see if Ian Bicking's formencode's variabledecode would meet your needs. The package itself is intended for web forms and validation, but a few of the methods seem pretty close to what you're looking for.
If nothing else, it might serve as an example for your own implementation.
A small example:
>>> from formencode.variabledecode import variable_decode, variable_encode
>>>
>>> d={'a.b.c.d.e': 1}
>>> variable_decode(d)
{'a': {'b': {'c': {'d': {'e': 1}}}}}
>>>
>>> d['a.b.x'] = 3
>>> variable_decode(d)
{'a': {'b': {'c': {'d': {'e': 1}}, 'x': 3}}}
>>>
>>> d2 = variable_decode(d)
>>> variable_encode(d2) == d
True
| Nested Dictionaries in Python, with implicit creation of non-existing intermediate containers? | I want to create a polymorphic structure that can be created on the fly with minimum typing effort and be very readable. For example:
a.b = 1
a.c.d = 2
a.c.e = 3
a.f.g.a.b.c.d = cucu
a.aaa = bau
I do not want to create an intermediate container such as:
a.c = subobject()
a.c.d = 2
a.c.e = 3
My question is similar to this one:
What is the best way to implement nested dictionaries?
But I am not happy with the solution there because I think there is a bug:
Items will be created even when you don't want: suppose you want to compare 2 polymorphic structures: it will create in the 2nd structure any attribute that exists in the first and is just checked in the other. e.g:
a = {1:2, 3: 4}
b = {5:6}
# now compare them:
if b[1] == a[1]
# whoops, we just created b[1] = {} !
I also want to get the simplest possible notation
a.b.c.d = 1
# neat
a[b][c][d] = 1
# yuck
I did try to derive from the object class... but I couldn't avoid to leave the same bug as above where attributes were born just by trying to read them: a simple dir() would try to create attributes like "methods"... like in this example, which is obviously broken:
class KeyList(object):
def __setattr__(self, name, value):
print "__setattr__ Name:", name, "value:", value
object.__setattr__(self, name, value)
def __getattribute__(self, name):
print "__getattribute__ called for:", name
return object.__getattribute__(self, name)
def __getattr__(self, name):
print "__getattr__ Name:", name
try:
ret = object.__getattribute__(self, name)
except AttributeError:
print "__getattr__ not found, creating..."
object.__setattr__(self, name, KeyList())
ret = object.__getattribute__(self, name)
return ret
>>> cucu = KeyList()
>>> dir(cucu)
__getattribute__ called for: __dict__
__getattribute__ called for: __members__
__getattr__ Name: __members__
__getattr__ not found, creating...
__getattribute__ called for: __methods__
__getattr__ Name: __methods__
__getattr__ not found, creating...
__getattribute__ called for: __class__
Thanks, really!
p.s.: the best solution I found so far is:
class KeyList(dict):
def keylset(self, path, value):
attr = self
path_elements = path.split('.')
for i in path_elements[:-1]:
try:
attr = attr[i]
except KeyError:
attr[i] = KeyList()
attr = attr[i]
attr[path_elements[-1]] = value
# test
>>> a = KeyList()
>>> a.keylset("a.b.d.e", "ferfr")
>>> a.keylset("a.b.d", {})
>>> a
{'a': {'b': {'d': {}}}}
# shallow copy
>>> b = copy.copy(a)
>>> b
{'a': {'b': {'d': {}}}}
>>> b.keylset("a.b.d", 3)
>>> b
{'a': {'b': {'d': 3}}}
>>> a
{'a': {'b': {'d': 3}}}
# complete copy
>>> a.keylset("a.b.d", 2)
>>> a
{'a': {'b': {'d': 2}}}
>>> b
{'a': {'b': {'d': 2}}}
>>> b = copy.deepcopy(a)
>>> b.keylset("a.b.d", 4)
>>> b
{'a': {'b': {'d': 4}}}
>>> a
{'a': {'b': {'d': 2}}}
| [
"I think at a minimum you need to do a check in __getattr__ that the requested attrib doesn't start and end with __. Attributes which match that description implement established Python APIs, so you shouldn't be instantiating those attributes. Even so you'll still end up implementing some API attribs, like for ex... | [
1,
1
] | [] | [] | [
"creation",
"dictionary",
"implicit",
"nested",
"python"
] | stackoverflow_0003955898_creation_dictionary_implicit_nested_python.txt |
Q:
What do these arguments refer to?
In the method of the class urllib2.HTTPDefaultErrorHandler what so the arguments - self, req, fp, code,msg, hdrs - refer to?
A:
What does the documentation say?
req will be a Request object, fp will be a file-like object with the HTTP error body, code will be the three-digit code of the error, msg will be the user-visible explanation of the code and hdrs will be a mapping object with the headers of the error.
A:
Req refers to request object usually contains HTTP method and url
code refers to response code or HTTP code value like 200 etc
hdr refers to headers of the request like user-agent etc
fp refers to file descriptor or socket descriptor in this case
| What do these arguments refer to? | In the method of the class urllib2.HTTPDefaultErrorHandler what so the arguments - self, req, fp, code,msg, hdrs - refer to?
| [
"What does the documentation say?\nreq will be a Request object, fp will be a file-like object with the HTTP error body, code will be the three-digit code of the error, msg will be the user-visible explanation of the code and hdrs will be a mapping object with the headers of the error.\n",
"\nReq refers to reques... | [
3,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003961945_python_urllib2.txt |
Q:
Python - functions being called inside list bracket. How does it work?
I was looking for an algorithm to replace some content inside a list with another. For instance, changing all the '0' with 'X'.
I found this piece of code, which works:
list = ['X' if coord == '0' else coord for coord in printready]
What I would like to know is exactly why this works (I understand the logic in the code, just not why the compiler accepts this.)
I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').
This is probably thoroughly documented, but I have no idea on what this thing is called.
A:
This construction is called a list comprehension. These look similar to generator expressions but are slightly different. List comprehensions create a new list up front, while generator expressions create each new element as needed. List comprehensions must be finite; generators may be "infinite".
A:
I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').
If you're going to substitute multiple variables, I would use a dictionary instead of an "elif". This makes your code easier to read, and it's easy to add/remove substitutions.
d = {'0':'X', '1':'Y', '2':'Z'}
lst = [d[coord] if coord in d else coord for coord in printready]
| Python - functions being called inside list bracket. How does it work? | I was looking for an algorithm to replace some content inside a list with another. For instance, changing all the '0' with 'X'.
I found this piece of code, which works:
list = ['X' if coord == '0' else coord for coord in printready]
What I would like to know is exactly why this works (I understand the logic in the code, just not why the compiler accepts this.)
I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').
This is probably thoroughly documented, but I have no idea on what this thing is called.
| [
"This construction is called a list comprehension. These look similar to generator expressions but are slightly different. List comprehensions create a new list up front, while generator expressions create each new element as needed. List comprehensions must be finite; generators may be \"infinite\".\n",
"\nI'm a... | [
7,
4
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0003961923_list_comprehension_python.txt |
Q:
How to display an image from web?
I have written this simple script in python:
import gtk
window = gtk.Window()
window.set_size_request(800, 700)
window.show()
gtk.main()
now I want to load in this window an image from web ( and not from my PC ) like this:
http://www.dailygalaxy.com/photos/uncategorized/2007/05/05/planet_x.jpg
How can I do that ?
P.S. I don't want download the image ! I just want load the image from the URL.
A:
This downloads the image from a url, but writes the data into a gtk.gdk.Pixbuf instead of to a file:
import pygtk
pygtk.require('2.0')
import gtk
import urllib2
class MainWin:
def destroy(self, widget, data=None):
print "destroy signal occurred"
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.destroy)
self.window.set_border_width(10)
self.image=gtk.Image()
response=urllib2.urlopen(
'http://www.dailygalaxy.com/photos/uncategorized/2007/05/05/planet_x.jpg')
loader=gtk.gdk.PixbufLoader()
loader.write(response.read())
loader.close()
self.image.set_from_pixbuf(loader.get_pixbuf())
# This does the same thing, but by saving to a file
# fname='/tmp/planet_x.jpg'
# with open(fname,'w') as f:
# f.write(response.read())
# self.image.set_from_file(fname)
self.window.add(self.image)
self.image.show()
self.window.show()
def main(self):
gtk.main()
if __name__ == "__main__":
MainWin().main()
A:
Download the image. Google on how to download files with python, there are easy-to-use libraries for that.
Load the image into a widget. Look up how to display an image in GTK.
Sorry for the lack of detail, but the answer would get long and you'd still be better off reading on those subjects somewhere else.
Hope it helps!
A:
Here's a simple script using WebKit:
#!/usr/bin/env python
import gtk
import webkit
window = gtk.Window()
window.set_size_request(800, 700)
webview = webkit.WebView()
window.add(webview)
window.show_all()
webview.load_uri('http://www.dailygalaxy.com/photos/uncategorized/2007/05/05/planet_x.jpg')
gtk.main()
Take note, though, that this does in fact download the image.
| How to display an image from web? | I have written this simple script in python:
import gtk
window = gtk.Window()
window.set_size_request(800, 700)
window.show()
gtk.main()
now I want to load in this window an image from web ( and not from my PC ) like this:
http://www.dailygalaxy.com/photos/uncategorized/2007/05/05/planet_x.jpg
How can I do that ?
P.S. I don't want download the image ! I just want load the image from the URL.
| [
"This downloads the image from a url, but writes the data into a gtk.gdk.Pixbuf instead of to a file:\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport urllib2\n\nclass MainWin:\n\n def destroy(self, widget, data=None):\n print \"destroy signal occurred\"\n gtk.main_quit()\n\n def __init__... | [
15,
3,
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003962180_gtk_pygtk_python.txt |
Q:
python 2to3 manual modification
Is there a way to change python2.x source code to python 3.x manually. I guess using lib2to3 this can be done but I don't know exactly how to do this ?
A:
Yes, porting is what you are looking here.
Porting is a non-trivial task that requires making various decisions about your code. For instance, whether or not you want to maintaing backward compatibility. There is no single, universal solution to porting. The way you port depends on your specific requirements.
The best resource I have found for porting apps from Python 2 to 3 is the wiki page PortingPythonToPy3k. The page contains several approaches to porting as well as a lot of links to resources that are potentially helpful in porting work.
A:
Thanks. Here is the answer I was looking for:
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
"""assume `files` to a be a list of all filenames you want to convert"""
r = RefactoringTool(get_fixers_from_package('lib2to3.fixes'))
r.refactor(files, write=True)
| python 2to3 manual modification | Is there a way to change python2.x source code to python 3.x manually. I guess using lib2to3 this can be done but I don't know exactly how to do this ?
| [
"Yes, porting is what you are looking here.\nPorting is a non-trivial task that requires making various decisions about your code. For instance, whether or not you want to maintaing backward compatibility. There is no single, universal solution to porting. The way you port depends on your specific requirements.\nTh... | [
4,
2
] | [] | [] | [
"python",
"python_2to3"
] | stackoverflow_0003950330_python_python_2to3.txt |
Q:
gtk: why do Gtk::Main::Iteration?
What's the point of doing the Gtk::Main::iteration() on the last two lines of the answer to this question? I'm using pygtk, so the equivalent question would be, why do gtk.main_iteration_do()? Isn't the main loop that's running already taking care of this?
A:
When I wrote that answer, I was assuming that the items would be added in a long loop - for example in a callback somewhere. Unless you're explicitly doing the work in a separate thread, then the main loop is in fact not running during that code. The code there tells the window to scroll to the bottom, but the scrolling only actually happens when the main loop regains control.
"While events pending, do main interation" in whatever language is an often-used way to run the main loop until all waiting GUI updates have been processed.
A:
These functions exist to let you create your own loop, and have an iteration of GTK's loop run somewhere in it.
You may want to take care of other stuff while the loop runs, in the same thread/process as the loop. Many libraries with main loops provide either a way to schedule tasks in their main loop, or a function to run a single iteration of the loop for you embed somewhere else.
| gtk: why do Gtk::Main::Iteration? | What's the point of doing the Gtk::Main::iteration() on the last two lines of the answer to this question? I'm using pygtk, so the equivalent question would be, why do gtk.main_iteration_do()? Isn't the main loop that's running already taking care of this?
| [
"When I wrote that answer, I was assuming that the items would be added in a long loop - for example in a callback somewhere. Unless you're explicitly doing the work in a separate thread, then the main loop is in fact not running during that code. The code there tells the window to scroll to the bottom, but the scr... | [
3,
2
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003961977_gtk_pygtk_python.txt |
Q:
Unable to print variables in Python when using def function
I am trying to implement a simple neural net. I want to print the initial pattern, weights, activation. I then want it to print the learning process (i.e. every pattern it goes through as it learns). I am as yet unable to do this - it returns the initial and final pattern (whn I put print p in appropriate places), but nothing else. Hints and tips appreciated - I'm a complete newbie to Python!
#!/usr/bin/python
import random
p = [ [1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1] ] # pattern I want the net to learn
n = 5
alpha = 0.01
activation = [] # unit activations
weights = [] # weights
output = [] # output
def initWeights(n): # set weights to zero, n is the number of units
global weights
weights = [[[0]*n]*n] # initialised to zero
def initNetwork(p): # initialises units to activation
global activation
activation = p
def updateNetwork(k): # pick unit at random and update k times
for l in range(k):
unit = random.randint(0,n-1)
activation[unit] = 0
for i in range(n):
activation[unit] += output[i] * weights[unit][i]
output[unit] = 1 if activation[unit] > 0 else -1
def learn(p):
for i in range(n):
for j in range(n):
weights += alpha * p[i] * p[j]
A:
You have a problem with the line:
weights = [[[0]*n]*n]
When you use*, you multiply object references. You are using the same n-len array of zeroes every time. This will cause:
>>> weights[0][1][0] = 8
>>> weights
[[[8, 0, 0], [8, 0, 0], [8, 0, 0]]]
The first item of all the sublists is 8, because they are one and the same list. You stored the same reference multiple times, and so modifying the n-th item on any of them will alter all of them.
A:
this the line is where you get :
"IndexError: list index out of range"
output[unit] = 1 if activation[unit] > 0 else -1
because output = [] , you should do output.append() or ...
| Unable to print variables in Python when using def function | I am trying to implement a simple neural net. I want to print the initial pattern, weights, activation. I then want it to print the learning process (i.e. every pattern it goes through as it learns). I am as yet unable to do this - it returns the initial and final pattern (whn I put print p in appropriate places), but nothing else. Hints and tips appreciated - I'm a complete newbie to Python!
#!/usr/bin/python
import random
p = [ [1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1] ] # pattern I want the net to learn
n = 5
alpha = 0.01
activation = [] # unit activations
weights = [] # weights
output = [] # output
def initWeights(n): # set weights to zero, n is the number of units
global weights
weights = [[[0]*n]*n] # initialised to zero
def initNetwork(p): # initialises units to activation
global activation
activation = p
def updateNetwork(k): # pick unit at random and update k times
for l in range(k):
unit = random.randint(0,n-1)
activation[unit] = 0
for i in range(n):
activation[unit] += output[i] * weights[unit][i]
output[unit] = 1 if activation[unit] > 0 else -1
def learn(p):
for i in range(n):
for j in range(n):
weights += alpha * p[i] * p[j]
| [
"You have a problem with the line:\nweights = [[[0]*n]*n]\n\nWhen you use*, you multiply object references. You are using the same n-len array of zeroes every time. This will cause:\n>>> weights[0][1][0] = 8\n>>> weights\n[[[8, 0, 0], [8, 0, 0], [8, 0, 0]]]\n\nThe first item of all the sublists is 8, because they a... | [
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0003962163_python.txt |
Q:
Python: removing a TKinter frame
I want to remove a frame from my interface when a specific button is clicked.
This is the invoked callback function
def removeMyself(self):
del self
However, it doesn't remove itself. I'm probably just deleting the object in python without updating the interface ?
thanks
Update
self.itemFrame = tk.Frame(parent)
self.itemFrame.pack(expand=False, side=tk.TOP)
removeB = tk.Button(self.itemFrame, text="Remove", width=10, command=self.removeIsosurface)
def removeIsosurface(self):
self.itemFrame.Destroy()
Error message:
AttributeError: Frame instance has no attribute 'Destroy'
A:
To remove, call either frm.pack_forget() or frm.grid_forget() depending on whether the frame was packed or grided.
Then call frm.destroy() if you aren't going to use it again, or hold onto the reference and repack or regrid when you want to show it again.
A:
del does not delete anything. del something just removes something from the local scope. And although if something was the only reference to an object, it may allow the object it to be garbage collected in the future, don't even think of using del to delete objects!!! And since self is just a normal variables, del self does nothing, except of course stopping the rest of the method from accessing the instance (so at the end of the method, it's actually like pass).
The exact way to remove a widget from the GUI depends on what geometry manager you use. If you used .grid(), you can use .grid_forget(). Note that this still doesn't destroy the widget - quite the contrary, you can go on and .grid() it again! - but that doesn't make any difference.
A:
Let's say you're making a class. You have to do a couple of things special here:
The frame you want to destroy has to be an instance variable
You have to write a callback (which you did)
So, here's how a basic prototype would look.
from Tkinter import Tk, Frame, Button, Label
class GUI:
def __init__(self, root):
self.root = root # root is a passed Tk object
self.button = Button(self.root, text="Push me", command=self.removethis)
self.button.pack()
self.frame = Frame(self.root)
self.frame.pack()
self.label = Label(self.frame, text="I'll be destroyed soon!")
self.label.pack()
def removethis(self):
self.frame.destroy()
root = Tk()
window = GUI(root)
root.mainloop()
Happy hunting!
A:
wont this help : self.destroy()
chk this out : PY cookbook the last para
| Python: removing a TKinter frame | I want to remove a frame from my interface when a specific button is clicked.
This is the invoked callback function
def removeMyself(self):
del self
However, it doesn't remove itself. I'm probably just deleting the object in python without updating the interface ?
thanks
Update
self.itemFrame = tk.Frame(parent)
self.itemFrame.pack(expand=False, side=tk.TOP)
removeB = tk.Button(self.itemFrame, text="Remove", width=10, command=self.removeIsosurface)
def removeIsosurface(self):
self.itemFrame.Destroy()
Error message:
AttributeError: Frame instance has no attribute 'Destroy'
| [
"To remove, call either frm.pack_forget() or frm.grid_forget() depending on whether the frame was packed or grided.\nThen call frm.destroy() if you aren't going to use it again, or hold onto the reference and repack or regrid when you want to show it again.\n",
"del does not delete anything. del something just re... | [
23,
2,
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003962247_python_tkinter.txt |
Q:
Is there a better way to specify named arguments when calling in Python
template.render(current_user=current_user, thread=thread, messages=messages)
Is there a dont-repeat-yourself compliant way to do whatever=whatever? Like a magic symbol to prepend the variable name with or something like this ~whatever, ~something, ~etc?
A:
No, there is not.
For what it's worth, you can create a dictionary with your parameters and pass it with:
template.render(**parameters)
Note: You should always favor readability!
A:
If your template.render() method accepts any keyword arguments, and you don't mind passing it extra arguments that it won't use, then use:
template.render(**locals())
This will pass every local variable in under its own name.
Keep in mind that many people will object to the sloppiness implicit in this solution.
A:
You can pass keyword arguments from a dictionary if you want.
def a(b, c, d):
pass
someArgs = {"b" : 1, "c" : 2, "d" : 3}
a(**someArgs)
If you want to prepend something to the variable names, you can change the dictionary keys:
a(**dict(("prefix_" + k, v) for k, v in someArgs.items()))
And as an aside, you know that you can't specify arguments called "~arg" in your source code?!
A:
I sort of like aaronasterling's idea, but obviously it's not quite short. suppose you have a naming convention for local variables. variables that will be passed to the call have one naming style and everything else follows a different convention. For instance, suppose you just say that the leading character of 'private' locals begin with an underscore. thus:
def localargs (kwargs):
return dict((k, v) for (k, v) in kwargs.iteritems() if k[0] != '_')
def somefunction(public_arg, _private_arg):
public_local = "foo"
_private_local = "bar"
...
template.render(**localargs(locals()))
but that's hideous, don't do that.
A:
Here's a decorator, inspired to some degree by the one in a recipe titled Keyword Argument Injection with Python Decorators, that might help. It certainly cuts down on the repetition, maybe too much.
import sys
def injectlocalargs(inFunction):
def outFunction(*args, **kwargs):
# get decorated function's argument names
func_argnames = inFunction.func_code.co_varnames
# caller's local namespace
namespace = sys._getframe(1).f_locals
# add values of any arguments named in caller's namespace
kwargs.update([(name,namespace[name]) for name in func_argnames if name in namespace])
# call decorated function and return its result
return inFunction(*args, **kwargs)
return outFunction
##### testbed #####
class template_class:
@injectlocalargs
def render(self, extra_stuff, current_user, thread, messages):
print 'render() args'
print ' extra_stuff:%s, current_user:%s, thread:%s, messages:%s' % (extra_stuff, current_user, thread, messages)
def test():
current_user = 'joe'
thread = 42
messages = ['greetings',"how's it going?"]
template = template_class()
template.render('extra_stuff')
test()
Output:
render() args
extra_stuff:extra_stuff, current_user:joe, thread:42, messages:['greetings', "how's it going?"]
| Is there a better way to specify named arguments when calling in Python | template.render(current_user=current_user, thread=thread, messages=messages)
Is there a dont-repeat-yourself compliant way to do whatever=whatever? Like a magic symbol to prepend the variable name with or something like this ~whatever, ~something, ~etc?
| [
"No, there is not.\nFor what it's worth, you can create a dictionary with your parameters and pass it with:\ntemplate.render(**parameters)\n\nNote: You should always favor readability!\n",
"If your template.render() method accepts any keyword arguments, and you don't mind passing it extra arguments that it won't ... | [
3,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003956804_python.txt |
Q:
Determine if a Python list is 95% the same?
This question asks how to determine if every element in a list is the same. How would I go about determining if 95% of the elements in a list are the same in a reasonably efficient way? For example:
>>> ninety_five_same([1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1])
True
>>> ninety_five_same([1,1,1,1,1,1,2,1]) # only 80% the same
False
This would need to be somewhat efficient because the lists may be very large.
A:
>>> from collections import Counter
>>> lst = [1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
>>> _, freq = Counter(lst).most_common(1)[0]
>>> len(lst)*.95 <= freq
True
A:
Actually, there's an easy linear solution for similar problem, only with 50% constraint instead of 95%. Check this question, it's just a few lines of code.
It will work for you as well, only in the end you check that selected element satisfies 95% threshold, not 50%. (Although, as Thilo notes, it's not necessary if currentCount >= n*0.95 already.)
I'll also post Python code from st0le's answer, to show everybody how difficult it is.
currentCount = 0
currentValue = lst[0]
for val in lst:
if val == currentValue:
currentCount += 1
else:
currentCount -= 1
if currentCount == 0:
currentValue = val
currentCount = 1
If you're looking for explanation, I think Nabb has got the best one.
A:
def ninety_five_same(lst):
freq = collections.defaultdict(int)
for x in lst:
freq[x] += 1
freqsort = sorted(freq.itervalues())
return freqsort[-1] >= .95 * sum(freqsort)
Assuming perfect hash table performance and a good sorting algorithm, this runs in O(n + m lg m), where m is the number of distinct items. O(n lg n) worst case.
Edit: here's an O(n + m), single-pass version (assuming m << n):
def ninety_five_same(lst):
freq = collections.defaultdict(int)
for x in lst:
freq[x] += 1
freq = freq.values()
return max(freq) >= .95 * sum(freq)
Memory use is O(m). max and sum can be replaced by a single loop.
A:
This is even less efficient than checking if every element is the same.
The algorithm is roughly the same, go through every element in the list and count those that do not match the expected one (with the extra difficulty of knowing which one is the expected one). However, this time, you cannot just return false when you meet the first mismatch, you have to continue until you have enough mismatches to make up a 5% error rate.
Come to think of it, figuring out which element is the "right" one is probably not so easy, and involves counting every value up to the point where you can be sure that 5% are misplaced.
Consider a list with 10.000 elements of which 99% are 42:
(1,2,3,4,5,6,7,8,9,10, ... , 100, 42,42, 42, 42 .... 42)
So I think you would have to start out building a frequency table for at least the first 5% of the table.
A:
def ninety_five_same(l):
return max([l.count(i) for i in set(l)])*20 >= 19*len(l)
Also eliminating the problem with with accuracy of float division.
A:
Think about your list as a bucket of red and black balls.
If you have one red ball in a bucket of ten balls, and you pick a ball at random and put it back in the bucket, and then repeat that sample-and-replace step a thousand times, how many times out of a thousand do you expect to observe a red ball, on average?
Check out the Binomial distribution and check out confidence intervals. If you have a very long list and want to do things relatively efficiently, sampling is the way to go.
A:
lst = [1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
#lst = [1, 2, 1, 4, 1]
#lst = [1, 2, 1, 4]
length = len(lst)
currentValue = lst[0]
lst.pop(0)
currentCount = 1
for val in lst:
if currentCount == 0:
currentValue = val
if val == currentValue:
currentCount += 1
else:
currentCount -= 1
percent = (currentCount * 50.0 / length + 50)
epsilon = 0.1
if (percent - 50 > epsilon):
print "Percent %g%%" % percent
else:
print "No majority"
Note: epsilon has a "random" value, chose something depending on the length of the array etc.
Nikita Rybak's solution with currentCount >= n*0.95 won't work, because the value of currentCount differs depending on the order of elements, but the above does work.
C:\Temp>a.py
[2, 1, 1, 4, 1]
currentCount = 1
C:\Temp>a.py
[1, 2, 1, 4, 1]
currentCount = 2
A:
sort as general solution probably is heavy, but consider the exceptional well balanced nature of tim sort in Python, which utilize the existing order of the list. I would suggest to sort the list (or copy of it with sorted, but that copy will hurt the performance). Scan from end and front to find the same element or reach scan length > 5 %, otherwise list is 95% similar with the element found.
Taking random elements as candidates and taking count of them by decreasing order of frequency would not probably also be so bad until found count > 95 % or the total of counts goes over 5%.
| Determine if a Python list is 95% the same? | This question asks how to determine if every element in a list is the same. How would I go about determining if 95% of the elements in a list are the same in a reasonably efficient way? For example:
>>> ninety_five_same([1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1])
True
>>> ninety_five_same([1,1,1,1,1,1,2,1]) # only 80% the same
False
This would need to be somewhat efficient because the lists may be very large.
| [
">>> from collections import Counter\n>>> lst = [1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]\n>>> _, freq = Counter(lst).most_common(1)[0]\n>>> len(lst)*.95 <= freq\nTrue\n\n",
"Actually, there's an easy linear solution for similar problem, only with 50% constraint instead of 95%. Check this question, it's just ... | [
16,
15,
6,
3,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"list",
"python"
] | stackoverflow_0003957856_algorithm_list_python.txt |
Q:
Google App Engine Internationalization Help needed (Python)
Has anyone any suggestions on how to use internationalization in app engine / webapp / python. I have seen some posts re - django - translation support but i cant seem to find enough info on how to make it work.
What i need is a solution where
browser can detect language
user can override and set
strings in templates and from code can be localized
easy file editing for language support.
I'm new to app engine so need some easy to follow/understand pointers/code assistance
many than
A:
There are several options to consider.
Standard gettext(). See this code example. The code is outdated: there is a standard way to manage cookies and sessions, so it should be rewritten for the real usage.
Sometimes this method fails, see this issue. Usually it's resolved by just reuploading an application, but this is weird.
Use babel. It's pure python, so it can be integrated easily. The drawback is an external dependency, but it's small and good working. Here is an answer with explanations.
Don't do l10n and i18n in the code. My vision is that GAE should be a backend service, serving html just occasionally.
Recently I did the project requiring web UI in several languages. This time I've generated a set of templates in all languages needed by making a 'master' template using _() and gettext() (python module, not django tags), extracting strings and iterating over the languages. A simple template loader checks the current language and loads an appropriate template. The idea is shamelessly stolen from p. 1.
A:
Here I provide some informations about Internationalization and Localization under the Google App Engine framework.
http://eflorent.blogspot.com/2010/08/internationalization-under-google-app.html
| Google App Engine Internationalization Help needed (Python) | Has anyone any suggestions on how to use internationalization in app engine / webapp / python. I have seen some posts re - django - translation support but i cant seem to find enough info on how to make it work.
What i need is a solution where
browser can detect language
user can override and set
strings in templates and from code can be localized
easy file editing for language support.
I'm new to app engine so need some easy to follow/understand pointers/code assistance
many than
| [
"There are several options to consider. \n\nStandard gettext(). See this code example. The code is outdated: there is a standard way to manage cookies and sessions, so it should be rewritten for the real usage. \n\nSometimes this method fails, see this issue. Usually it's resolved by just reuploading an application... | [
2,
1
] | [] | [] | [
"google_app_engine",
"internationalization",
"python"
] | stackoverflow_0002236153_google_app_engine_internationalization_python.txt |
Q:
missing messages when reading with non-blocking udp
I have problem with missing messages when using nonblocking read in udp between two hosts. The sender is on linux and the reader is on winxp. This example in python shows the problem.
Here are three scripts used to show the problem.
send.py:
import socket, sys
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
host = sys.argv[1]
s.sendto('A'*10, (host,8888))
s.sendto('B'*9000, (host,8888))
s.sendto('C'*9000, (host,8888))
s.sendto('D'*10, (host,8888))
s.sendto('E'*9000, (host,8888))
s.sendto('F'*9000, (host,8888))
s.sendto('G'*10, (host,8888))
read.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('',8888))
while True:
data,address = s.recvfrom(10000)
print "recv:", data[0],"times",len(data)
read_nb.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('',8888))
s.setblocking(0)
data =''
address = ''
while True:
try:
data,address = s.recvfrom(10000)
except socket.error:
pass
else:
print "recv:", data[0],"times",len(data)
Example 1 (works ok):
ubuntu> python send.py
winxp > read.py
give this ok result from read.py:
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: D times 10
recv: E times 9000
recv: F times 9000
recv: G times 10
Example 2 (missing messages):
in this case the short messages will often not be catched by read_nb.py
I give two examples of how it can look like.
ubuntu> python send.py
winxp > read_nb.py
give this result from read_nb.py:
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: D times 10
recv: E times 9000
recv: F times 9000
above is the last 10 byte message missing
below is a 10 byte message in the middle missing
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: E times 9000
recv: F times 9000
recv: G times 10
I have checked with wireshark on windows and every time all messages is captured so they reach the host interface but is not captured by read_nb.py. What is the explanation?
I have also tried with read_nb.py on linux and send.py on windows and then it works.
So I figure that this problem has something to do with winsock2
Or maybe I am using nonblocking udp the wrong way?
A:
If the datagrams are getting to the host (as your wireshark log shows) then the first place I'd look is the size of your socket recv buffer, make it as big as you can, and run as fast as you can.
Of course this is completely expected with UDP. You should assume that datagrams can be thrown away at any point and for any reason. Also you may get datagrams more than once...
If you need reliability then you need to build your own, or use TCP.
A:
Losing messages is normal with UDP - the transport layer does not guarantee order or delivery of datagrams. If you want them in order and/or always delivered, switch to TCP or implement sequencing and/or ack/timeout/retransmission yourself.
To your example - the large messages are larger then normal ethernet MTU of 1500 minus eight bytes of UDP header (unless you are using jumbo frames) and thus will be fragmented by the sender. This puts more load onto both sender and receiver, but more on the receiver since it needs to keep fragments in kernel memory until the full datagram arrives.
I doubt you are overflowing the receive buffer with 36030 bytes, but then I never do networking on Windows, so you better check the value of SO_RECVBUF socket option on the receiver as @Len suggests.
Also check the output of netstat -s to see the dropped packet counts.
| missing messages when reading with non-blocking udp | I have problem with missing messages when using nonblocking read in udp between two hosts. The sender is on linux and the reader is on winxp. This example in python shows the problem.
Here are three scripts used to show the problem.
send.py:
import socket, sys
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
host = sys.argv[1]
s.sendto('A'*10, (host,8888))
s.sendto('B'*9000, (host,8888))
s.sendto('C'*9000, (host,8888))
s.sendto('D'*10, (host,8888))
s.sendto('E'*9000, (host,8888))
s.sendto('F'*9000, (host,8888))
s.sendto('G'*10, (host,8888))
read.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('',8888))
while True:
data,address = s.recvfrom(10000)
print "recv:", data[0],"times",len(data)
read_nb.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('',8888))
s.setblocking(0)
data =''
address = ''
while True:
try:
data,address = s.recvfrom(10000)
except socket.error:
pass
else:
print "recv:", data[0],"times",len(data)
Example 1 (works ok):
ubuntu> python send.py
winxp > read.py
give this ok result from read.py:
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: D times 10
recv: E times 9000
recv: F times 9000
recv: G times 10
Example 2 (missing messages):
in this case the short messages will often not be catched by read_nb.py
I give two examples of how it can look like.
ubuntu> python send.py
winxp > read_nb.py
give this result from read_nb.py:
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: D times 10
recv: E times 9000
recv: F times 9000
above is the last 10 byte message missing
below is a 10 byte message in the middle missing
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: E times 9000
recv: F times 9000
recv: G times 10
I have checked with wireshark on windows and every time all messages is captured so they reach the host interface but is not captured by read_nb.py. What is the explanation?
I have also tried with read_nb.py on linux and send.py on windows and then it works.
So I figure that this problem has something to do with winsock2
Or maybe I am using nonblocking udp the wrong way?
| [
"If the datagrams are getting to the host (as your wireshark log shows) then the first place I'd look is the size of your socket recv buffer, make it as big as you can, and run as fast as you can.\nOf course this is completely expected with UDP. You should assume that datagrams can be thrown away at any point and f... | [
8,
8
] | [] | [] | [
"nonblocking",
"python",
"sockets",
"udp",
"winsock2"
] | stackoverflow_0003960680_nonblocking_python_sockets_udp_winsock2.txt |
Q:
Is it typical to have more than a dozen django applications in your project root for medium-high scale sites? Does it not feel bloated?
I was looking at the INSTALLED_APPS of django-mingus:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.sitemaps',
'django.contrib.flatpages',
'django.contrib.redirects',
'django_extensions',
'tagging',
'djangodblog',
'disqus',
'basic.inlines',
'basic.blog',
'basic.bookmarks',
'basic.media',
'oembed',
'flatblocks',
'dbtemplates',
'navbar',
'sorl.thumbnail',
'template_utils',
'django_proxy',
'django_markup',
'google_analytics',
'robots',
'basic.elsewhere',
'compressor',
'contact_form',
'honeypot',
'sugar',
'quoteme',
'mingus.core',
'debug_toolbar',
'django_twitter',
'django_bitly',
'staticfiles',
'tinymce',
'django_wysiwyg',
'cropper',
'memcache_status',
'request',
)
This does feel somewhat bloated. But I assume this really isn't as bad as it looks, because django only uses what is requested, in that it doesn't load every application per request, but only if it's called? If not, can someone demystify the process?
A:
I think it's quite common to find a lot of apps in your INSTALLED_APPS. To keep some system in your package/directory structure I think it's recommendable to have your apps inside an apps folder within your project root, while keeping other third party apps, that you do not touch somewhere else on your PYTHONPATH. I think it's very recommendable to use something like PIP and virtualenv to keep track of your apps and organize them.
Here you can read another article about a useful directory structure for django projects.
If an app is in your INSTALLED_APPS django will always load its models on startup and populate its APP_CACHE with these classes, but I think this is an overhead you can ignore if you are dealing with conventional apps...
EDIT: Also consider that apps vary a lot in complexity, eg. something like tinymce mainly just provides a widget and some views, but no model, so if it is not used it just adds a few urls to the urlresolver and thats it...
A:
Well, Mingus is specifically a project aimed at demonstrating the use of multiple reusable components, so it's not surprising it uses quite a few of them.
A dozen doesn't sound too bloated, to be honest - I've definitely done sites with more. But in any case, you shouldn't think in terms of requests: Django, or rather mod_wsgi, doesn't start up a stack for each request. Rather, Apache manages processes dynamically, and they load their required code on startup, and the process persists for many requests. This is pretty efficient.
A:
Obviously some of these are 3rd party, and dealing with them by sequestering them in /apps (or even in subdirectories of that, if there are very many) is a good solution for keeping your directory structure sane, as lazerscience points out.
As for your own apps, this is a great question that comes up in #django twice a day or so, and I'd love to see a synthesis of the range of viewpoints.
When I am deciding whether or not to make a separate app, I generally ask myself: Will this new app have models that are a completely different type of knowledge than the apps that came before it? If one app is about people (say, authors) and another is about material possessions (say, books) - it makes sense to separate them. Does 'chapter' need its own app? Clearly not.
I know other developers who focus more on the views that an app has - they ask themselves, "how many top-level terms will I have in my dispatcher?" and go from there. I think this is also a good approach in many cases, but for many projects, some 90% of the models and views will be primarily or exclusively associated with 10% of the top-level URL terms.
As a general matter, having a boatload of apps isn't bad per se. It only becomes bad when it becomes an organizational problem for your group.
| Is it typical to have more than a dozen django applications in your project root for medium-high scale sites? Does it not feel bloated? | I was looking at the INSTALLED_APPS of django-mingus:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.sitemaps',
'django.contrib.flatpages',
'django.contrib.redirects',
'django_extensions',
'tagging',
'djangodblog',
'disqus',
'basic.inlines',
'basic.blog',
'basic.bookmarks',
'basic.media',
'oembed',
'flatblocks',
'dbtemplates',
'navbar',
'sorl.thumbnail',
'template_utils',
'django_proxy',
'django_markup',
'google_analytics',
'robots',
'basic.elsewhere',
'compressor',
'contact_form',
'honeypot',
'sugar',
'quoteme',
'mingus.core',
'debug_toolbar',
'django_twitter',
'django_bitly',
'staticfiles',
'tinymce',
'django_wysiwyg',
'cropper',
'memcache_status',
'request',
)
This does feel somewhat bloated. But I assume this really isn't as bad as it looks, because django only uses what is requested, in that it doesn't load every application per request, but only if it's called? If not, can someone demystify the process?
| [
"I think it's quite common to find a lot of apps in your INSTALLED_APPS. To keep some system in your package/directory structure I think it's recommendable to have your apps inside an apps folder within your project root, while keeping other third party apps, that you do not touch somewhere else on your PYTHONPATH.... | [
5,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003962177_django_python.txt |
Q:
How to display all words that contain these characters?
I have a text file and I want to display all words that contains both z and x characters.
How can I do that ?
A:
If you don't want to have 2 problems:
for word in file('myfile.txt').read().split():
if 'x' in word and 'z' in word:
print word
A:
Assuming you have the entire file as one large string in memory, and that the definition of a word is "a contiguous sequence of letters", then you could do something like this:
import re
for word in re.findall(r"\w+", mystring):
if 'x' in word and 'z' in word:
print word
A:
>>> import re
>>> pattern = re.compile('\b(\w*z\w*x\w*|\w*x\w*z\w*)\b')
>>> document = '''Here is some data that needs
... to be searched for words that contain both z
... and x. Blah xz zx blah jal akle asdke asdxskz
... zlkxlk blah bleh foo bar'''
>>> print pattern.findall(document)
['xz', 'zx', 'asdxskz', 'zlkxlk']
A:
I just want to point out how heavy-handed some of these regular expressions can be, in comparison to the simple string methods-based solution provided by Wooble.
Let's do some timings, shall we?
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import timeit
import re
import sys
WORD_RE_COMPILED = re.compile(r'\w+')
Z_RE_COMPILED = re.compile(r'(\b\w*z\w*\b)')
XZ_RE_COMPILED = re.compile(r'\b(\w*z\w*x\w*|\w*x\w*z\w*)\b')
##########################
# Tim Pietzcker's solution
# https://stackoverflow.com/questions/3962846/how-to-display-all-words-that-contain-these-characters/3962876#3962876
#
def xz_re_word_find(text):
for word in re.findall(r'\w+', text):
if 'x' in word and 'z' in word:
print word
# Tim's solution, compiled
def xz_re_word_compiled_find(text):
pattern = re.compile(r'\w+')
for word in pattern.findall(text):
if 'x' in word and 'z' in word:
print word
# Tim's solution, with the RE pre-compiled so compilation doesn't get
# included in the search time
def xz_re_word_precompiled_find(text):
for word in WORD_RE_COMPILED.findall(text):
if 'x' in word and 'z' in word:
print word
################################
# Steven Rumbalski's solution #1
# (provided in the comment)
# https://stackoverflow.com/questions/3962846/how-to-display-all-words-that-contain-these-characters/3963285#3963285
def xz_re_z_find(text):
for word in re.findall(r'(\b\w*z\w*\b)', text):
if 'x' in word:
print word
# Steven's solution #1 compiled
def xz_re_z_compiled_find(text):
pattern = re.compile(r'(\b\w*z\w*\b)')
for word in pattern.findall(text):
if 'x' in word:
print word
# Steven's solution #1 with the RE pre-compiled
def xz_re_z_precompiled_find(text):
for word in Z_RE_COMPILED.findall(text):
if 'x' in word:
print word
################################
# Steven Rumbalski's solution #2
# https://stackoverflow.com/questions/3962846/how-to-display-all-words-that-contain-these-characters/3962934#3962934
def xz_re_xz_find(text):
for word in re.findall(r'\b(\w*z\w*x\w*|\w*x\w*z\w*)\b', text):
print word
# Steven's solution #2 compiled
def xz_re_xz_compiled_find(text):
pattern = re.compile(r'\b(\w*z\w*x\w*|\w*x\w*z\w*)\b')
for word in pattern.findall(text):
print word
# Steven's solution #2 pre-compiled
def xz_re_xz_precompiled_find(text):
for word in XZ_RE_COMPILED.findall(text):
print word
#################################
# Wooble's simple string solution
def xz_str_find(text):
for word in text.split():
if 'x' in word and 'z' in word:
print word
functions = [
'xz_re_word_find',
'xz_re_word_compiled_find',
'xz_re_word_precompiled_find',
'xz_re_z_find',
'xz_re_z_compiled_find',
'xz_re_z_precompiled_find',
'xz_re_xz_find',
'xz_re_xz_compiled_find',
'xz_re_xz_precompiled_find',
'xz_str_find'
]
import_stuff = functions + [
'text',
'WORD_RE_COMPILED',
'Z_RE_COMPILED',
'XZ_RE_COMPILED'
]
if __name__ == '__main__':
text = open(sys.argv[1]).read()
timings = {}
setup = 'from __main__ import ' + ','.join(import_stuff)
for func in functions:
statement = func + '(text)'
timer = timeit.Timer(statement, setup)
min_time = min(timer.repeat(3, 10))
timings[func] = min_time
for func in functions:
print func + ":", timings[func], "seconds"
Running this script on a plaintext copy of Moby Dick obtained from Project Gutenberg, on Python 2.6, I get the following timings:
xz_re_word_find: 1.21829485893 seconds
xz_re_word_compiled_find: 1.42398715019 seconds
xz_re_word_precompiled_find: 1.40110301971 seconds
xz_re_z_find: 0.680151939392 seconds
xz_re_z_compiled_find: 0.673038005829 seconds
xz_re_z_precompiled_find: 0.673489093781 seconds
xz_re_xz_find: 1.11700701714 seconds
xz_re_xz_compiled_find: 1.12773990631 seconds
xz_re_xz_precompiled_find: 1.13285303116 seconds
xz_str_find: 0.590088844299 seconds
In Python 3.1 (after using 2to3 to fix the print statements), I get the following timings:
xz_re_word_find: 2.36110496521 seconds
xz_re_word_compiled_find: 2.34727501869 seconds
xz_re_word_precompiled_find: 2.32607793808 seconds
xz_re_z_find: 1.32204890251 seconds
xz_re_z_compiled_find: 1.34104800224 seconds
xz_re_z_precompiled_find: 1.34424304962 seconds
xz_re_xz_find: 2.33851099014 seconds
xz_re_xz_compiled_find: 2.29653286934 seconds
xz_re_xz_precompiled_find: 2.32416701317 seconds
xz_str_find: 0.656699895859 seconds
We can see that the regular expression-based functions tend to take twice as long to run as the string methods-based function in Python 2.6, and over 3 times as long in Python 3. The time difference is trivial for one-off parsing (nobody's going to miss those milliseconds), but for cases where the function must be called many times, the string methods-based approach is both simpler and faster.
A:
I do not know the performance of this generator, but for me this is the way:
from __future__ import print_function
import string
bookfile = '11.txt' # Alice in Wonderland
hunted = 'az' # in your case xz but there is none of those in this book
with open(bookfile) as thebook:
# read text of book and split from white space
print('\n'.join(set(word.lower().strip(string.punctuation)
for word in thebook.read().split()
if all(c in word.lower() for c in hunted))))
""" Output:
zealand
crazy
grazed
lizard's
organized
lazy
zigzag
lizard
lazily
gazing
""
"
A:
Sounds like a job for Regular Expressions. Read that and try it out. If you run into problems, update your question and we can help you with the specifics.
A:
>>> import re
>>> print re.findall('(\w*x\w*z\w*|\w*z\w*x\w*)', 'axbzc azb axb abc axzb')
['axbzc', 'axzb']
| How to display all words that contain these characters? | I have a text file and I want to display all words that contains both z and x characters.
How can I do that ?
| [
"If you don't want to have 2 problems:\nfor word in file('myfile.txt').read().split():\n if 'x' in word and 'z' in word:\n print word\n\n",
"Assuming you have the entire file as one large string in memory, and that the definition of a word is \"a contiguous sequence of letters\", then you could do somet... | [
12,
8,
4,
3,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003962846_python.txt |
Q:
Problem with Prototype Ajax.Request in Internet Explorer 8 prompting file download
Have a set of prototype-enabled ajax code that is working in all browsers other than IE. In IE8 the JSON, that otherwise gets returned to the onSuccess handler function specified in Ajax.Request, gets thrown into a file download stream which pops up and prompts for where to download.
askForm = $('askForm');
var askUrl = '.';
var askParameters = askForm.serialize(true);
askForm.disable();
var askAjax = new Ajax.Request(
askUrl, {
method: 'post',
parameters: askParameters,
onSuccess: handleResults,
onFailure: handleError
}
);
function handleError(transport) {
alert('Please refresh this page, an error occurred in processing at the server.');
}
function handleResults(transport) {
...
}
There is more code in the handleResults function but this never gets called. Having debugged, the download prompt occurs when the Ajax.Request function is called.
The filename IE8 prompts to download changes each time, 4 seemingly random hex values (8 characters) with no filename extension. And the contents of the file are the pure JSON response from the server...
{"question": ["Enter your question*"], "name": ["Enter your name (First L.)*"], "sender": ["Enter your e-mail*"]}
Would be much obliged for any tips here. This is occurring on Snow Leopard with IE8 running in VMWare Fusion accessing a site running via apache/django/python on OS X. However, since Chrome and Firefox in the VMWare Windows XP machine function properly, seems to point directly to IE8 as the culprit.
A:
This problem has been solved. Crazy issue here but it turns out that there was a javascript error that was preventing the script from executing and the standard form submit was occurring thru the browser thus returning AJAX code as a file download prompt. The form was designed in such a way that javascript-disabled browsers would still be able to use the form without ajax using a hidden input field with name "js". The javascript would blank the value of this field when submitting via AJAX to let server know the response should be JSON and not a full page refresh. Well, that part of the javascript that blanked the js field value processed normally but then the script errored out and thus the event.stop() javascript never executed. Resulting in the form being processed as a standard Submit button click, POST request through browser.
Note in the code above...
askForm = $('askForm');
which clearly should be...
var askForm = $('askForm');
Thanks to the browsers that allowed this syntax but it sent me on an IE8 wild goose chase as a result. Always learning.
A:
Does the server side file that sends the JSON to the browser send the proper headers? If it doesn't identify itself as JSON the browser might consider it a file to be downloaded.
| Problem with Prototype Ajax.Request in Internet Explorer 8 prompting file download | Have a set of prototype-enabled ajax code that is working in all browsers other than IE. In IE8 the JSON, that otherwise gets returned to the onSuccess handler function specified in Ajax.Request, gets thrown into a file download stream which pops up and prompts for where to download.
askForm = $('askForm');
var askUrl = '.';
var askParameters = askForm.serialize(true);
askForm.disable();
var askAjax = new Ajax.Request(
askUrl, {
method: 'post',
parameters: askParameters,
onSuccess: handleResults,
onFailure: handleError
}
);
function handleError(transport) {
alert('Please refresh this page, an error occurred in processing at the server.');
}
function handleResults(transport) {
...
}
There is more code in the handleResults function but this never gets called. Having debugged, the download prompt occurs when the Ajax.Request function is called.
The filename IE8 prompts to download changes each time, 4 seemingly random hex values (8 characters) with no filename extension. And the contents of the file are the pure JSON response from the server...
{"question": ["Enter your question*"], "name": ["Enter your name (First L.)*"], "sender": ["Enter your e-mail*"]}
Would be much obliged for any tips here. This is occurring on Snow Leopard with IE8 running in VMWare Fusion accessing a site running via apache/django/python on OS X. However, since Chrome and Firefox in the VMWare Windows XP machine function properly, seems to point directly to IE8 as the culprit.
| [
"This problem has been solved. Crazy issue here but it turns out that there was a javascript error that was preventing the script from executing and the standard form submit was occurring thru the browser thus returning AJAX code as a file download prompt. The form was designed in such a way that javascript-disable... | [
3,
0
] | [] | [] | [
"ajax",
"django",
"internet_explorer_8",
"prototypejs",
"python"
] | stackoverflow_0003956287_ajax_django_internet_explorer_8_prototypejs_python.txt |
Q:
How to match patterns "begins with A or ends with B" with Python regular expression?
r'(^|^A)(\S+)(B$|$)'
results to matches everything, which actually equals to ^\S$.
How to write one matches "begins with A or ends with B, may both but not neither?"
PS: I also need refer to group (\S+) in the substring module.
Example:
Match Aanything, anythingB, and refer anything group in the replace.
A:
(^A.*B$)|(^A.*$)|(^.*B$)
A:
^A|B$ or ^A|.*B$ (depending whether the match function is matching from the beginning)
UPDATE
it's difficult to write single regexp for this..
a possibility is:
match = re.match(r'^(?:A(\S+))|(?:(\S+)B)$', string)
if match:
capture = max(match.groups())
# because match.groups() is either (capture, None) or (None, capture)
A:
Is this the desired behavior?
var rx = /^((?:A)?)(.*?)((?:B)?)$/;
"Aanything".match(rx)
> ["Aanything", "A", "anything", ""]
"anythingB".match(rx)
> ["anythingB", "", "anything", "B"]
"AanythingB".match(rx)
> ["AanythingB", "A", "anything", "B"]
"anything".match(rx)
> ["anything", "", "anything", ""]
"AanythingB".replace(rx, '$1nothing$3');
> "AnothingB"
"AanythingB".replace(rx, '$2');
> "anything"
A:
try this:
/(^A|B$)/
A:
Problem solved.
I use this regex in python, I found this in the Python manual:
(?(id/name)yes-pattern|no-pattern)
Will try to match with yes-pattern if
the group with given id or name
exists, and with no-pattern if it
doesn’t. no-pattern is optional and
can be omitted. For example,
(<)?(\w+@\w+(?:.\w+)+)(?(1)>) is a
poor email matching pattern, which
will match with '' as
well as 'user@host.com', but not with
'
New in version 2.4.
So my final answer is:
r'(?P<prefix>A)?(?P<key>\S+)(?(prefix)|B)'
Commands:
>>>re.sub(r'(?P<prefix>A)?(?P<key>\S+)(?(prefix)|B)','\g<key>',"Aanything")
'anything'
>>>re.sub(r'(?P<prefix>A)?(?P<key>\S+)(?(prefix)|B)','\g<key>',"anythingB")
'anything'
While AanythingB give me anythingB back, but I don't care anyway.
>>>re.sub(r'(?P<prefix>A)?(?P<key>\S+)(?(prefix)|B)','\g<key>',"AanythingB")
'anythingB'
A:
If you don't mind the extra weight in the case where both prefix "A" and suffix "B" exist, you can use a shorter regex:
reMatcher= re.compile(r"(?<=\AA).*|.*(?=B\Z)")
(using \A for ^ and \Z for $)
This one keeps the "A" prefix (instead of the "B" prefix of your solution) when both "A" and "B" are at their respective corners:
'A text here' matches ' text here'
'more text hereB' matches 'more text here'
'AYES!B' matched 'AYES!'
'neither' doesn't match
Otherwise, a non-regex solution (some would say a more “Pythonic” one) is:
def strip_prefix_suffix(text, prefix, suffix):
left = len(prefix) if text.startswith(prefix) else 0
right= -len(suffix) if text.endswith(suffix) else None
return text[left:right] if left or right else None
If there is no match, the function returns None to differentiate from a possible '' (e.g. when called as strip_prefix_suffix('AB', 'A', 'B')).
PS I should also say that this regex:
(?<=\AA).*(?=B\Z)|(?<=\AA).*|.*(?=B\Z)
should work, but it doesn't; it works just like the one I suggested, and I can't understand why. Breaking down the regex into parts, we can see something weird:
>>> text= 'AYES!B'
>>> re.compile('(?<=\\AA).*(?=B\\Z)').search(text).group(0)
'YES!'
>>> re.compile('(?<=\\AA).*').search(text).group(0)
'YES!B'
>>> re.compile('.*(?=B\\Z)').search(text).group(0)
'AYES!'
>>> re.compile('(?<=\\AA).*(?=B\\Z)|(?<=\\AA).*').search(text).group(0)
'YES!'
>>> re.compile('(?<=\\AA).*(?=B\\Z)|.*(?=B\\Z)').search(text).group(0)
'AYES!'
>>> re.compile('(?<=\\AA).*|.*(?=B\\Z)').search(text).group(0)
'AYES!'
>>> re.compile('(?<=\\AA).*(?=B\\Z)|(?<=\\AA).*|.*(?=B\\Z)').search(text).group(0)
'AYES!'
For some strange reason, the .*(?=B\\Z) subexpression takes precedence, even though it's the last alternative.
| How to match patterns "begins with A or ends with B" with Python regular expression? | r'(^|^A)(\S+)(B$|$)'
results to matches everything, which actually equals to ^\S$.
How to write one matches "begins with A or ends with B, may both but not neither?"
PS: I also need refer to group (\S+) in the substring module.
Example:
Match Aanything, anythingB, and refer anything group in the replace.
| [
"(^A.*B$)|(^A.*$)|(^.*B$)\n\n",
"^A|B$ or ^A|.*B$ (depending whether the match function is matching from the beginning)\nUPDATE\nit's difficult to write single regexp for this..\na possibility is:\nmatch = re.match(r'^(?:A(\\S+))|(?:(\\S+)B)$', string)\nif match:\n capture = max(match.groups())\n# because matc... | [
4,
2,
2,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003957164_python_regex.txt |
Q:
What makes some programming languages more powerful than others?
I'm going to reveal my ignorance here, but in my defense, I'm an accounting major, and I've never taken a computer science class.
I'm about to start a new project, and I'm considering using Python instead of PHP, even though I am much more adept with PHP, because I have heard that Python is a more powerful language. That got me wondering, what makes one programming language more powerful than another? I figure javascript isn't very powerful because it (generally) runs inside a browser. But, why is Python more powerful than PHP? In each case, I'm giving instructions to the computer, so why are some languages better at interpreting and executing these instructions? How do I know how much "power" I actually need for a specific project?
A:
When Paul Graham talked about Lisp being the most powerful language available, he meant most expressive. You can express any program in any turing complete language. That's the whole point. What makes one language better than another (for a particular task) is its ability to define a given program more concisely or clearly. For most programming tasks, that's what matters.
Occasionally (and I mean very occasionally) performance starts to play a role, and features like the ability to embed assembly language easily in your program matters. But for the most part, it's about the ability to express your ideas clearly and concisely.
A:
I hate statements of the sort "language X is more powerful than Y." The real question is which language makes you more powerful. If language X allows you to write better code (that works) faster than Y does then, yes, X is more "powerful".
If you are looking for an objective explanation of language powerful-ness ... well, good luck with that.
A:
It's not really a matter of power, but a matter of what you're trying to do and how you try to do it. You could say that Python is "more powerful" because it comes with a large set of built-in libraries, or that C++ is "more powerful" because it's much faster, or that Haskell is "more powerful" because it uses lazy evaluation - in short, it's really a matter of opinion. But I haven't seen many desktop apps written in PHP, and I don't see web apps written in C++ (though there are probably exceptions, of course).
Some languages simply offer what is considered an "elegant" way to perform certain tasks. For instance, look at a factorial function in Haskell:
factorial 0 = 1
factorial n = n * factorial (n-1)
Some might consider this elegant mainly because it reflects the mathematical definition clearly. But is this better than another implementation? No. (Especially since this would overflow the stack.)
In conclusion, use what you feel is best for your task - if you're best with PHP, and you don't want to learn Python, than don't. If you're interested in what it's like, then check it out. Don't learn it because it's "more powerful."
A:
I would not say that there are computer languages "more powerful", just languages more suited for your specific problem domain.
That said, PHP is a language that evolved from a hack and tailored for a very specific problem domain; this shows up in several places, like for example inconsistent parameter order across database interfaces. IMHO PHP community has made some very sad decisions for new syntax enhancements over the time.
IMHO Python is much more general, well designed and elegant, but your question is one that usually starts flamewars.
A:
The stock answer is the only features that make certain languages more powerful than others are language features that cannot be easily replaced by adding libraries.
This definition will almost always list LISP on the top, but has the odd side effect of listing assembly near the top unless special care is taken to exclude it.
A:
Its an interesting topic and in my line of word I come across this a lot. But I've discovered 'power' in the literal sense no longer has value when it comes to the language. What I fear those telling you 'python is more' powerful are getting mixed up with the language and the implementation.
I'm a recent convert to python (last 2 weeks) previously I was a PHP coder. The libraries made on top of the language of python - namely django -help make the language more powerful - as its faster to use and build upon.
PHP has the fable 'if you want to do something. there is a function for it' and the documentation is brilliant - therefore powerful in that sense.
And in regards to interpreting the language - again dependant upon who has been coding it - its no matter. By general consensus python may be considered quicker and less CPU intensive, is it creates compiled versions of your code. But PHP can have a good caching system.
In short - Pick you favorite.
| What makes some programming languages more powerful than others? | I'm going to reveal my ignorance here, but in my defense, I'm an accounting major, and I've never taken a computer science class.
I'm about to start a new project, and I'm considering using Python instead of PHP, even though I am much more adept with PHP, because I have heard that Python is a more powerful language. That got me wondering, what makes one programming language more powerful than another? I figure javascript isn't very powerful because it (generally) runs inside a browser. But, why is Python more powerful than PHP? In each case, I'm giving instructions to the computer, so why are some languages better at interpreting and executing these instructions? How do I know how much "power" I actually need for a specific project?
| [
"When Paul Graham talked about Lisp being the most powerful language available, he meant most expressive. You can express any program in any turing complete language. That's the whole point. What makes one language better than another (for a particular task) is its ability to define a given program more concisely o... | [
8,
4,
4,
1,
0,
0
] | [] | [] | [
"programming_languages",
"python"
] | stackoverflow_0003963438_programming_languages_python.txt |
Q:
python regex question
What is the best way to search for matching words inside a string?
Right now I do something like the following:
if re.search('([h][e][l][l][o])',file_name_tmp, re.IGNORECASE):
Which works but its slow as I have probably around 100 different regex statements searching for full words so I'd like to combine several using a | separator or something.
A:
Can you try:
if 'hello' in longtext:
or
if 'HELLO' in longtext.upper():
to match hello/Hello/HELLO.
A:
>>> words = ('hello', 'good\-bye', 'red', 'blue')
>>> pattern = re.compile('(' + '|'.join(words) + ')', re.IGNORECASE)
>>> sentence = 'SAY HeLLo TO reD, good-bye to Blue.'
>>> print pattern.findall(sentence)
['HeLLo', 'reD', 'good-bye', 'Blue']
A:
If you are trying to check 'hello' or a complete word in a string, you could also do
if 'hello' in stringToMatch:
... # Match found , do something
To find various strings, you could also use find all
>>>toMatch = 'e3e3e3eeehellloqweweemeeeeefe'
>>>regex = re.compile("hello|me",re.IGNORECASE)
>>>print regex.findall(toMatch)
>>>[u'me']
>>>toMatch = 'e3e3e3eeehelloqweweemeeeeefe'
>>>print regex.findall(toMatch)
>>>[u'hello', u'me']
>>>toMtach = 'e3e3e3eeeHelLoqweweemeeeeefe'
>>>print regex.findall(toMatch)
>>>[u'HelLo', u'me']
A:
You say you want to search for WORDS. What is your definition of a "word"? If you are looking for "meet", do you really want to match the "meet" in "meeting"? If not, you might like to try something like this:
>>> import re
>>> query = ("meet", "lot")
>>> text = "I'll meet a lot of friends including Charlotte at the town meeting"
>>> regex = r"\b(" + "|".join(query) + r")\b"
>>> re.findall(regex, text, re.IGNORECASE)
['meet', 'lot']
>>>
The \b at each end forces it to match only at word boundaries, using re's definition of "word" -- "isn't" isn't a word, it's two words separated by an apostrophe. If you don't like that, look at the nltk package.
| python regex question | What is the best way to search for matching words inside a string?
Right now I do something like the following:
if re.search('([h][e][l][l][o])',file_name_tmp, re.IGNORECASE):
Which works but its slow as I have probably around 100 different regex statements searching for full words so I'd like to combine several using a | separator or something.
| [
"Can you try:\nif 'hello' in longtext:\n\nor\nif 'HELLO' in longtext.upper():\n\nto match hello/Hello/HELLO.\n",
">>> words = ('hello', 'good\\-bye', 'red', 'blue')\n>>> pattern = re.compile('(' + '|'.join(words) + ')', re.IGNORECASE)\n>>> sentence = 'SAY HeLLo TO reD, good-bye to Blue.'\n>>> print pattern.findal... | [
3,
3,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003962241_python_regex.txt |
Q:
Accept lowercase or uppercase letter in Python
Working on a menu display where the letter "m" takes the user back to the main menu. How can I have it so that it works regardless if the letter "m" is uppercase or lowercase?
elif choice == "m":
A:
One of
elif choice in ("m", "M"):
elif choice in "mM": # false positive if choice == ''
elif choice == 'm' or choice == 'M':
elif choice.lower() == 'm':
In terms of maintainability, the 4th alternative is better when you want to extend to case-insensitive comparison of multiple-letter strings, as you need to provide all 2N possibilities in the 1st and 3rd alternatives. The 2nd alternative only works properly for single-character strings.
With the 4th alternative it is also impossible to miss a case when you want to change the 'm' to other letters.
In terms of efficiency, the 2nd alternative is the most efficient, and then the 1st, and then the 3rd and finally the 4th. This is because the 3nd alternative involves more operations; and while function calling and getting attribution is slow in Python so both makes the 4th alternative relatively slow.
See http://pastie.org/1230957 for the disassembly and timeit result.
Of course unless you're doing this comparison 10 million times there is no perceivable difference between each one.
A:
elif choice.lower() == "m":
A:
This way would be both explicit and very succinct:
elif choice in {'m', 'M'}:
Of course, to express it this way requires Python 2.7 or 3.x which support set literals. I don't know how it compares efficiency-wise to the other answers, but doubt that matters much for a case like this.
| Accept lowercase or uppercase letter in Python | Working on a menu display where the letter "m" takes the user back to the main menu. How can I have it so that it works regardless if the letter "m" is uppercase or lowercase?
elif choice == "m":
| [
"One of\nelif choice in (\"m\", \"M\"):\n\nelif choice in \"mM\": # false positive if choice == ''\n\nelif choice == 'm' or choice == 'M':\n\nelif choice.lower() == 'm':\n\nIn terms of maintainability, the 4th alternative is better when you want to extend to case-insensitive comparison of mult... | [
14,
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0003963161_python.txt |
Q:
Unable to parse the output from HTTPConnection.debuglevel
I am trying to programmability check the output of a tcp stream. I am able to get the results of the tcp stream by turning on debug in HTTPConnection but how do I read the data and evaluate it with say a regular expression. I keep getting "TypeError: expected string or buffer". Is there a way to convert the result to a string?
thanks!
SCRIPT:
from urllib2 import Request, urlopen, URLError, HTTPError
import urllib2
import cookielib
import httplib
import re
httplib.HTTPConnection.debuglevel = 1
p = re.compile('abc=..........')
cj = cookielib.CookieJar()
proxy_address = '192.168.232.134:8083' # change the IP:PORT, this one is for example
proxy_handler = urllib2.ProxyHandler({'http': proxy_address})
opener = urllib2.build_opener(proxy_handler, urllib2.HTTPCookieProcessor(cj), urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)
url = "http://www.google.com/" # change the url
req=urllib2.Request(url)
data=urllib2.urlopen(req)
m=p.match(data)
if m:
print "Match found."
else:
print "Match not found."
RESULTS:
send: 'GET hyperlink/ HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\nConnection: close\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
reply: 'HTTP/1.1 303 See Other\r\n'
header: Location: hyperlink:8083/3240951276
header: Set-Cookie: abc=3240951276; path=/; domain=.google.com; expires=Thu, 31-Dec-2020 23:59:59 GMT
header: Content-Length: 0
send: 'GET hyperlink/3240951276 HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: hyperlink\r\nConnection: close\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
reply: 'HTTP/1.1 303 See Other\r\n'
header: Location: hyperlink
header: Set-Cookie: abc=3240951276; path=/; expires=Thu, 31-Dec-2020 23:59:59 GMT
header: Content-Length: 0
send: 'GET http://www.google.com/ HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\nCookie: abc=3240951276\r\nConnection: close\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Mon, 18 Oct 2010 21:09:32 GMT
header: Expires: -1
header: cache-control: max-age=0, private, private
header: Content-Type: text/html; charset=ISO-8859-1
header: Set-Cookie: PREF=ID=066bc785a2b15ef6:FF=0:TM=1287436172:LM=1287436172:S=mNiXaRhshpf8nLji; expires=Wed, 17-Oct-2012 21:09:32 GMT; path=/; domain=.google.com
header: Set-Cookie: NID=39=ur3gnXL80kEy4shKAh8_-XV8PhmS4G83slPcX9OD3L6uthQZw-wq7RUnB0WKGYR3F_QGoyZAyEPCvjdi69EXXq23dzvpuZSl_KU2o7pqcTB7Vym4co1LOXmi9YQGpbkb; expires=Tue, 19-Apr-2011 21:09:32 GMT; path=/; domain=.google.com; HttpOnly
header: Server: gws
header: X-XSS-Protection: 1; mode=block
header: Connection: close
header: Content-Length: 4676
header: X-Con-Reuse: 1
header: Content-Encoding: gzip
header: via: 1.1 HermesPrefetch (CID2627003316.AID3240951276.TID1)
header: X-Trace-Timing: Start=1287436172845, Sched=0, Dns=2, Con=11, RxS=28, RxD=35
Traceback (most recent call last):
File "C:\Documents and Settings\asdf\workspace\PythonScripts2\src\Test1.py", line 18, in <module>
m=p.match(data)
TypeError: expected string or buffer
A:
The debug information httplib provides you there, which you see in your terminal, is not actually part of the object returned by urllib2.urlopen(). Instead, it's printed directly to your process's sys.stdout. There's no way to change this behaviour in httplib, unfortunately. It's not entirely clear to me what you're trying to achieve by "capturing" this output and running a regular expression over it, but if that's really what you want to do, you would need to replace sys.stdout with something else, such as a suitable StringIO object, and somehow seeing which output is the output you care about.
However, keep in mind that all the information that httplib produces in its debug output is available directly in your program. It's either based on stuff you pass to httplib (through urllib2) or it's part of the server's response, and thus available in the object returned by urllib2.urlopen(). For example, it looks like you're trying to extract the cookie information, which you can get at simply by getting the cookie from the CookieJar you're already providing. There doesn't seem to be any sensible reason to try and capture the output and parsing it.
| Unable to parse the output from HTTPConnection.debuglevel | I am trying to programmability check the output of a tcp stream. I am able to get the results of the tcp stream by turning on debug in HTTPConnection but how do I read the data and evaluate it with say a regular expression. I keep getting "TypeError: expected string or buffer". Is there a way to convert the result to a string?
thanks!
SCRIPT:
from urllib2 import Request, urlopen, URLError, HTTPError
import urllib2
import cookielib
import httplib
import re
httplib.HTTPConnection.debuglevel = 1
p = re.compile('abc=..........')
cj = cookielib.CookieJar()
proxy_address = '192.168.232.134:8083' # change the IP:PORT, this one is for example
proxy_handler = urllib2.ProxyHandler({'http': proxy_address})
opener = urllib2.build_opener(proxy_handler, urllib2.HTTPCookieProcessor(cj), urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)
url = "http://www.google.com/" # change the url
req=urllib2.Request(url)
data=urllib2.urlopen(req)
m=p.match(data)
if m:
print "Match found."
else:
print "Match not found."
RESULTS:
send: 'GET hyperlink/ HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\nConnection: close\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
reply: 'HTTP/1.1 303 See Other\r\n'
header: Location: hyperlink:8083/3240951276
header: Set-Cookie: abc=3240951276; path=/; domain=.google.com; expires=Thu, 31-Dec-2020 23:59:59 GMT
header: Content-Length: 0
send: 'GET hyperlink/3240951276 HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: hyperlink\r\nConnection: close\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
reply: 'HTTP/1.1 303 See Other\r\n'
header: Location: hyperlink
header: Set-Cookie: abc=3240951276; path=/; expires=Thu, 31-Dec-2020 23:59:59 GMT
header: Content-Length: 0
send: 'GET http://www.google.com/ HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\nCookie: abc=3240951276\r\nConnection: close\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Mon, 18 Oct 2010 21:09:32 GMT
header: Expires: -1
header: cache-control: max-age=0, private, private
header: Content-Type: text/html; charset=ISO-8859-1
header: Set-Cookie: PREF=ID=066bc785a2b15ef6:FF=0:TM=1287436172:LM=1287436172:S=mNiXaRhshpf8nLji; expires=Wed, 17-Oct-2012 21:09:32 GMT; path=/; domain=.google.com
header: Set-Cookie: NID=39=ur3gnXL80kEy4shKAh8_-XV8PhmS4G83slPcX9OD3L6uthQZw-wq7RUnB0WKGYR3F_QGoyZAyEPCvjdi69EXXq23dzvpuZSl_KU2o7pqcTB7Vym4co1LOXmi9YQGpbkb; expires=Tue, 19-Apr-2011 21:09:32 GMT; path=/; domain=.google.com; HttpOnly
header: Server: gws
header: X-XSS-Protection: 1; mode=block
header: Connection: close
header: Content-Length: 4676
header: X-Con-Reuse: 1
header: Content-Encoding: gzip
header: via: 1.1 HermesPrefetch (CID2627003316.AID3240951276.TID1)
header: X-Trace-Timing: Start=1287436172845, Sched=0, Dns=2, Con=11, RxS=28, RxD=35
Traceback (most recent call last):
File "C:\Documents and Settings\asdf\workspace\PythonScripts2\src\Test1.py", line 18, in <module>
m=p.match(data)
TypeError: expected string or buffer
| [
"The debug information httplib provides you there, which you see in your terminal, is not actually part of the object returned by urllib2.urlopen(). Instead, it's printed directly to your process's sys.stdout. There's no way to change this behaviour in httplib, unfortunately. It's not entirely clear to me what you'... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003963499_python.txt |
Q:
Tkinter unexpected behaviour
I've been writing a long GUI in Python using Tkinter. One thing that I don't understand is why I can't bind events to widgets in a loop. In the code below, binding works well if I do it manually (commented out code) but not in a for loop. Am I doing something wrong?
import Tkinter
root = Tkinter.Tk()
b1 = Tkinter.Button(root, text="Button 1")
b1.pack()
b1.focus_set()
b2 = Tkinter.Button(root, text="Button 2")
b2.pack()
b3 = Tkinter.Button(root, text="Button 3")
b3.pack()
def up_and_down(*buttons):
for i in range(len(buttons)-1):
buttons[i].bind("<Down>", lambda x: buttons[i+1].focus_set())
for i in range(1, len(buttons)):
buttons[i].bind("<Down>", lambda x: buttons[i-1].focus_set())
'''
buttons[0].bind("<Down>", lambda x: buttons[1].focus_set())
buttons[1].bind("<Down>", lambda x: buttons[2].focus_set())
buttons[1].bind("<Up>", lambda x: buttons[0].focus_set())
buttons[2].bind("<Up>", lambda x: buttons[1].focus_set())
'''
up_and_down(b1, b2, b3)
root.mainloop()
A:
Your closures (lambdas) are not working as you expect them to. They keep references to i which is mutated as the loop iterates, and in the end all lambdas from the same loop refer to the same single last button.
Here's an illustration of the behaviour:
>>> k = []
>>> for i in range(5):
... k.append(lambda: i)
>>> k[0]()
4
>>> [f() for f in k]
[4, 4, 4, 4, 4]
A:
You can fix the problem with:
for i in range(len(buttons)-1):
buttons[i].bind("<Down>", lambda x, i=i: buttons[i+1].focus_set())
for i in range(1, len(buttons)):
buttons[i].bind("<Down>", lambda x, i=i: buttons[i-1].focus_set())
Note the i=i argument to the lambda closure.
| Tkinter unexpected behaviour | I've been writing a long GUI in Python using Tkinter. One thing that I don't understand is why I can't bind events to widgets in a loop. In the code below, binding works well if I do it manually (commented out code) but not in a for loop. Am I doing something wrong?
import Tkinter
root = Tkinter.Tk()
b1 = Tkinter.Button(root, text="Button 1")
b1.pack()
b1.focus_set()
b2 = Tkinter.Button(root, text="Button 2")
b2.pack()
b3 = Tkinter.Button(root, text="Button 3")
b3.pack()
def up_and_down(*buttons):
for i in range(len(buttons)-1):
buttons[i].bind("<Down>", lambda x: buttons[i+1].focus_set())
for i in range(1, len(buttons)):
buttons[i].bind("<Down>", lambda x: buttons[i-1].focus_set())
'''
buttons[0].bind("<Down>", lambda x: buttons[1].focus_set())
buttons[1].bind("<Down>", lambda x: buttons[2].focus_set())
buttons[1].bind("<Up>", lambda x: buttons[0].focus_set())
buttons[2].bind("<Up>", lambda x: buttons[1].focus_set())
'''
up_and_down(b1, b2, b3)
root.mainloop()
| [
"Your closures (lambdas) are not working as you expect them to. They keep references to i which is mutated as the loop iterates, and in the end all lambdas from the same loop refer to the same single last button.\nHere's an illustration of the behaviour:\n>>> k = []\n>>> for i in range(5):\n... k.append(lambda:... | [
3,
3
] | [] | [] | [
"events",
"loops",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0003963613_events_loops_python_tkinter_user_interface.txt |
Q:
QComboBox replacing edit text if case differs from existing item
I'm having a problem with QComboBox not allowing me to change the edit
text to anything existing item of differing case.
Example code is below. What I'd like to do is enter 'one' into a combo
box already containing the item 'One' without the side effect of the
text being changed to 'One'. Currently it's changed back to 'One' as
soon as the combo box loses focus.
Disabling AutoCompletionCaseSensitivity works, but it has the side
effect of not being useful (Doesn't eg. show completions for 'one').
I've also tried overriding the focusOutEvent of QComboBox and
restoring the correct text, but then things like copy-paste don't
work. Changing the completer hasn't helped any either.
The fact combo boxes behave this way is detrimental to my app. If
anyone has any ideas (or I missed something obvious), please let me
know.
I'm using Qt 4.6.2 and PyQt 4.7.2 on Ubuntu 10.04, but have
experienced this on other distros/Qt versions above 4.5.
Thanks and Regards
Example Code:
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt
class Widget(QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
combo = QComboBox()
combo.setEditable(True)
combo.addItems(['One', 'Two', 'Three'])
lineedit = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(combo)
layout.addWidget(lineedit)
self.setLayout(layout)
app = QApplication([])
widget = Widget()
widget.show()
app.exec_()
A:
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt, QEvent
class MyComboBox(QComboBox):
def __init__(self):
QComboBox.__init__(self)
def event(self, event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Return:
self.addItem(self.currentText())
return QComboBox.event(self, event)
class Widget(QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
combo = MyComboBox()
combo.setEditable(True)
combo.addItems(['One', 'Two', 'Three'])
lineedit = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(combo)
layout.addWidget(lineedit)
self.setLayout(layout)
app = QApplication([])
widget = Widget()
widget.show()
app.exec_()
The only issue with this is that it will allow adding duplicates to your combobox.
I tried adding a self.findText(...) to the if statement but even Qt.MatchExactly | Qt.MatchCaseSensitive
would match "bla", "bLa" and "BLA".
I guess you'll find out.
| QComboBox replacing edit text if case differs from existing item | I'm having a problem with QComboBox not allowing me to change the edit
text to anything existing item of differing case.
Example code is below. What I'd like to do is enter 'one' into a combo
box already containing the item 'One' without the side effect of the
text being changed to 'One'. Currently it's changed back to 'One' as
soon as the combo box loses focus.
Disabling AutoCompletionCaseSensitivity works, but it has the side
effect of not being useful (Doesn't eg. show completions for 'one').
I've also tried overriding the focusOutEvent of QComboBox and
restoring the correct text, but then things like copy-paste don't
work. Changing the completer hasn't helped any either.
The fact combo boxes behave this way is detrimental to my app. If
anyone has any ideas (or I missed something obvious), please let me
know.
I'm using Qt 4.6.2 and PyQt 4.7.2 on Ubuntu 10.04, but have
experienced this on other distros/Qt versions above 4.5.
Thanks and Regards
Example Code:
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt
class Widget(QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
combo = QComboBox()
combo.setEditable(True)
combo.addItems(['One', 'Two', 'Three'])
lineedit = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(combo)
layout.addWidget(lineedit)
self.setLayout(layout)
app = QApplication([])
widget = Widget()
widget.show()
app.exec_()
| [
"from PyQt4.QtGui import * \nfrom PyQt4.QtCore import SIGNAL, Qt, QEvent\n\n\nclass MyComboBox(QComboBox):\n def __init__(self):\n QComboBox.__init__(self)\n\n def event(self, event):\n if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Return:\n self.addItem(self.currentTex... | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qcombobox",
"qt4"
] | stackoverflow_0003957445_pyqt_pyqt4_python_qcombobox_qt4.txt |
Q:
How to access Apples iCal-Server via Python
I'm trying to access Apples iCal-Server on a Mac OS X Snow Leopard Server via Python. The server is up and running and working with it via the iCal-Application is just fine.
Now I need to access this server via Python to use it as backend for resource planning. I have already looked at the CalDav-Module (http://packages.python.org/caldav/index.html) but the sample provided there didn't find any calendar, although the Principal-URL is correct.
So how can I read the events within a time range from a user's calendar using python?
A:
[Not a solution but to debug]
From the example given in the caldav module documentation:
from datetime import datetime
import caldav
from caldav.elements import dav, cdav
# Principal url
url = "https://user:pass@hostname/user/Calendar"
client = caldav.DAVClient(url)
principal = caldav.Principal(client, url)
calendars = principal.calendars()
Issues
The url example is not the principal url for ical server
if you look at the code for calendars = principal.calendars(), it ignores the response.
If your principal url is incorrect then without issuing any errors it will return just an empty set of calendars.
Debugging help:
in file objects.py, there is a method for DAVObject called children. You can modify the code to include some debugging information. If you can paste the following and also paste your information in the question.
response = self.client.propfind(self.url.path, body, depth)
print response, self.url.path #provide additional info
print response.raw #provide additional info
for r in response.tree.findall(dav.Response.tag):
| How to access Apples iCal-Server via Python | I'm trying to access Apples iCal-Server on a Mac OS X Snow Leopard Server via Python. The server is up and running and working with it via the iCal-Application is just fine.
Now I need to access this server via Python to use it as backend for resource planning. I have already looked at the CalDav-Module (http://packages.python.org/caldav/index.html) but the sample provided there didn't find any calendar, although the Principal-URL is correct.
So how can I read the events within a time range from a user's calendar using python?
| [
"[Not a solution but to debug]\nFrom the example given in the caldav module documentation:\nfrom datetime import datetime\nimport caldav\nfrom caldav.elements import dav, cdav\n\n# Principal url\nurl = \"https://user:pass@hostname/user/Calendar\"\n\nclient = caldav.DAVClient(url)\nprincipal = caldav.Principal(clien... | [
1
] | [] | [] | [
"caldav",
"icalendar",
"python"
] | stackoverflow_0003758358_caldav_icalendar_python.txt |
Q:
Convert File to HEX String Python
How would I convert a file to a HEX string using Python? I have searched all over Google for this, but can't seem to find anything useful.
A:
import binascii
filename = 'test.dat'
with open(filename, 'rb') as f:
content = f.read()
print(binascii.hexlify(content))
| Convert File to HEX String Python | How would I convert a file to a HEX string using Python? I have searched all over Google for this, but can't seem to find anything useful.
| [
"import binascii\nfilename = 'test.dat'\nwith open(filename, 'rb') as f:\n content = f.read()\nprint(binascii.hexlify(content))\n\n"
] | [
68
] | [] | [] | [
"file",
"hex",
"python",
"string"
] | stackoverflow_0003964245_file_hex_python_string.txt |
Q:
General convention for python libraries that also have an interface module?
Right now I've got a project that has the following layout:
foo/
__init__.py
__main__.py
foo.py
In this case, foo.py is actually the main api file, so developers are meant to do "from foo import foo", but I also wanted to make it so that end users could just run ~$ foo and get an interface.
which, when I do a distutils install, creates /usr/bin/__main__.py because (a) I don't know how to use distutils, [less important] and (b) I am not sure about what is generally considered to be the Right Thing.
As far as I can tell I have three options:
Make distutils smarter, so that setup.py install creates the
symlink /usr/bin/foo -> $PYTHONLIB/foo/__main__.py. This is my
immediate intuition, and I could probably figure out how to do it,
although the things that I'm thinking of doing all feel like hacks
and I haven't found anybody talking about this.
Rename __main__.py to just foo before distribution, and modify the call to
distutils' setup to be setup(scripts=['foo'], ...). This is pretty similar to (1), except for when it happens, I think.
Just don't include an interface with a library package. I feel
like this depends mostly on the size of the library/interface as
to whether it makes sense.
I haven't seen very many packages that include a __main__.py, if any, so I'm not sure if people just don't use them or I haven't been using the right packages. The fact that I couldn't find any blog posts or articles dealing with __main__.py and distutils suggests to me that it's not a particularly popular combination, though.
A:
Calling a module __main__.py is a bad idea, since that name has a special meaning. Instead use a main sentinel in __init__.py and create a script that does exec python -m foo.
A:
Combining Ignacio Vazquez-Abrams' answer with some googling that resulted in me finding this article about using _main_.py, I think I'm probably going to go with a layout along the lines of:
foo/
foo/
__main__.py
...
scripts/
foo
where scripts/foo is just
#!/bin/sh
exec python foo "$@"
This seems like it will install cleanly, and let people use my module without installing, just by doing python path/to/foo.
| General convention for python libraries that also have an interface module? | Right now I've got a project that has the following layout:
foo/
__init__.py
__main__.py
foo.py
In this case, foo.py is actually the main api file, so developers are meant to do "from foo import foo", but I also wanted to make it so that end users could just run ~$ foo and get an interface.
which, when I do a distutils install, creates /usr/bin/__main__.py because (a) I don't know how to use distutils, [less important] and (b) I am not sure about what is generally considered to be the Right Thing.
As far as I can tell I have three options:
Make distutils smarter, so that setup.py install creates the
symlink /usr/bin/foo -> $PYTHONLIB/foo/__main__.py. This is my
immediate intuition, and I could probably figure out how to do it,
although the things that I'm thinking of doing all feel like hacks
and I haven't found anybody talking about this.
Rename __main__.py to just foo before distribution, and modify the call to
distutils' setup to be setup(scripts=['foo'], ...). This is pretty similar to (1), except for when it happens, I think.
Just don't include an interface with a library package. I feel
like this depends mostly on the size of the library/interface as
to whether it makes sense.
I haven't seen very many packages that include a __main__.py, if any, so I'm not sure if people just don't use them or I haven't been using the right packages. The fact that I couldn't find any blog posts or articles dealing with __main__.py and distutils suggests to me that it's not a particularly popular combination, though.
| [
"Calling a module __main__.py is a bad idea, since that name has a special meaning. Instead use a main sentinel in __init__.py and create a script that does exec python -m foo.\n",
"Combining Ignacio Vazquez-Abrams' answer with some googling that resulted in me finding this article about using _main_.py, I think ... | [
3,
1
] | [] | [] | [
"conventions",
"distribution",
"distutils",
"python"
] | stackoverflow_0003962628_conventions_distribution_distutils_python.txt |
Q:
Are Python functions "compile" and "compiler.parse" safe (sandboxed)?
I plan to use those functions in web-environment, so my concern is if those functions can be exploited and used for executing malicious software on the server.
Edit: I don't execute the result. I parse the AST tree and/or catch SyntaxError.
This is the code in question:
try:
#compile the code and check for syntax errors
compile(code_string, filename, "exec")
except SyntaxError, value:
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
if text is None:
return [{"line": 0, "offset": 0,
"message": u"Problem decoding source"}]
else:
line = text.splitlines()[-1]
if offset is not None:
offset = offset - (len(text) - len(line))
else:
offset = 0
return [{"line": lineno, "offset": offset, "message": msg}]
else:
#no syntax errors, check it with pyflakes
tree = compiler.parse(code_string)
w = checker.Checker(tree, filename)
w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
checker.Checker is pyflakes class that parses the AST tree.
A:
I think the more interesting question is what are you doing with the compiled functions? Running them is definitely unsafe.
I've tested the few exploits i could think of seeing as its just a syntax checker (can't redefine classes/functions etc) i don't think there is anyway to get python to execute arbitrary code at compile time
A:
If the resulting code or AST object is never evaluated, I think you are only subject to DDoS attacks.
If you are evaluating user inputed code, it is the same as giving shell access as the webserver user to every user.
A:
They are not, but it's not too hard finding a subset of Python that can be sandboxed to a point. If you want to go down that road you need to parse that subset of Python yourself and intercept all calls, attribute lookups and everything else involved. You also don't want to give users access to any language construct such as unterminating loops and more.
Still interested? Head over to jinja2.sandbox :)
A:
compiler.parse and compile could most definitely be used for an attack if the attacker can control their input and the output is executed. In most cases, you are going to either eval or exec their output to make it run so those are still the usual suspects and compile and compiler.parse (deprecated BTW) are just adding another step between the malicious input and the execution.
EDIT: Just saw that you left a comment indicating that you are actually planning on using these on USER INPUT. Don't do that. Or at least, don't actually execute the result. That's a huge security hole for whoever ends up running that code. And if nobody's going to run it, why compile it? Since you clarified that you only want to check syntax, this should be fine. I would not store the output though as there's no reason to make anything easier for a potential attacker and being able to get arbitrary code onto your system is a first step.
If you do need to store it, I would probably favor a scheme similar to that commonly used for images where they are renamed in a non-predictable manner with the added step of making sure that it is not stored on the import path.
A:
Yes, they can be maliciously exploited.
If you really want safe sandboxing, you could look at PyPy's sandboxing features, but be aware that sandboxing is not easy, and there may be better ways to accomplish whatever you are seeking.
Correction
Since you've updated your question to clarify that you're only parsing the untrusted input to AST, there is no need to sandbox anything: sandboxing is specifically about executing untrusted code (which most people probably assumed your goal was, by asking about sandboxing).
Using compile / compiler only for parsing this way should be safe: Python source parsing does not have any hooks into code execution. (Note that this is not necessarily true of all languages: for example, Perl cannot be (completely) parsed without code execution.)
The only other remaining risk is that someone may be able to craft some pathological Python source code that makes one of the parsers use runaway amounts of memory / processor time, but resource exhaustion attacks affect everything, so you'll just want to manage this as it becomes necessary. (For example, if your deployment is mission-critical and cannot afford a denial of service by an attacker armed with pathological source code, you can execute the parsing in a resource-limited subprocess).
| Are Python functions "compile" and "compiler.parse" safe (sandboxed)? | I plan to use those functions in web-environment, so my concern is if those functions can be exploited and used for executing malicious software on the server.
Edit: I don't execute the result. I parse the AST tree and/or catch SyntaxError.
This is the code in question:
try:
#compile the code and check for syntax errors
compile(code_string, filename, "exec")
except SyntaxError, value:
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
if text is None:
return [{"line": 0, "offset": 0,
"message": u"Problem decoding source"}]
else:
line = text.splitlines()[-1]
if offset is not None:
offset = offset - (len(text) - len(line))
else:
offset = 0
return [{"line": lineno, "offset": offset, "message": msg}]
else:
#no syntax errors, check it with pyflakes
tree = compiler.parse(code_string)
w = checker.Checker(tree, filename)
w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
checker.Checker is pyflakes class that parses the AST tree.
| [
"I think the more interesting question is what are you doing with the compiled functions? Running them is definitely unsafe.\nI've tested the few exploits i could think of seeing as its just a syntax checker (can't redefine classes/functions etc) i don't think there is anyway to get python to execute arbitrary code... | [
4,
2,
2,
1,
1
] | [] | [] | [
"python",
"security"
] | stackoverflow_0003964077_python_security.txt |
Q:
Mark File For Removal from Python?
In one of my scripts, I need to delete a file that could be in use at the time. I know that I can't remove the file that is in use until it isn't anymore, but I also know that I can mark the file for removal by the Operating System (Windows XP). How would I do this in Python?
A:
...and another version which doesn't depend on pywin32 binaries.
import ctypes
MOVEFILE_DELAY_UNTIL_REBOOT = 4
ctypes.windll.kernel32.MoveFileExA("/path/to/lockedfile.ext", None,
MOVEFILE_DELAY_UNTIL_REBOOT)
A:
import win32file
import win32api
win32file.MoveFileEx("/path/to/lockedfile.ext", None ,
win32file.MOVEFILE_DELAY_UNTIL_REBOOT)
A:
Use the MoveFileEx function:
If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT and lpNewFileName is NULL, MoveFileEx registers the lpExistingFileName file to be deleted when the system restarts. If lpExistingFileName refers to a directory, the system removes the directory at restart only if the directory is empty.
| Mark File For Removal from Python? | In one of my scripts, I need to delete a file that could be in use at the time. I know that I can't remove the file that is in use until it isn't anymore, but I also know that I can mark the file for removal by the Operating System (Windows XP). How would I do this in Python?
| [
"...and another version which doesn't depend on pywin32 binaries.\nimport ctypes\nMOVEFILE_DELAY_UNTIL_REBOOT = 4\n\nctypes.windll.kernel32.MoveFileExA(\"/path/to/lockedfile.ext\", None,\n MOVEFILE_DELAY_UNTIL_REBOOT)\n\n",
"import win32file\nimport win32api\nwin32file.MoveFi... | [
7,
5,
1
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003964400_file_python.txt |
Q:
Why this request doesn't work?
I want to make a simple stupid twitter app using Twitter API.
If I request this page from my browser it does work:
http://search.twitter.com/search.atom?q=hello&rpp=10&page=1
but if I request this page from python using urllib or urllib2 most of the times it doesn't work:
response = urllib2.urlopen("http://search.twitter.com/search.atom?q=hello&rpp=10&page=1")
and I get this error:
Traceback (most recent call last):
File "twitter.py", line 24, in <module>
response = urllib2.urlopen("http://search.twitter.com/search.atom?q=hello&rpp=10&page=1")
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 110] Connection timed out>
Why ??
A:
The code seems alright.
The following worked.
>>> import urllib
>>> import urllib2
>>> user_agent = 'curl/7.21.1 (x86_64-apple-darwin10.4.0) libcurl/7.21.1'
>>> url='http://search.twitter.com/search.atom?q=hello&rpp=10&page=1'
>>> headers = { 'User-Agent' : user_agent }
>>> req = urllib2.Request(url, None, headers)
>>> response = urllib2.urlopen(req)
>>> the_page = response.read()
>>> print the_page
The other is twitter actually could not respond. This happens once too often with Twitter.
A:
did you change the default socket timeout somewhere in your script? your example code works reliably for me.
it could be your internet connection, or you might try
import socket
socket.setdefaulttimeout(30)
assuming urllib/2 don't override the socket timeout.
| Why this request doesn't work? | I want to make a simple stupid twitter app using Twitter API.
If I request this page from my browser it does work:
http://search.twitter.com/search.atom?q=hello&rpp=10&page=1
but if I request this page from python using urllib or urllib2 most of the times it doesn't work:
response = urllib2.urlopen("http://search.twitter.com/search.atom?q=hello&rpp=10&page=1")
and I get this error:
Traceback (most recent call last):
File "twitter.py", line 24, in <module>
response = urllib2.urlopen("http://search.twitter.com/search.atom?q=hello&rpp=10&page=1")
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 110] Connection timed out>
Why ??
| [
"The code seems alright.\nThe following worked. \n>>> import urllib\n>>> import urllib2\n>>> user_agent = 'curl/7.21.1 (x86_64-apple-darwin10.4.0) libcurl/7.21.1'\n>>> url='http://search.twitter.com/search.atom?q=hello&rpp=10&page=1'\n>>> headers = { 'User-Agent' : user_agent }\n>>> req = urllib2.Request(url, None,... | [
2,
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003964519_python_urllib2.txt |
Q:
is there a limit to the (CSV) filesize that a Python script can read/write?
I will be writing a little Python script tomorrow, to retrieve all the data from an old MS Access database into a CSV file first, and then after some data cleansing, munging etc, I will import the data into a mySQL database on Linux.
I intend to use pyodbc to make a connection to the MS Access db. I will be running the initial script in a Windows environment.
The db has IIRC well over half a million rows of data. My questions are:
Is the number of records a cause for concern? (i.e. Will I hit some limits)?
Is there a better file format for the transitory data (instead of CSV)?
I chose CSv because it is quite simple and straightforward (and I am a Python newbie) - but
I would like to hear from someone who may have done something similar before.
A:
Memory usage for csvfile.reader and csvfile.writer isn't proportional to the number of records, as long as you iterate correctly and don't try to load the whole file into memory. That's one reason the iterator protocol exists. Similarly, csvfile.writer writes directly to disk; it's not limited by available memory. You can process any number of records with these without memory limitations.
For simple data structures, CSV is fine. It's much easier to get fast, incremental access to CSV than more complicated formats like XML (tip: pulldom is painfully slow).
A:
Yet another approach if you have Access available ...
Create a table in MySQL to hold the data.
In your Access db, create an ODBC link to the MySQL table.
Then execute a query such as:
INSERT INTO MySqlTable (field1, field2, field3)
SELECT field1, field2, field3
FROM AccessTable;
Note: This suggestion presumes you can do your data cleaning operations in Access before sending the data on to MySQL.
A:
I wouldn't bother using an intermediate format. Pulling from Access via ADO and inserting right into MySQL really shouldn't be an issue.
A:
The only limit should be operating system file size.
That said, make sure when you send the data to the new database, you're writing it a few records at a time; I've seen people do things where they try to load the entire file first, then write it.
| is there a limit to the (CSV) filesize that a Python script can read/write? | I will be writing a little Python script tomorrow, to retrieve all the data from an old MS Access database into a CSV file first, and then after some data cleansing, munging etc, I will import the data into a mySQL database on Linux.
I intend to use pyodbc to make a connection to the MS Access db. I will be running the initial script in a Windows environment.
The db has IIRC well over half a million rows of data. My questions are:
Is the number of records a cause for concern? (i.e. Will I hit some limits)?
Is there a better file format for the transitory data (instead of CSV)?
I chose CSv because it is quite simple and straightforward (and I am a Python newbie) - but
I would like to hear from someone who may have done something similar before.
| [
"Memory usage for csvfile.reader and csvfile.writer isn't proportional to the number of records, as long as you iterate correctly and don't try to load the whole file into memory. That's one reason the iterator protocol exists. Similarly, csvfile.writer writes directly to disk; it's not limited by available memor... | [
5,
3,
1,
0
] | [] | [] | [
"csv",
"ms_access",
"odbc",
"python"
] | stackoverflow_0003964378_csv_ms_access_odbc_python.txt |
Q:
How can I ensure that my Python regular expression outputs a dictionary?
I'm using Beej's Python Flickr API to ask Flickr for JSON. The unparsed string Flickr returns looks like this:
jsonFlickrApi({'photos': 'example'})
I want to access the returned data as a dictionary, so I have:
photos = "jsonFlickrApi({'photos': 'test'})"
# to match {'photos': 'example'}
response_parser = re.compile(r'jsonFlickrApi\((.*?)\)$')
parsed_photos = response_parser.findall(photos)
However, parsed_photos is a list, not a dictionary (according to type(parsed_photos). It outputs like:
["{'photos': 'test'}"]
How can I ensure that my parsed data ends up as a dictionary type?
A:
If you're using Python 2.6, you can just use the JSON module to parse JSON stuff.
import json
json.loads(dictString)
If you're using an earlier version of Python, you can download the simplejson module and use that.
Example:
>>> json.loads('{"hello" : 4}')
{u'hello': 4}
A:
You need to use a JSON parser to convert the string representation to actual Python data structure. Take a look at the documentation of the json module in the standard library for some examples.
In other words you'd have to add the following line at the end of your code
photos = json.loads(parsed_photos[0])
PS. In theory you could also use eval to achieve the same effect, as JSON is (almost) compatible with Python literals, but doing that would open a huge security hole. Just to let you know.
| How can I ensure that my Python regular expression outputs a dictionary? | I'm using Beej's Python Flickr API to ask Flickr for JSON. The unparsed string Flickr returns looks like this:
jsonFlickrApi({'photos': 'example'})
I want to access the returned data as a dictionary, so I have:
photos = "jsonFlickrApi({'photos': 'test'})"
# to match {'photos': 'example'}
response_parser = re.compile(r'jsonFlickrApi\((.*?)\)$')
parsed_photos = response_parser.findall(photos)
However, parsed_photos is a list, not a dictionary (according to type(parsed_photos). It outputs like:
["{'photos': 'test'}"]
How can I ensure that my parsed data ends up as a dictionary type?
| [
"If you're using Python 2.6, you can just use the JSON module to parse JSON stuff.\nimport json\njson.loads(dictString)\n\nIf you're using an earlier version of Python, you can download the simplejson module and use that.\nExample:\n>>> json.loads('{\"hello\" : 4}')\n{u'hello': 4}\n\n",
"You need to use a JSON pa... | [
2,
1
] | [] | [] | [
"json",
"python",
"regex"
] | stackoverflow_0003964621_json_python_regex.txt |
Q:
AttributeError Exception raised when trying to bulk delete items in Django
I'm trying to bulk delete all of the comments on a dev instance of my Django website and Django is raising an AttributeException.
I've got the following code on a python prompt:
>>> from django.contrib.comments.models import Comment
>>> Comment.objects.all().delete()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/jeff/.virtualenvs/osl_main-website/lib/python2.6/site-packages/django/db/models/query.py", line 441, in delete
obj._collect_sub_objects(seen_objs)
File "/home/jeff/.virtualenvs/osl_main-website/lib/python2.6/site-packages/django/db/models/base.py", line 569, in _collect_sub_objects
sub_obj._collect_sub_objects(seen_objs, self, related.field.null)
File "/home/jeff/.virtualenvs/osl_main-website/lib/python2.6/site-packages/django/db/models/base.py", line 585, in _collect_sub_objects
delete_qs = rel_descriptor.delete_manager(self).all()
AttributeError: 'ReverseSingleRelatedObjectDescriptor' object has no attribute 'delete_manager'
I'm not sure as to why the delete statement is not working. Can anyone help me with why this isn't working and what I can do to fix it?
Additional details about my models:
I have another model called OslComment that inherits from Comment. I also have a Vote model that points to entries in OslComment.
BaseCommentAbstractModel
class BaseCommentAbstractModel(models.Model):
"""
An abstract base class that any custom comment models probably should
subclass.
"""
# Content-object field
content_type = models.ForeignKey(ContentType,
verbose_name=_('content type'),
related_name="content_type_set_for_%(class)s")
object_pk = models.TextField(_('object ID'))
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
# Metadata about the comment
site = models.ForeignKey(Site)
Comment
class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH)
# Metadata about the comment
submit_date = models.DateTimeField(_('date/time submitted'), default=None)
ip_address = models.IPAddressField(_('IP address'), blank=True, null=True)
is_public = models.BooleanField(_('is public'), default=True,
help_text=_('Uncheck this box to make the comment effectively ' \
'disappear from the site.'))
is_removed = models.BooleanField(_('is removed'), default=False,
help_text=_('Check this box if the comment is inappropriate. ' \
'A "This comment has been removed" message will ' \
'be displayed instead.'))
OslComment
class OslComment(Comment):
parent_comment = models.ForeignKey(Comment, blank=True, null=True, related_name='parent_comment')
inline_to_object = models.BooleanField(default=False)
edit_timestamp = models.DateTimeField()
transformed_comment = models.TextField(editable=False)
is_deleted_by_user = models.BooleanField(default=False)
Vote
class Vote(models.Model):
"""
A vote on an object by a User.
"""
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('content_type', 'object_id')
vote = models.SmallIntegerField(choices=SCORES)
Misc information:
Python Version: 2.6.5
Operating System: Linux Mint 9 (Linux 2.6.32-21-generic)
Django: 1.2
Database driver: postgresql_psycopg2 (2.2.1)
A:
Edited: Originally I thought you couldn't do delete() on a QuerySet and was going to recommend you iterate over the items, but apparently you can do bulk deletes like that. Trying to iterate over the QuerySet might give you a better clue as to what's wrong, though.
| AttributeError Exception raised when trying to bulk delete items in Django | I'm trying to bulk delete all of the comments on a dev instance of my Django website and Django is raising an AttributeException.
I've got the following code on a python prompt:
>>> from django.contrib.comments.models import Comment
>>> Comment.objects.all().delete()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/jeff/.virtualenvs/osl_main-website/lib/python2.6/site-packages/django/db/models/query.py", line 441, in delete
obj._collect_sub_objects(seen_objs)
File "/home/jeff/.virtualenvs/osl_main-website/lib/python2.6/site-packages/django/db/models/base.py", line 569, in _collect_sub_objects
sub_obj._collect_sub_objects(seen_objs, self, related.field.null)
File "/home/jeff/.virtualenvs/osl_main-website/lib/python2.6/site-packages/django/db/models/base.py", line 585, in _collect_sub_objects
delete_qs = rel_descriptor.delete_manager(self).all()
AttributeError: 'ReverseSingleRelatedObjectDescriptor' object has no attribute 'delete_manager'
I'm not sure as to why the delete statement is not working. Can anyone help me with why this isn't working and what I can do to fix it?
Additional details about my models:
I have another model called OslComment that inherits from Comment. I also have a Vote model that points to entries in OslComment.
BaseCommentAbstractModel
class BaseCommentAbstractModel(models.Model):
"""
An abstract base class that any custom comment models probably should
subclass.
"""
# Content-object field
content_type = models.ForeignKey(ContentType,
verbose_name=_('content type'),
related_name="content_type_set_for_%(class)s")
object_pk = models.TextField(_('object ID'))
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
# Metadata about the comment
site = models.ForeignKey(Site)
Comment
class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH)
# Metadata about the comment
submit_date = models.DateTimeField(_('date/time submitted'), default=None)
ip_address = models.IPAddressField(_('IP address'), blank=True, null=True)
is_public = models.BooleanField(_('is public'), default=True,
help_text=_('Uncheck this box to make the comment effectively ' \
'disappear from the site.'))
is_removed = models.BooleanField(_('is removed'), default=False,
help_text=_('Check this box if the comment is inappropriate. ' \
'A "This comment has been removed" message will ' \
'be displayed instead.'))
OslComment
class OslComment(Comment):
parent_comment = models.ForeignKey(Comment, blank=True, null=True, related_name='parent_comment')
inline_to_object = models.BooleanField(default=False)
edit_timestamp = models.DateTimeField()
transformed_comment = models.TextField(editable=False)
is_deleted_by_user = models.BooleanField(default=False)
Vote
class Vote(models.Model):
"""
A vote on an object by a User.
"""
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('content_type', 'object_id')
vote = models.SmallIntegerField(choices=SCORES)
Misc information:
Python Version: 2.6.5
Operating System: Linux Mint 9 (Linux 2.6.32-21-generic)
Django: 1.2
Database driver: postgresql_psycopg2 (2.2.1)
| [
"Edited: Originally I thought you couldn't do delete() on a QuerySet and was going to recommend you iterate over the items, but apparently you can do bulk deletes like that. Trying to iterate over the QuerySet might give you a better clue as to what's wrong, though.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003964687_django_python.txt |
Q:
How do I calculate the magnitude of the velocity of my mouse cursor, in Python?
http://dl.dropbox.com/u/779859/speedCalc_puradata.JPG
I achieved it in pure data, have a look at the schematic of what I'm thinking:
Recieving Midi Control input from ctlin 20 and 21
Pipe delays whatever signal it recieves
Pythagoras
Viola, the speed of the input. The units don't matter, as long as it is absolute.
I was thinking about doing the same but in python, for the mouse cursor.
Basically, when I move my mouse, I want to see at what speed the mouse is moving.
The rate of input packets is constant at 200hz.
I might have come up with a way, though I haven't tested it yet. How about collecting, say, 51 values in a list, keeping the [0] current, and [50] the oldest. Then simply doing the math on those two values?
A:
What you are describing will give you the magnitude of the velocity times the length of the time interval of measurement. The actual velocity will be a vector. You can get its first coordinate as (posX - delayed_posX)/t and its second coordinate as (posY-delayed_posY)/t where t is the time interval between the measurements. Note that this satisfies Pfinal = Pstart + t V where P is our position vector. Whenever you want to know how to measure an approximation of the velocity, that's always your starting point. The smaller the time interval, the more accurate a picture of the velocity you will have.
In response to your question about time.sleep, no it will not slow down your other code: it will stop it completely unless it runs in another thread.
What exactly are you trying to do? It's hard to say if there's a better way unless we know where you need the data to be, when you need it to be there and how current you need it to be.
A:
Turns out all I needed was the difference in X, and then I used that as the magnitude.
x_list.insert(0, x)
if len(x_list) > 5:
x_list.pop()
# Get the velocity
velocity = abs(x_list[0]-x_list[-1])
Where 'x' is the current value of the cursor, updating at 200hz.
| How do I calculate the magnitude of the velocity of my mouse cursor, in Python? | http://dl.dropbox.com/u/779859/speedCalc_puradata.JPG
I achieved it in pure data, have a look at the schematic of what I'm thinking:
Recieving Midi Control input from ctlin 20 and 21
Pipe delays whatever signal it recieves
Pythagoras
Viola, the speed of the input. The units don't matter, as long as it is absolute.
I was thinking about doing the same but in python, for the mouse cursor.
Basically, when I move my mouse, I want to see at what speed the mouse is moving.
The rate of input packets is constant at 200hz.
I might have come up with a way, though I haven't tested it yet. How about collecting, say, 51 values in a list, keeping the [0] current, and [50] the oldest. Then simply doing the math on those two values?
| [
"What you are describing will give you the magnitude of the velocity times the length of the time interval of measurement. The actual velocity will be a vector. You can get its first coordinate as (posX - delayed_posX)/t and its second coordinate as (posY-delayed_posY)/t where t is the time interval between the mea... | [
2,
0
] | [] | [] | [
"mouse_cursor",
"python"
] | stackoverflow_0003956539_mouse_cursor_python.txt |
Q:
How do you pass multiple arguments to __setstate__?
I am doing deepcopy on a class I designed, which has multiple lists as attributes to it. With a single list, this is solvable by overriding getstate to return that list, and setstate to set that list, but setstate seems unable to take multiple parameters.
How is this accomplished?
A:
You can have __getstate__ return (and __setstate__ accept) a list of lists, or a dict (if you implement __getstate__ and __setstate__, __getstate__ doesn't have to return a dict)
import pickle
class Example:
def __init__(self):
self.list1 = [1]
self.list2 = [2]
def __getstate__(self):
return {'list1': self.list1, 'list2': self.list2}
def __setstate__(self, state):
self.list1 = state['list1']
self.list2 = state['list2']
ex = Example()
s = pickle.dumps(ex)
ex2 = pickle.loads(s)
print ex.list1, ex.list2
This is just a demo. You really don't even need to override pickle's default behavior for a simple case like this.
| How do you pass multiple arguments to __setstate__? | I am doing deepcopy on a class I designed, which has multiple lists as attributes to it. With a single list, this is solvable by overriding getstate to return that list, and setstate to set that list, but setstate seems unable to take multiple parameters.
How is this accomplished?
| [
"You can have __getstate__ return (and __setstate__ accept) a list of lists, or a dict (if you implement __getstate__ and __setstate__, __getstate__ doesn't have to return a dict)\nimport pickle\n\nclass Example:\n def __init__(self):\n self.list1 = [1]\n self.list2 = [2]\n\n def __getstate__(se... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003964895_python.txt |
Q:
Image analysis in R
I would like to know how I would go about performing image analysis in R. My goal is to convert images into matrices (pixel-wise information), extract/quantify color, estimate the presence of shapes and compare images based on such metrics/patterns.
I am aware of relevant packages available in Python (suggestions relevant to Python are also welcome), but I am looking to accomplish these tasks in R.
Thank you for your feedback.
-Harsh
A:
I'd start with EBImage - check out the vignette which demonstrates many of the tasks you mention.
A:
Also check out the RASTER package on the R-Forge website:
http://r-forge.r-project.org/projects/raster/
It is not released to CRAN yet but it is an excellent package to import, analyse, extract, subset images and convert them to matrices). Spatial analysis is also possible.
You can download the package in R via:
install.packages("raster",repos="http://r-forge.r-project.org")
require(raster)
An example for R:
#from file
r <- raster(system.file("external/test.grd", package="raster"))
logo <- raster(system.file("external/rlogo.grd", package="raster"), values=TRUE)
plot(logo)
Check out
?raster # and go to index of the package for an overview of all the options for image analysis.
A:
I believe the CRAN Task View on Medical Imaging should have something for you.
A:
You may also be interested in Rpy which allows you to call R functions and use R packages from Python. This may allow you to have your cake (Python's imaging libraries) and eat it too (R's statistical analysis capabilities).
A:
Try the rgdal package. You will be able to read (import) and write (export) GeoTiff image files from/to R.
Marcio Pupin Mello
| Image analysis in R | I would like to know how I would go about performing image analysis in R. My goal is to convert images into matrices (pixel-wise information), extract/quantify color, estimate the presence of shapes and compare images based on such metrics/patterns.
I am aware of relevant packages available in Python (suggestions relevant to Python are also welcome), but I am looking to accomplish these tasks in R.
Thank you for your feedback.
-Harsh
| [
"I'd start with EBImage - check out the vignette which demonstrates many of the tasks you mention.\n",
"Also check out the RASTER package on the R-Forge website:\nhttp://r-forge.r-project.org/projects/raster/\nIt is not released to CRAN yet but it is an excellent package to import, analyse, extract, subset images... | [
9,
8,
1,
1,
1
] | [] | [] | [
"analysis",
"image",
"python",
"r"
] | stackoverflow_0003955077_analysis_image_python_r.txt |
Q:
Python - Function has a list as argument. How to return another list without changing the first?
I'm pretty new in Python (and programming as a whole). I'm pretty sure the answer to this is obvious, but I really don't know what to do.
def do_play(value, slot, board):
temp=board
(i,j) = slot
temp[i][j] = value
return temp
board is a list of lists. value is an integer. slot is and integer tuple.
What I am trying to do here is to
feed the function board
copy board to a new list called temp
insert a new value in a specific location in temp
return temp, leaving board unchanged
When I run this is the shell, both the the original list (board) and the new list (temp) change.
= \
Any help would be appreciated.
A:
temp=board does not make a new board. It makes the temp variable reference the very same list as board. So changing temp[i][j] changes board[i][j] too.
To make a copy, use
import copy
temp=copy.deepcopy(board)
Note that temp=board[:] makes temp refer to a new list (different than board, but the contents (that is, the lists within the list) are still the same:
In [158]: board=[[1,2],[3,4]]
In [159]: temp=board[:]
Modifying temp modifies board too:
In [161]: temp[1][0]=100
In [162]: temp
Out[162]: [[1, 2], [100, 4]]
In [163]: board
Out[163]: [[1, 2], [100, 4]]
id shows the object's memory address. This shows temp and board are different lists:
In [172]: id(temp)
Out[172]: 176446508
In [173]: id(board)
Out[173]: 178068780 # The ids don't match
But this shows the second list inside temp is the very same list inside board:
In [174]: id(temp[1])
Out[174]: 178827948
In [175]: id(board[1])
Out[175]: 178827948 # The ids are the same
But if you use copy.deepcopy, then the lists within the list also get copied, which is what you need if modifying temp is to leave board unchanged:
In [164]: import copy
In [165]: board=[[1,2],[3,4]]
In [166]: temp=copy.deepcopy(board)
In [167]: temp[1][0]=100
In [168]: temp
Out[168]: [[1, 2], [100, 4]]
In [169]: board
Out[169]: [[1, 2], [3, 4]]
A:
Are you trying to copy board?
temp = board[:]
Or maybe this to copy the structure.
temp = [ r[:] for r in board ]
A:
Use copy.deepcopy() to copy the object.
A:
Here temp is a reference to board, a shallow copy. I usually like to import the copy module (import copy) and use copy.deepcopy which makes temp separate from board. You'd call it something like this:
import copy
temp = copy.deepcopy(board)
Otherwise, you can just make a slice of board (which also makes a deep copy). I believe this should work, but I haven't tried it on a list of lists. You'd call it as so:
temp = board[:]
A:
temp=board
This doesn't copy list, it just makes one more reference to the same object. Use temp = board[:] instead.
| Python - Function has a list as argument. How to return another list without changing the first? | I'm pretty new in Python (and programming as a whole). I'm pretty sure the answer to this is obvious, but I really don't know what to do.
def do_play(value, slot, board):
temp=board
(i,j) = slot
temp[i][j] = value
return temp
board is a list of lists. value is an integer. slot is and integer tuple.
What I am trying to do here is to
feed the function board
copy board to a new list called temp
insert a new value in a specific location in temp
return temp, leaving board unchanged
When I run this is the shell, both the the original list (board) and the new list (temp) change.
= \
Any help would be appreciated.
| [
"temp=board does not make a new board. It makes the temp variable reference the very same list as board. So changing temp[i][j] changes board[i][j] too.\nTo make a copy, use\nimport copy\ntemp=copy.deepcopy(board)\n\n\nNote that temp=board[:] makes temp refer to a new list (different than board, but the contents (t... | [
10,
5,
2,
2,
0
] | [] | [] | [
"function_declaration",
"python",
"return_value"
] | stackoverflow_0003964967_function_declaration_python_return_value.txt |
Q:
How to convert base 10 to base X?
I'm wanting to write a program that asks the user to enter a number in base 10, and to enter the base that they want to convert to. What is the highest base that I can convert to without having my program become incredibly complicated? I'm thinking Base 9, because after 10 (which is already given), the bases start to use letters. Am I correct?
Note: By complicated, I mean complicated for a Python beginner. I'm very far off from being skilled with the program.
Note 2: I'm attempting to do this without modules.
A:
If you put the digit values in a string then the base you can use gets very high very easily.
radixdigits = '0123456789ABCDEFGHI...'
And then you can do divmod() with the length of the string in order to get the current digit, and index the string with that number.
A:
What is the highest base that I can convert to without having my program become incredibly complicated?
In ASCII, base 127. However, that will be hard to read because of the upper-case/lower-case things looking similar, and the non-printable ASCII characters requiring a lot of complex escapes.
You're better limiting things to about base 36 because you can use digits and letters without any confusing ambiguity.
In Unicde, base 65536 or some such, depending on how many Unicode characters you want to deal with.
I'm thinking Base 9, because after 10 (which is already given), the bases start to use letters. Am I correct?
You're sort-of correct.
Standard ASCII has 9 digit symbols. You're not forced to use letters, but it's pretty common to use letters.
You could use lots of Unicode symbols that are neither letters nor digits.
I'm attempting to do this without modules.
That's not terribly relevant.
Now read other Stackoverflow questions on Base Conversion.
Here's a starter: Base 62 conversion
Here's the search: https://stackoverflow.com/search?q=%5Bpython%5D+base+conversion
| How to convert base 10 to base X? | I'm wanting to write a program that asks the user to enter a number in base 10, and to enter the base that they want to convert to. What is the highest base that I can convert to without having my program become incredibly complicated? I'm thinking Base 9, because after 10 (which is already given), the bases start to use letters. Am I correct?
Note: By complicated, I mean complicated for a Python beginner. I'm very far off from being skilled with the program.
Note 2: I'm attempting to do this without modules.
| [
"If you put the digit values in a string then the base you can use gets very high very easily.\nradixdigits = '0123456789ABCDEFGHI...'\n\nAnd then you can do divmod() with the length of the string in order to get the current digit, and index the string with that number.\n",
"\nWhat is the highest base that I can ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003964926_python.txt |
Q:
Python: How to export Sympy image to png?
Python: How to export Sympy image to png?
Who has any idea with this?
A:
Use the saveimage method:
import sympy
x, y, z = sympy.symbols('xyz')
p = sympy.Plot(x * y ** 3 - y * x ** 3)
p.saveimage('/tmp/plot.png', format='png')
| Python: How to export Sympy image to png? | Python: How to export Sympy image to png?
Who has any idea with this?
| [
"Use the saveimage method:\nimport sympy\nx, y, z = sympy.symbols('xyz')\np = sympy.Plot(x * y ** 3 - y * x ** 3)\np.saveimage('/tmp/plot.png', format='png')\n\n"
] | [
2
] | [] | [] | [
"python",
"python_imaging_library",
"sympy"
] | stackoverflow_0003964968_python_python_imaging_library_sympy.txt |
Q:
Creating a custom file like object python suggestions?
Hi i am looking to implement my own custom file like object for an internal binary format we use at work(i don't really want to go into too much detail because i don't know if i can). I am trying to go for a more pythonic way of doing things since currently we have two functions read/write(each ~4k lines of code) which do everything. However we need more control/finesse hence the fact of me rewriting this stuff.
I looked at the python documentation and they say what methods i need to implement, but don't mention stuff like iter() / etc.
Basically what i would love to do is stuff like this:
output_file_objs = [
open("blah.txt", "w")
open("blah142.txt", "wb")
my_lib.open("internal_file.something", "wb", ignore_something=True)
]
data_to_write = <data>
for f in output_file_objs:
f.write(data_to_write)
So i can mix it in with the others, and basically have a level of transparency. I will add custom methods to it, but thats not a problem.
Is there any sort of good reference regarding writing your own custom file like objects? Like any form of restrictions or special methods (iter). I should implement?
Or is there a good example of one from within the python standard library that i can look at?
A:
What makes up a "file-like" actually depends on what you intend to use it for; not all methods are required to be implemented (or to have a sane implementation).
Having said that, the file and iterator docs are what you want.
A:
Why not stuff your data in StringIO? Otherwise, you can look at the documentation and implement all of the file like methods. Truth be told, there are no real interfaces in Python, and some features (like tell()) may not make sense for your files, so you can leave them unimplemented.
| Creating a custom file like object python suggestions? | Hi i am looking to implement my own custom file like object for an internal binary format we use at work(i don't really want to go into too much detail because i don't know if i can). I am trying to go for a more pythonic way of doing things since currently we have two functions read/write(each ~4k lines of code) which do everything. However we need more control/finesse hence the fact of me rewriting this stuff.
I looked at the python documentation and they say what methods i need to implement, but don't mention stuff like iter() / etc.
Basically what i would love to do is stuff like this:
output_file_objs = [
open("blah.txt", "w")
open("blah142.txt", "wb")
my_lib.open("internal_file.something", "wb", ignore_something=True)
]
data_to_write = <data>
for f in output_file_objs:
f.write(data_to_write)
So i can mix it in with the others, and basically have a level of transparency. I will add custom methods to it, but thats not a problem.
Is there any sort of good reference regarding writing your own custom file like objects? Like any form of restrictions or special methods (iter). I should implement?
Or is there a good example of one from within the python standard library that i can look at?
| [
"What makes up a \"file-like\" actually depends on what you intend to use it for; not all methods are required to be implemented (or to have a sane implementation).\nHaving said that, the file and iterator docs are what you want.\n",
"Why not stuff your data in StringIO? Otherwise, you can look at the documentati... | [
5,
1
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003965036_file_python.txt |
Q:
Python: determine length of sequence of equal items in list
I have a list as follows:
l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
I want to determine the length of a sequence of equal items, i.e for the given list I want the output to be:
[(0, 6), (1, 6), (0, 4), (2, 3)]
(or a similar format).
I thought about using a defaultdict but it counts the occurrences of each item and accumulates it for the entire list, since I cannot have more than one key '0'.
Right now, my solution looks like this:
out = []
cnt = 0
last_x = l[0]
for x in l:
if x == last_x:
cnt += 1
else:
out.append((last_x, cnt))
cnt = 1
last_x = x
out.append((last_x, cnt))
print out
I am wondering if there is a more pythonic way of doing this.
A:
You almost surely want to use itertools.groupby:
l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
answer = []
for key, iter in itertools.groupby(l):
answer.append((key, len(list(iter))))
# answer is [(0, 6), (1, 6), (0, 4), (2, 3)]
If you want to make it more memory efficient, yet add more complexity, you can add a length function:
def length(l):
if hasattr(l, '__len__'):
return len(l)
else:
i = 0
for _ in l:
i += 1
return i
l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
answer = []
for key, iter in itertools.groupby(l):
answer.append((key, length(iter)))
# answer is [(0, 6), (1, 6), (0, 4), (2, 3)]
Note though that I have not benchmarked the length() function, and it's quite possible it will slow you down.
A:
Mike's answer is good, but the itertools._grouper returned by groupby will never have a __len__ method so there is no point testing for it
I use sum(1 for _ in i) to get the length of the itertools._grouper
>>> import itertools as it
>>> L = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
>>> [(k, sum(1 for _ in i)) for k, i in it.groupby(L)]
[(0, 6), (1, 6), (0, 4), (2, 3)]
| Python: determine length of sequence of equal items in list | I have a list as follows:
l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
I want to determine the length of a sequence of equal items, i.e for the given list I want the output to be:
[(0, 6), (1, 6), (0, 4), (2, 3)]
(or a similar format).
I thought about using a defaultdict but it counts the occurrences of each item and accumulates it for the entire list, since I cannot have more than one key '0'.
Right now, my solution looks like this:
out = []
cnt = 0
last_x = l[0]
for x in l:
if x == last_x:
cnt += 1
else:
out.append((last_x, cnt))
cnt = 1
last_x = x
out.append((last_x, cnt))
print out
I am wondering if there is a more pythonic way of doing this.
| [
"You almost surely want to use itertools.groupby:\nl = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]\nanswer = []\nfor key, iter in itertools.groupby(l):\n answer.append((key, len(list(iter))))\n\n# answer is [(0, 6), (1, 6), (0, 4), (2, 3)]\n\nIf you want to make it more memory efficient, yet add more complexity, you... | [
16,
3
] | [] | [] | [
"count",
"list",
"python"
] | stackoverflow_0003964963_count_list_python.txt |
Q:
Nested SELECT queries sometimes stall
I've been using sqlite3 in a python application, and when testing it, my queries sometimes cause the program to freeze up. A rough (from memory) example:
SELECT id,name FROM main_table WHERE name IN
(SELECT name FROM another_table WHERE another_table.attribute IN
('foo', 'bar', 'baz'))
Often, the first time I attempt something like this, the program simply freezes. Now, if I try the subquery first and then the whole nested mess, it works almost instantly.
I'm guessing that it's caching the results of the first, simpler query for later which makes things faster the next time around, but even so I'd like to know how to avoid this stalling in the first place.
A:
You didn't mention anything about indexes... name in both tables should be indexed at a minimum.
Here's an equivalent using JOINs:
SELECT DISTINCT
x.id,
x.name
FROM main_table x
JOIN ANOTHER_TABLE y ON y.name = x.name
AND y.attribute IN ('foo', 'bar', 'baz')
But mind that if there are more than one record in ANOTHER_TABLE that associates with a MAIN_TABLE record - the JOIN will produce duplicates. Hence the need for the DISTINCT (or GROUP BY if that's your preference).
The EXISTS is likely to be a better choice than IN:
SELECT x.id,
x.name
FROM main_table x
WHERE EXISTS(SELECT NULL
FROM ANOTHER_TABLE y
WHERE y.name = x.name
AND y.attribute IN ('foo', 'bar', 'baz'))
A:
select ... where ... in ... queries often perform poorly. They are usually treated by optimizers as a potentially very large series of (name=val1 or name=val2 or ... or name=valn)
Try using inner joins for the subquery:
SELECT
id
,name
FROM
main_table
INNER JOIN another_table on
main_table.name=another_table.name
and another_table.attribute in (
'foo','bar','baz'
)
| Nested SELECT queries sometimes stall | I've been using sqlite3 in a python application, and when testing it, my queries sometimes cause the program to freeze up. A rough (from memory) example:
SELECT id,name FROM main_table WHERE name IN
(SELECT name FROM another_table WHERE another_table.attribute IN
('foo', 'bar', 'baz'))
Often, the first time I attempt something like this, the program simply freezes. Now, if I try the subquery first and then the whole nested mess, it works almost instantly.
I'm guessing that it's caching the results of the first, simpler query for later which makes things faster the next time around, but even so I'd like to know how to avoid this stalling in the first place.
| [
"You didn't mention anything about indexes... name in both tables should be indexed at a minimum.\nHere's an equivalent using JOINs:\nSELECT DISTINCT\n x.id,\n x.name \n FROM main_table x\n JOIN ANOTHER_TABLE y ON y.name = x.name\n AND y.attribute IN ('foo', 'bar', 'baz')\n\nBut m... | [
1,
0
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0003965178_python_sql_sqlite.txt |
Q:
Redis key management
So im working with redis in a python app. any advice on key management? i try and keep all redis calls in one location but something seems off with hardcoding keys everywhere. tips?
A:
I use a set of wrapper classes that handle key generation, something like:
public User Get(string username) {
return redis.Get("user:"+username);
}
I have an instance of each of these classes globally available, so just need to call
Server.Users.Get(username);
That's in .NET of course, but something similar should work in any language. An additional advantage of this approach over using a generic mapping tool is that it provides a good place to put things like connection sharing and indexing.
A:
Well, key names are comparable to classes and attributes in your application, so some degree of 'repetition' will happen.
However, if you find you're repeating a lot of code to actually build your keys, then you might want to look at a mapper. In Python there's Redisco.
Or if you need something simpler, in Ruby there's Nest (porting it to Python should be trivial). It allows you to DRY up your references to keys:
users = Nest.new("User")
user = users[1]
# => "User:1"
user[:name]
# => "User:1:name"
redis.set(user[:name], "Foo")
# or even:
user[:name].set("Foo")
user[:name].get
# => "Foo"
| Redis key management | So im working with redis in a python app. any advice on key management? i try and keep all redis calls in one location but something seems off with hardcoding keys everywhere. tips?
| [
"I use a set of wrapper classes that handle key generation, something like:\npublic User Get(string username) {\n return redis.Get(\"user:\"+username);\n}\n\nI have an instance of each of these classes globally available, so just need to call\nServer.Users.Get(username);\n\nThat's in .NET of course, but somethin... | [
2,
1
] | [] | [] | [
"python",
"redis"
] | stackoverflow_0003450027_python_redis.txt |
Q:
rotating the tires in a car (open gl)
Based on the answer i got for the same question earlier, i changed my code, as per the homework i had to use glmultmatrix. But this is not working. Here is the code, what i am doing is that i translate the center of tire to the center of car, rotate the tire, and then translate back. But it is not placing back the tire where it should be:
if (name == 'Front Driver tire' ) & (self.fFlag == "true"):
self.getCenterTireRim()
bodyFace = self.mini.group(name)
glPushMatrix()
x = self.carCenterX - self.xtFront
y = self.carCenterY - self.ytFront
z = self.carCenterZ - self.ztFront
A = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1)
glMultMatrixd(cast(A, POINTER(c_double)))
#print self.carCenterX, self.carCenterY, self.carCenterZ
#print self.xtFront, self.ytFront, self.ztFront
B = self.matrix(1,0,0,0,0, math.cos(math.radians(self.angle1 + 45)), math.sin(math.radians(self.angle1 + 45)), 0, 0, -math.sin(math.radians(self.angle1 + 45)), math.cos(math.radians(self.angle1 + 45)), 0, 0,0,0, 1)
glMultMatrixd(cast(B, POINTER(c_double)))
for face in bodyFace:
if len(face) == 3:
glBegin(GL_TRIANGLES)
elif len(face) == 4:
glBegin(GL_QUADS)
else:
glBegin(GL_POLYGON)
for i in face:
glNormal3f(*self.mini.normal(i))
glVertex3f(*self.mini.vertex(i))
glEnd()
C = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x - self.carCenterX , y - self.carCenterY, z - self.carCenterZ, 1)
glMultMatrixd(cast(C, POINTER(c_double)))
glPopMatrix()
elif (name == 'Front Driver tire rim') & (self.fFlag == "true"):
bodyFace = self.mini.group(name)
glPushMatrix()
self.getCenterTireRim()
bodyFace = self.mini.group(name)
A1 = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, self.carCenterX - self.xrFront, self.carCenterY - self.yrFront, self.carCenterZ - self.zrFront, 1)
glMultMatrixd(cast(A1, POINTER(c_double)))
#print self.carCenterX, self.carCenterY, self.carCenterZ
#print self.xrFront, self.yrFront, self.zrFront
B1 = self.matrix(1,0,0,0,0, math.cos(math.radians(self.angle1 + 45)), math.sin(math.radians(self.angle1 + 45)), 0, 0, -math.sin(math.radians(self.angle1 + 45)), math.cos(math.radians(self.angle1 + 45)), 0, 0, 0, 0, 1)
glMultMatrixd(cast(B1, POINTER(c_double)))
for face in bodyFace:
if len(face) == 3:
glBegin(GL_TRIANGLES)
elif len(face) == 4:
glBegin(GL_QUADS)
else:
glBegin(GL_POLYGON)
for i in face:
glNormal3f(*self.mini.normal(i))
glVertex3f(*self.mini.vertex(i))
glEnd()
C1 = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, self.xrFront - self.carCenterX , self.yrFront - self.carCenterY, self.zrFront - self.carCenterZ, 1)
glMultMatrixd(cast(C1, POINTER(c_double)))
glPopMatrix()
A:
I'm pretty sure that it is because this line
C = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x - self.carCenterX , y - self.carCenterY, z - self.carCenterZ, 1)
should be
C = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -x , -y, -z, 1)
I'm not sure why you were using x - self.carCenterX and so forth. You translated one way (x,y,z) so just go back the opposite direction, -(x,y,z) = (-x,-y,-z)
I hope that helps.
| rotating the tires in a car (open gl) | Based on the answer i got for the same question earlier, i changed my code, as per the homework i had to use glmultmatrix. But this is not working. Here is the code, what i am doing is that i translate the center of tire to the center of car, rotate the tire, and then translate back. But it is not placing back the tire where it should be:
if (name == 'Front Driver tire' ) & (self.fFlag == "true"):
self.getCenterTireRim()
bodyFace = self.mini.group(name)
glPushMatrix()
x = self.carCenterX - self.xtFront
y = self.carCenterY - self.ytFront
z = self.carCenterZ - self.ztFront
A = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1)
glMultMatrixd(cast(A, POINTER(c_double)))
#print self.carCenterX, self.carCenterY, self.carCenterZ
#print self.xtFront, self.ytFront, self.ztFront
B = self.matrix(1,0,0,0,0, math.cos(math.radians(self.angle1 + 45)), math.sin(math.radians(self.angle1 + 45)), 0, 0, -math.sin(math.radians(self.angle1 + 45)), math.cos(math.radians(self.angle1 + 45)), 0, 0,0,0, 1)
glMultMatrixd(cast(B, POINTER(c_double)))
for face in bodyFace:
if len(face) == 3:
glBegin(GL_TRIANGLES)
elif len(face) == 4:
glBegin(GL_QUADS)
else:
glBegin(GL_POLYGON)
for i in face:
glNormal3f(*self.mini.normal(i))
glVertex3f(*self.mini.vertex(i))
glEnd()
C = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x - self.carCenterX , y - self.carCenterY, z - self.carCenterZ, 1)
glMultMatrixd(cast(C, POINTER(c_double)))
glPopMatrix()
elif (name == 'Front Driver tire rim') & (self.fFlag == "true"):
bodyFace = self.mini.group(name)
glPushMatrix()
self.getCenterTireRim()
bodyFace = self.mini.group(name)
A1 = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, self.carCenterX - self.xrFront, self.carCenterY - self.yrFront, self.carCenterZ - self.zrFront, 1)
glMultMatrixd(cast(A1, POINTER(c_double)))
#print self.carCenterX, self.carCenterY, self.carCenterZ
#print self.xrFront, self.yrFront, self.zrFront
B1 = self.matrix(1,0,0,0,0, math.cos(math.radians(self.angle1 + 45)), math.sin(math.radians(self.angle1 + 45)), 0, 0, -math.sin(math.radians(self.angle1 + 45)), math.cos(math.radians(self.angle1 + 45)), 0, 0, 0, 0, 1)
glMultMatrixd(cast(B1, POINTER(c_double)))
for face in bodyFace:
if len(face) == 3:
glBegin(GL_TRIANGLES)
elif len(face) == 4:
glBegin(GL_QUADS)
else:
glBegin(GL_POLYGON)
for i in face:
glNormal3f(*self.mini.normal(i))
glVertex3f(*self.mini.vertex(i))
glEnd()
C1 = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, self.xrFront - self.carCenterX , self.yrFront - self.carCenterY, self.zrFront - self.carCenterZ, 1)
glMultMatrixd(cast(C1, POINTER(c_double)))
glPopMatrix()
| [
"I'm pretty sure that it is because this line\nC = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x - self.carCenterX , y - self.carCenterY, z - self.carCenterZ, 1)\n\nshould be\nC = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -x , -y, -z, 1)\n\nI'm not sure why you were using x - self.carCenterX and s... | [
1
] | [] | [] | [
"opengl",
"python"
] | stackoverflow_0003965166_opengl_python.txt |
Q:
Method signature for Jacobian of a least squares function in scipy
Can anyone provide an example of providing a Jacobian to a least squares function in scipy?
I can't figure out the method signature they want - they say it should be a function, yet it's very hard to figure out what input parameters in what order this function should accept.
A:
Here's the exponential decay fitting that I got to work with this:
import numpy as np
from scipy.optimize import leastsq
def f(var,xs):
return var[0]*np.exp(-var[1]*xs)+var[2]
def func(var, xs, ys):
return f(var,xs) - ys
def dfunc(var,xs,ys):
v = np.exp(-var[1]*xs)
return [v,-var[0]*xs*v,np.ones(len(xs))]
xs = np.linspace(0,4,50)
ys = f([2.5,1.3,0.5],xs)
yn = ys + 0.2*np.random.normal(size=len(xs))
fit = leastsq(func,[10,10,10],args=(xs,yn),Dfun=dfunc,col_deriv=1)
If I wanted to use col_deriv=0, I think that I would have to basically take the transpose of what I return with dfunc. You're quite right though: the documentation on this isn't so great.
| Method signature for Jacobian of a least squares function in scipy | Can anyone provide an example of providing a Jacobian to a least squares function in scipy?
I can't figure out the method signature they want - they say it should be a function, yet it's very hard to figure out what input parameters in what order this function should accept.
| [
"Here's the exponential decay fitting that I got to work with this:\nimport numpy as np\nfrom scipy.optimize import leastsq\n\ndef f(var,xs):\n return var[0]*np.exp(-var[1]*xs)+var[2]\n\ndef func(var, xs, ys):\n return f(var,xs) - ys\n\ndef dfunc(var,xs,ys):\n v = np.exp(-var[1]*xs)\n return [v,-var[0]*... | [
14
] | [] | [] | [
"least_squares",
"numpy",
"python",
"scipy"
] | stackoverflow_0003965404_least_squares_numpy_python_scipy.txt |
Q:
How come there's no C# equivalent of python's doctest feature?
Seems like it would be a good way to introduce some people to unit testing.
A:
Well for one thing, the documentation for doctest talks about "interactive Python sessions". There's no equivalent of that in C#... so how would the output be represented? How would you perform all the necessary setup?
I dare say such a thing would be possible, but personally I think that at least for C#, it's clearer to have unit tests as unit tests, where you have all the benefits of the fact that you're writing code rather than comments. The code can be checked for syntactic correctness at compile-time, you have IntelliSense, syntax highlighting, debugger support etc.
If you're writing code, why not represent that as code? Admittedly it's reasonably common to include sample code in XML documentation, but that's rarely in the form of tests - and without an equivalent of an "interactive session" it would require an artificial construct to represent the output in a testable form.
I'm not saying this is a bad feature in Python - just that it's one which I don't believe maps over to C# particularly well. Languages have their own styles, and not every feature in language X will make sense in language Y.
| How come there's no C# equivalent of python's doctest feature? | Seems like it would be a good way to introduce some people to unit testing.
| [
"Well for one thing, the documentation for doctest talks about \"interactive Python sessions\". There's no equivalent of that in C#... so how would the output be represented? How would you perform all the necessary setup?\nI dare say such a thing would be possible, but personally I think that at least for C#, it's ... | [
6
] | [] | [] | [
".net",
"c#",
"doctest",
"python",
"unit_testing"
] | stackoverflow_0003965547_.net_c#_doctest_python_unit_testing.txt |
Q:
How to pass variable arguments from bash script to python script
I've been trying to solve this issue for sometime now with no luck. The crust of the situation is that I'm using a bash script to send parameters to a a python script:
Example:
foo.sh calls bar.py....the call looks like: bar.py $var1 $var2 ... $varn
The python script then prints all the arguments using the sys.argv array. The python script works correctly from the command line, but when called from with the bash script (i.e foo.sh), I get no output from bar.py.
Also, I started foo.sh with the "#!/bin/bash -x" option and watched the output as well.
TO summarize:
Two scripts, foo.sh and bar.py
foo.sh calls bar.py, passing variables of foo.sh as arguments to bar.py
bar.py prints the arguments it sees using sys.argv
bar.py works when run from its own terminal, doesn't work when called from foo.sh
Any help would be awesome!!!!
Thanks!
Edit: Hi all, thanks for the replies, the complete code is pretty long...but... the contents of the two scripts could be summed
foo.sh ____
#!/bin/bash
declare -a list1;
declare -a list2;
list1=("foo" "bar" "please");
list2=("foo" "bar" "please" "help");
declare -a joined;
joined=( $(bar.py "${list1[@]}" "${list2[@]}" ) );
bar.py ____
#!/bin/python
import sys
for arg in sys.argv:
print arg
As I assume all the indents in the python are correct (not sure how StackOverflow does this yet :) ). These two represent the core of the issue i'm having. As stated, bar.py prints arguments correctly, when it it not called from foo.sh.
PS: I did mean to say "crust"
A:
Edit, since code has been posted
Your code is doing the correct thing - except that the output from your bar.py script is being captured into the array joined. Since it looks like you're not printing out the contents of joined, you never see any output.
Here's a demonstration:
File pybash.sh
#!/bin/bash
declare -a list1
declare -a list2
list1=("Hello" "there" "honey")
list2=("More" "strings" "here")
declare -a joined
joined=($(./pytest.py ${list1[@]} ${list2[@]}))
echo ${joined[@]}
File pytest.py
#!/usr/bin/python
import sys
for i in sys.argv:
print "hi"
This will print out a bunch of 'hi' strings if you run the bash script.
A:
EDIT:
I figured it out, I had some weired combo of characters, the line was not properly escaped. I changed it from
var=( $( some commands) )
to
var=( some commands ) // using backticks (still learning the SO editor...)
Bash escaping is some ride lol! To those who answered, thanks for all your help
| How to pass variable arguments from bash script to python script | I've been trying to solve this issue for sometime now with no luck. The crust of the situation is that I'm using a bash script to send parameters to a a python script:
Example:
foo.sh calls bar.py....the call looks like: bar.py $var1 $var2 ... $varn
The python script then prints all the arguments using the sys.argv array. The python script works correctly from the command line, but when called from with the bash script (i.e foo.sh), I get no output from bar.py.
Also, I started foo.sh with the "#!/bin/bash -x" option and watched the output as well.
TO summarize:
Two scripts, foo.sh and bar.py
foo.sh calls bar.py, passing variables of foo.sh as arguments to bar.py
bar.py prints the arguments it sees using sys.argv
bar.py works when run from its own terminal, doesn't work when called from foo.sh
Any help would be awesome!!!!
Thanks!
Edit: Hi all, thanks for the replies, the complete code is pretty long...but... the contents of the two scripts could be summed
foo.sh ____
#!/bin/bash
declare -a list1;
declare -a list2;
list1=("foo" "bar" "please");
list2=("foo" "bar" "please" "help");
declare -a joined;
joined=( $(bar.py "${list1[@]}" "${list2[@]}" ) );
bar.py ____
#!/bin/python
import sys
for arg in sys.argv:
print arg
As I assume all the indents in the python are correct (not sure how StackOverflow does this yet :) ). These two represent the core of the issue i'm having. As stated, bar.py prints arguments correctly, when it it not called from foo.sh.
PS: I did mean to say "crust"
| [
"Edit, since code has been posted\nYour code is doing the correct thing - except that the output from your bar.py script is being captured into the array joined. Since it looks like you're not printing out the contents of joined, you never see any output.\nHere's a demonstration:\nFile pybash.sh\n#!/bin/bash\n\ndec... | [
6,
1
] | [
"I have pretty much the exact setup that you are describing, and this is how my bash script looks:\nVAR1=...\nVAR2=...\nVAR3=...\n\npython my_script.py $VAR1 $VAR2 $VAR3 \n\n"
] | [
-2
] | [
"arguments",
"bash",
"parameters",
"python"
] | stackoverflow_0003955571_arguments_bash_parameters_python.txt |
Q:
about python list step issue when the element is long type
In [2]: list=range(627)
In [3]: list[::150]
Out[3]: [0, 150, 300, 450, 600]
the above code is right,but if i use the bellow code,caution:the l means long type,
the return result is not like above,what's the hell?
In [4]: list=[1323l,123123l,4444l,12312312l]
In [5]: list=[1323l,123123l,4444l,12312312l]
In [6]: list[::2]
Out[6]: [1323L, 4444L]
A:
The step denotes the multiples of indices that are included in the slice, not of the actual values contained in the array. In your second example:
list[0] = 1323L
list[1] = 123123L
list[2] = 4444L
list[3] = 12312312L
Since you're using the default argument for the start of the slice, it will start at the first element (list[0]), and it will get every 2nd element after that, so it will also get list[2]. It does not look at what those elements are, only at their indices.
| about python list step issue when the element is long type | In [2]: list=range(627)
In [3]: list[::150]
Out[3]: [0, 150, 300, 450, 600]
the above code is right,but if i use the bellow code,caution:the l means long type,
the return result is not like above,what's the hell?
In [4]: list=[1323l,123123l,4444l,12312312l]
In [5]: list=[1323l,123123l,4444l,12312312l]
In [6]: list[::2]
Out[6]: [1323L, 4444L]
| [
"The step denotes the multiples of indices that are included in the slice, not of the actual values contained in the array. In your second example:\nlist[0] = 1323L\nlist[1] = 123123L\nlist[2] = 4444L\nlist[3] = 12312312L\n\nSince you're using the default argument for the start of the slice, it will start at the fi... | [
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003965507_list_python.txt |
Q:
Python Boto S3 to work with Custom Domains in Amazon S3
How do I use the Python Boto library with S3 where the URL's it generate will be my CNAME'd subdomain to the Amazon S3 Server.
By default it uses the default format BUCKETNAME.s3.amazonaws.com but S3 supports custom domain aliasing using CNAME (so you can have custom.domain.com -> CNAME -> custom.domain.com.s3.amazonaws.com where "custom.domain.com" is the bucket. AWS Documentation
I see that the boto library has boto.s3.connection.SubdomainCallingFormat and class boto.s3.connection.VHostCallingFormat...
Anyone know how I can setup the boto.s3 where the generate URL's are for my own custom domain instead of the default?
A:
Your CNAME records must be already pointing to your S3 bucket.
Your S3 bucket needs to also be named custom.domain.com
Verify you are able to access your files from custom.domain.com in your browser.
Once that's done, the following snippet I wrote will print the URL's to all the files within a key:
import sys
import boto.s3
from boto.s3.connection import VHostCallingFormat
from boto.s3.connection import S3Connection
def main():
access_key = "<AWS_ACCESS_KEY>"
secret_key = "<AWS_SECRET_KEY>"
bucket = "custom.domain.com"
# assuming you have your files organized with keys
key_prefix = "css"
key_prefix = key_prefix + "/"
conn = S3Connection(access_key, secret_key, calling_format=VHostCallingFormat())
bucket = conn.get_bucket(bucket)
# get all the keys with the prefix 'css/' inside said bucket
keys = bucket.get_all_keys(prefix=key_prefix)
for k in keys:
print k.generate_url(3600, query_auth=False, force_http=True)
# output:
# http://custom.domain.com/css/ie.css
# http://custom.domain.com/css/print.css
# http://custom.domain.com/css/screen.css
# http://custom.domain.com/css/style.min.css
if __name__ == '__main__':
main()
| Python Boto S3 to work with Custom Domains in Amazon S3 | How do I use the Python Boto library with S3 where the URL's it generate will be my CNAME'd subdomain to the Amazon S3 Server.
By default it uses the default format BUCKETNAME.s3.amazonaws.com but S3 supports custom domain aliasing using CNAME (so you can have custom.domain.com -> CNAME -> custom.domain.com.s3.amazonaws.com where "custom.domain.com" is the bucket. AWS Documentation
I see that the boto library has boto.s3.connection.SubdomainCallingFormat and class boto.s3.connection.VHostCallingFormat...
Anyone know how I can setup the boto.s3 where the generate URL's are for my own custom domain instead of the default?
| [
"\nYour CNAME records must be already pointing to your S3 bucket.\nYour S3 bucket needs to also be named custom.domain.com\nVerify you are able to access your files from custom.domain.com in your browser.\n\nOnce that's done, the following snippet I wrote will print the URL's to all the files within a key:\nimport ... | [
2
] | [] | [] | [
"amazon_s3",
"boto",
"cname",
"python",
"subdomain"
] | stackoverflow_0002366093_amazon_s3_boto_cname_python_subdomain.txt |
Q:
Stock Symbols using python
I am looking for some stock symbol look-up API. I could able to query yahoo finance with a symbol & could able to retrieve the stock price & other details.
Is there any API for stock symbol searches
Any help would be great ..
Thanks
A:
You could use Python's urllib or the mechanise library to scrape the data from a website which publishes this data. Mechanise would be a better choice if the website requires some interaction before you can get hold of the data (like logging in).
EDIT - for getting stock quote for BT from Yahoo's UK site:
>>> import urllib
>>> import re
>>> data = urllib.urlopen('http://uk.finance.yahoo.com/q?s=BT&m=L&d=').read()
>>> re.search('<span id="yfs_l10_bt-a\.l".*?>([0-9.]+)', data).group(1)
'122.00'
The id in the regular expression was taken by viewing the source of the page and finding the id of the tag that surrounded the data required.
A:
As an alternative to parsing the HTML you could be downloading a clean pre-formatted .csv file. See the tutorial at http://www.gummy-stuff.org/Yahoo-data.htm. Found it in the question awatts linked to.
A:
Take a look at the Company Fundamentals API at http://www.mergent.com/servius
| Stock Symbols using python | I am looking for some stock symbol look-up API. I could able to query yahoo finance with a symbol & could able to retrieve the stock price & other details.
Is there any API for stock symbol searches
Any help would be great ..
Thanks
| [
"You could use Python's urllib or the mechanise library to scrape the data from a website which publishes this data. Mechanise would be a better choice if the website requires some interaction before you can get hold of the data (like logging in).\nEDIT - for getting stock quote for BT from Yahoo's UK site:\n>>> i... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002910808_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.