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 object has no referrers but still accessible via a weakref? Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference? If so how would I start trying to identify the cause for this object not being garbage collected? Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers(). Edit: Solved. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up. A: Yes: http://docs.python.org/library/weakref.html A weak reference won't be keeping the object alive. The get_referrers() function will only locate those containers which support garbage collection; extension types which do refer to other objects but do not support garbage collection will not be found. What makes you think the object isn't getting collected? Also, have you tried gc.collect()? A: It might also be the case that a reference was leaked by a buggy C extension, IMHO you will not see the referer, yet still the refcount does not go down to 0. You might want to check the return value of sys.getrefcount. A: I am glad you have found your problem, unrelated to the initial question. Nonetheless, I have a different take on the answer for posterity, in case others have the problem. It IS legal for the object to have no referrers and yet not be garbage collected. From the Python 2.7 manual: "An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable." The NO-OP garbage collector is legal. The discussions about generational and reference-counting garbage collectors are referring to a particular CPython implementation (as tagged in the question) A: As Christopher says, a weak reference does not count into object refcount, and therefore is not able to keep Python from deleting an object. However, Python's garbage collector does not delete objects that are in a circular reference and have a __del__ method defined. You can check (and fix) such situation by using gc.garbage. A: If you do have a strong reference to the object, use gc.get_referrers(obj) to find it. This can help if you have a leak and don't know what's leaking: http://mg.pov.lt/objgraph.py http://mg.pov.lt/blog/hunting-python-memleaks http://mg.pov.lt/blog/python-object-graphs.html It's a thin wrapper around the inspect module; it can help a lot if you have hard-to-track unwanted references. For just tracking down a reference, though, gc.get_referrers is probably all you need.
Python object has no referrers but still accessible via a weakref?
Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference? If so how would I start trying to identify the cause for this object not being garbage collected? Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers(). Edit: Solved. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.
[ "Yes: http://docs.python.org/library/weakref.html\nA weak reference won't be keeping the object alive.\nThe get_referrers() function will only locate those containers which support garbage collection; extension types which do refer to other objects but do not support garbage collection will not be found.\nWhat make...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "cpython", "garbage_collection", "python" ]
stackoverflow_0001127836_cpython_garbage_collection_python.txt
Q: Python programming help I have this python file that I'm working on: class Range: """ An object that has a non-negative start position and a non-negative length""" def __init__(self, start, end): """ Function: generates a new Range Returns : a new range Args : start - start position end - end position Start and End must be non-negative """ self.start = 0 self.end = 10000 self.setStart(start) self.setEnd(end) def getStart(self): """ Function: get the start of the range Returns : a number or None Args : start - the int index of the first nucleotide of this range """ return self.start def setStart(self, s): """ Function: set the start of the range Returns : None Args : start - a non-negative int or None """ if type(s) !=int: raise TypeError ("Cannot set Start as this is not an interger") elif s < 0: raise ValueError ("Cannot set Start as this is not a non-negative int") elif s > self.end: raise ValueError("start cannot be larger than end") else: self.start = s def getEnd(self): """ Function: get the end of the range Returns : a number Args : """ return self.end def setEnd(self, e): """ Function: set the end of the range Returns : None Args : end - a non-negative int or None """ if type(e) !=int: raise TypeError ("Cannot set End as this is not an interger") elif e < 0: raise ValueError ("Cannot set End as this is not a non-negative int") elif e < self.start: raise ValueError ("end has to be larger than start") else: self.end = e def getLength(self): """ Function: get the length of the range Returns : an int. the length of this range Args: """ return self.end - self.start def overlaps(self, r): """ Function: to test if two nucleotide is overlap Returns : True or False Args : other - a Range object """ start1 = self.getStart() end1 = start1 + self.getLength() start2 = r.getStart() end2 = start2 + self.getLength() max_start = max(start1,start2) min_end = min(end1,end2) return min_end - max_start > 0 if self.getStart() == r.getStart(): return True else: return False class DNAFeature(Range): """Represents a feature on a DNA sequence """ def __init__(self, seq_name = None, strand = 0, **kwargs): """ Function : represents a rane Returns : Args : strand, seqname, **kwargs """ Range.__init__(self, **kwargs) self.setStrand(strand) self.setSeqName(seq_name) def getSeqName(self): """ Function: Gets object's Sequence Name Returns : seqname - string Args : """ return self.seq_name def setSeqName(self, seq_name): """ Function: Sets object's Sequence Name Returns : None Args : seqname - mRNA accession name """ self.seq_name = seq_name def getStrand(self): """ Function: Retrieve the strand affiliation of this Returns : 1, 0, -1 - strand Args : """ return self.strand def setStrand(self, strand): """ Function: sets which strand the object is on Returns : None Args : strand - one of ['+',1,'F','-',-1,'R'] """ StrandValues = [1, 0, -1] if not strand in StrandValues: raise ValueError("only able to setStrand if the values is 1, 0, or -1") else: self.strand = strand def overlaps(self, other, ignore_strand = True): """ Function: tests if this overlaps other Returns : true if the ranges have same Seqname and overlap, false if not Args : other - another Range object """ if ignore_strand == True and self.getSeqName() == other.getSeqName(): return Range.overlaps(self,other) else: return False class GeneModel(DNAFeature): def __init__(self, transl_start=None, transl_stop=None, display_id = None, **kwargs): """ Function : contains a group of DNAFeature objects representing exons Returns : Args : **kwargs """ DNAFeature.__init__(self, **kwargs) self.setTranslStart(transl_start) self.setTranslStop(transl_stop) self.setDisplayId(display_id) self.exons = [ ] def getFeats(self): """ Function: gets object's feats list Returns : list of feature keys Args : feature_type - the type of strand the object holds """ self.exons.sort(cmp=self.start) return self.exons def addFeat(self, feat): """ Function: adds SeqFeature to feats keys Returns : None Args : feat - a single SeqFeature object """ if type(feat) == DNAFeature: self.exons.append(feat) else: raise TypeError("Cannot add feature as it is not a type of DNAFeature") def setTranslStart(self, transl_start): """ Function : accepts an non-negative int, sets the start position of the initiating ATG Returns : Args : transl_start """ if transl_start == None: self.transl_start = None return elif type(transl_start) !=int: raise TypeError("TranslStart cannot be set since it is not a type of int") elif transl_start < 0: raise ValueError("TranslStart cannot be set to a negative int") else: self.translStart = transl_start def getTranslStart(self): """ Function: the start position of initiating ATG codon Return : an int. Args : """ return self.transl_start def setTranslStop(self, transl_stop): """ Function: set the end position of initiating ATG codon Return : None Args : a positive int """ if transl_stop == None: self.transl_stop = None return elif type(transl_stop) !=int: raise TypeError("TranslStop cannot be set since it is not a type of int") elif transl_stop < 0: raise ValueError("TranslStop cannot be set to a negative int") else: self.translStop = transl_stop def getTranslStop(self): """ Function: the end position of initiating ATG codon Return : an int. Args : """ return self.transl_stop def setDisplayId(self, display_id): """ Function: set the display id Returns : None Args : display_id - a string, a preferred name for this """ if type(display_id) !=str: raise TypeError("Cannot set displayId as it is not a type string") else: self.display_id = display_id def getDisplayId(self): """ Function: get the display id Returns : display_id - a string, a preferred name for this, e.g AT1G10555.1 Args : """ return self.display_id Then, I got some code from my professor to test my file: class TestGeneModelConstructor(unittest.TestCase): def testGeneModelConstructor(self): """GeneModel constructor supports named arguments display_id,transl_start,transl_stop""" p1.GeneModel(start=0,end=10,seq_name='something',strand=1,display_id='foobar', transl_start=0,transl_stop=10) def testGeneModelConstructorDefaults(self): """Default values for display_id, transl_start, transl_stop should be None""" r = p1.GeneModel() self.assertEquals(r.getDisplayId(),None) self.assertEquals(r.getTranslStart(),None) self.assertEquals(r.getTranslStop(),None) def testGeneModelConstructorWrongTypeDisplayId(self): """Raise a TypeError if display_id is not a string.""" self.assertRaises(TypeError,p1.GeneModel,display_id=0) def testGeneModelConstructorWrongTypeTranslStart(self): """Raise a TypeError if transl_start is not an int.""" self.assertRaises(TypeError,p1.GeneModel,transl_start='0') def testGeneModelConstructorWrongTypeTranslStop(self): """Raise a TypeError if transl_stop is not an int.""" self.assertRaises(TypeError,p1.GeneModel,transl_stop='0') def testGeneModelConstructorWrongValueTranslStart(self): """Raise a ValueError if transl_start is int < 0.""" self.assertRaises(ValueError,p1.GeneModel,transl_start=-1) def testGeneModelConstructorWrongValueTranslStop(self): """Raise a ValueError if transl_stop is int < 0.""" self.assertRaises(ValueError,p1.GeneModel,transl_stop=-1) I have run it and got these errors: ERROR: Default values for display_id, transl_start, transl_stop should be None ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 117, in testGeneModelConstructorDefaults r = p1.GeneModel() TypeError: __init__() takes at least 3 arguments (1 given) ====================================================================== ERROR: Raise a ValueError if transl_start is int < 0. ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 136, in testGeneModelConstructorWrongValueTranslStart self.assertRaises(ValueError,p1.GeneModel,transl_start=-1) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 336, in failUnlessRaises TypeError: __init__() takes at least 3 non-keyword arguments (2 given) ====================================================================== ERROR: Raise a ValueError if transl_stop is int < 0. ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 140, in testGeneModelConstructorWrongValueTranslStop self.assertRaises(ValueError,p1.GeneModel,transl_stop=-1) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 336, in failUnlessRaises TypeError: __init__() takes at least 3 non-keyword arguments (1 given) I'm not sure what is wrong, I have tried to fixed it couple times, but haven't figure out what is wrong in my codes. Alright, I have change my code in DNAFeature like this: class DNAFeature(Range): """Represents a feature on a DNA sequence """ def __init__(self, seq_name = None, strand = 0, **kwargs): """ Function : represents a rane Returns : Args : strand, seqname, **kwargs """ Range.__init__(self, 0,10000, **kwargs) self.setStrand(strand) self.setSeqName(seq_name) And then, get 3 more errors and 1 failure like this: ERROR: DNAFeature on different sequence don't overlap ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 164, in testDiffSequenceOverlaps r1 = p1.DNAFeature(start=0,end=10,strand=1,seq_name="foo") File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__ Range.__init__(self, 0, 10000, **kwargs) TypeError: __init__() got multiple values for keyword argument 'start' ====================================================================== ERROR: DNAFeatures on the same strand can overlap if ignore_strand is True. ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 185, in testDiffStrandsDontOverlap r1 = p1.DNAFeature(start=0,end=10,strand=1,seq_name="foo") File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__ Range.__init__(self, 0, 10000, **kwargs) TypeError: __init__() got multiple values for keyword argument 'start' ====================================================================== ERROR: GeneModel constructor supports named arguments display_id,transl_start,transl_stop ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 113, in testGeneModelConstructor transl_start=0,transl_stop=10) File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 151, in __init__ DNAFeature.__init__(self, **kwargs) File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__ Range.__init__(self, 0, 10000, **kwargs) TypeError: __init__() got multiple values for keyword argument 'start' FAIL: Raise a TypeError if seq_name is not a string. ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 98, in testDNAFeatureSeqNameConstructorWrongType self.assertRaises(TypeError,p1.DNAFeature,seq_name=0) AssertionError: TypeError not raised A: There are several things wrong: Firstly: In your test function, testGeneModelConstructorDefaults, you have the comment: "Default values for display_id, transl_start, transl_stop should be None". The problem you are seeing is that you have only set up the defaults on 1 of the 3 arguments; whereas this test function assumes you have set up defaults on all three. To fix this, you need to define the constructor like this: def __init__(self, transl_start=None, transl_stop=None, display_id = None, **kwargs) By having the keyword arguments, it will use the default of None. If you don't specify those keyword arguments explicitly, Python will complain (as it is currently doing). Secondly: You have to consider your superclass constructors. The Range superclass asks for two parameters: start and end. def __init__(self, start, end): However, when the DNAFeature constructor calls the Range superclass, it doesn't pass in begin or end: Range.__init__(self, **kwargs) This is where I think the error is now (I think before it was at the p1.GeneModel() call - there are probably different error lines in your two error messages). To fix this, make the values for start and end into keyword parameters also. So instead of: def __init__(self, start, end): make it: def __init__(self, start=0, end=10000): You can then delete the following lines of code in your range constructor: self.start = 0 self.end = 10000 That should at least get you past this error - you may find more errors that you have. A: It appears that the tests are assuming that all parameters are passed by value. You need to give the positional arguments defaults. A: Smashery is right. Try running this simplified code: class GeneModel(object): def __init__(self, transl_start=None, transl_stop=None, display_id = None, **kwargs): pass def testGeneModelConstructor(): g = GeneModel(start=0,end=10,seq_name='something',strand=1,display_id='foobar', transl_start=0,transl_stop=10) def testGeneModelConstructorDefaults(): r = GeneModel() testGeneModelConstructor() testGeneModelConstructorDefaults()
Python programming help
I have this python file that I'm working on: class Range: """ An object that has a non-negative start position and a non-negative length""" def __init__(self, start, end): """ Function: generates a new Range Returns : a new range Args : start - start position end - end position Start and End must be non-negative """ self.start = 0 self.end = 10000 self.setStart(start) self.setEnd(end) def getStart(self): """ Function: get the start of the range Returns : a number or None Args : start - the int index of the first nucleotide of this range """ return self.start def setStart(self, s): """ Function: set the start of the range Returns : None Args : start - a non-negative int or None """ if type(s) !=int: raise TypeError ("Cannot set Start as this is not an interger") elif s < 0: raise ValueError ("Cannot set Start as this is not a non-negative int") elif s > self.end: raise ValueError("start cannot be larger than end") else: self.start = s def getEnd(self): """ Function: get the end of the range Returns : a number Args : """ return self.end def setEnd(self, e): """ Function: set the end of the range Returns : None Args : end - a non-negative int or None """ if type(e) !=int: raise TypeError ("Cannot set End as this is not an interger") elif e < 0: raise ValueError ("Cannot set End as this is not a non-negative int") elif e < self.start: raise ValueError ("end has to be larger than start") else: self.end = e def getLength(self): """ Function: get the length of the range Returns : an int. the length of this range Args: """ return self.end - self.start def overlaps(self, r): """ Function: to test if two nucleotide is overlap Returns : True or False Args : other - a Range object """ start1 = self.getStart() end1 = start1 + self.getLength() start2 = r.getStart() end2 = start2 + self.getLength() max_start = max(start1,start2) min_end = min(end1,end2) return min_end - max_start > 0 if self.getStart() == r.getStart(): return True else: return False class DNAFeature(Range): """Represents a feature on a DNA sequence """ def __init__(self, seq_name = None, strand = 0, **kwargs): """ Function : represents a rane Returns : Args : strand, seqname, **kwargs """ Range.__init__(self, **kwargs) self.setStrand(strand) self.setSeqName(seq_name) def getSeqName(self): """ Function: Gets object's Sequence Name Returns : seqname - string Args : """ return self.seq_name def setSeqName(self, seq_name): """ Function: Sets object's Sequence Name Returns : None Args : seqname - mRNA accession name """ self.seq_name = seq_name def getStrand(self): """ Function: Retrieve the strand affiliation of this Returns : 1, 0, -1 - strand Args : """ return self.strand def setStrand(self, strand): """ Function: sets which strand the object is on Returns : None Args : strand - one of ['+',1,'F','-',-1,'R'] """ StrandValues = [1, 0, -1] if not strand in StrandValues: raise ValueError("only able to setStrand if the values is 1, 0, or -1") else: self.strand = strand def overlaps(self, other, ignore_strand = True): """ Function: tests if this overlaps other Returns : true if the ranges have same Seqname and overlap, false if not Args : other - another Range object """ if ignore_strand == True and self.getSeqName() == other.getSeqName(): return Range.overlaps(self,other) else: return False class GeneModel(DNAFeature): def __init__(self, transl_start=None, transl_stop=None, display_id = None, **kwargs): """ Function : contains a group of DNAFeature objects representing exons Returns : Args : **kwargs """ DNAFeature.__init__(self, **kwargs) self.setTranslStart(transl_start) self.setTranslStop(transl_stop) self.setDisplayId(display_id) self.exons = [ ] def getFeats(self): """ Function: gets object's feats list Returns : list of feature keys Args : feature_type - the type of strand the object holds """ self.exons.sort(cmp=self.start) return self.exons def addFeat(self, feat): """ Function: adds SeqFeature to feats keys Returns : None Args : feat - a single SeqFeature object """ if type(feat) == DNAFeature: self.exons.append(feat) else: raise TypeError("Cannot add feature as it is not a type of DNAFeature") def setTranslStart(self, transl_start): """ Function : accepts an non-negative int, sets the start position of the initiating ATG Returns : Args : transl_start """ if transl_start == None: self.transl_start = None return elif type(transl_start) !=int: raise TypeError("TranslStart cannot be set since it is not a type of int") elif transl_start < 0: raise ValueError("TranslStart cannot be set to a negative int") else: self.translStart = transl_start def getTranslStart(self): """ Function: the start position of initiating ATG codon Return : an int. Args : """ return self.transl_start def setTranslStop(self, transl_stop): """ Function: set the end position of initiating ATG codon Return : None Args : a positive int """ if transl_stop == None: self.transl_stop = None return elif type(transl_stop) !=int: raise TypeError("TranslStop cannot be set since it is not a type of int") elif transl_stop < 0: raise ValueError("TranslStop cannot be set to a negative int") else: self.translStop = transl_stop def getTranslStop(self): """ Function: the end position of initiating ATG codon Return : an int. Args : """ return self.transl_stop def setDisplayId(self, display_id): """ Function: set the display id Returns : None Args : display_id - a string, a preferred name for this """ if type(display_id) !=str: raise TypeError("Cannot set displayId as it is not a type string") else: self.display_id = display_id def getDisplayId(self): """ Function: get the display id Returns : display_id - a string, a preferred name for this, e.g AT1G10555.1 Args : """ return self.display_id Then, I got some code from my professor to test my file: class TestGeneModelConstructor(unittest.TestCase): def testGeneModelConstructor(self): """GeneModel constructor supports named arguments display_id,transl_start,transl_stop""" p1.GeneModel(start=0,end=10,seq_name='something',strand=1,display_id='foobar', transl_start=0,transl_stop=10) def testGeneModelConstructorDefaults(self): """Default values for display_id, transl_start, transl_stop should be None""" r = p1.GeneModel() self.assertEquals(r.getDisplayId(),None) self.assertEquals(r.getTranslStart(),None) self.assertEquals(r.getTranslStop(),None) def testGeneModelConstructorWrongTypeDisplayId(self): """Raise a TypeError if display_id is not a string.""" self.assertRaises(TypeError,p1.GeneModel,display_id=0) def testGeneModelConstructorWrongTypeTranslStart(self): """Raise a TypeError if transl_start is not an int.""" self.assertRaises(TypeError,p1.GeneModel,transl_start='0') def testGeneModelConstructorWrongTypeTranslStop(self): """Raise a TypeError if transl_stop is not an int.""" self.assertRaises(TypeError,p1.GeneModel,transl_stop='0') def testGeneModelConstructorWrongValueTranslStart(self): """Raise a ValueError if transl_start is int < 0.""" self.assertRaises(ValueError,p1.GeneModel,transl_start=-1) def testGeneModelConstructorWrongValueTranslStop(self): """Raise a ValueError if transl_stop is int < 0.""" self.assertRaises(ValueError,p1.GeneModel,transl_stop=-1) I have run it and got these errors: ERROR: Default values for display_id, transl_start, transl_stop should be None ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 117, in testGeneModelConstructorDefaults r = p1.GeneModel() TypeError: __init__() takes at least 3 arguments (1 given) ====================================================================== ERROR: Raise a ValueError if transl_start is int < 0. ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 136, in testGeneModelConstructorWrongValueTranslStart self.assertRaises(ValueError,p1.GeneModel,transl_start=-1) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 336, in failUnlessRaises TypeError: __init__() takes at least 3 non-keyword arguments (2 given) ====================================================================== ERROR: Raise a ValueError if transl_stop is int < 0. ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 140, in testGeneModelConstructorWrongValueTranslStop self.assertRaises(ValueError,p1.GeneModel,transl_stop=-1) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 336, in failUnlessRaises TypeError: __init__() takes at least 3 non-keyword arguments (1 given) I'm not sure what is wrong, I have tried to fixed it couple times, but haven't figure out what is wrong in my codes. Alright, I have change my code in DNAFeature like this: class DNAFeature(Range): """Represents a feature on a DNA sequence """ def __init__(self, seq_name = None, strand = 0, **kwargs): """ Function : represents a rane Returns : Args : strand, seqname, **kwargs """ Range.__init__(self, 0,10000, **kwargs) self.setStrand(strand) self.setSeqName(seq_name) And then, get 3 more errors and 1 failure like this: ERROR: DNAFeature on different sequence don't overlap ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 164, in testDiffSequenceOverlaps r1 = p1.DNAFeature(start=0,end=10,strand=1,seq_name="foo") File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__ Range.__init__(self, 0, 10000, **kwargs) TypeError: __init__() got multiple values for keyword argument 'start' ====================================================================== ERROR: DNAFeatures on the same strand can overlap if ignore_strand is True. ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 185, in testDiffStrandsDontOverlap r1 = p1.DNAFeature(start=0,end=10,strand=1,seq_name="foo") File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__ Range.__init__(self, 0, 10000, **kwargs) TypeError: __init__() got multiple values for keyword argument 'start' ====================================================================== ERROR: GeneModel constructor supports named arguments display_id,transl_start,transl_stop ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 113, in testGeneModelConstructor transl_start=0,transl_stop=10) File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 151, in __init__ DNAFeature.__init__(self, **kwargs) File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__ Range.__init__(self, 0, 10000, **kwargs) TypeError: __init__() got multiple values for keyword argument 'start' FAIL: Raise a TypeError if seq_name is not a string. ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 98, in testDNAFeatureSeqNameConstructorWrongType self.assertRaises(TypeError,p1.DNAFeature,seq_name=0) AssertionError: TypeError not raised
[ "There are several things wrong:\nFirstly:\nIn your test function, testGeneModelConstructorDefaults, you have the comment: \"Default values for display_id, transl_start, transl_stop should be None\".\nThe problem you are seeing is that you have only set up the defaults on 1 of the 3 arguments; whereas this test fun...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004093530_python.txt
Q: finding all float literals in Python code I am trying to find all occurrences of a literal float value in Python code. Can I do that in Komodo (or in any other way)? In other words, I want to find every line where something like 0.0 or 1.5 or 1e5 is used, assuming it is interpreted by Python as a float literal (so no comments, for example). I'm using Komodo 6.0 with Python 3.1. If possible, a way to find string and integer literals would be nice to have as well. A: You could do that by selecting what you need with regular expressions. This command (run it on a terminal) should do the trick: sed -r "s/^([^#]*)#.*$/\1/g" YOUR_FILE | grep -P "[^'\"\w]-?[1-9]\d*[.e]\d*[^'\"\w]" You'll probably need to tweak it to get a better result. `sed' cuts out comments, while grep selects only lines containing (a small subsect of - the expression I gave is not perfect) float values... Hope it helps. A: Our SD Source Code Search Engine (SCSE) can easily do this. SCSE is a tool for searching large source code bases, much faster than grep, by indexing the elements of the source code languages of interest. Queries can then be posed, which use the index to enable fast location of search hits. Queries and hits are displayed in a GUI, and a click on a hit will show the block of source code containing the hit. The SCSE knows the lexical structure of each language it has indexed with the precision as that langauge's compiler. (It uses front ends from family of accurate programming language processors; this family is pretty large and happens to include the OP's target langauge of Python/Perl/Java/...). Thus it knows exactly where identifiers, comments, and literals (integral, float, character or string) are, and exactly their content. SCSE queries are composed of commands representing sequences of language elements of interest. The query 'for' ... I '=' N=103 finds a for keyword near ("...") an arbitrary identifier(I) which is initialized ("=") with the numeric value ("N") of 103. Because SCSE understands the language structure, it ignores language-whitespace between the tokens, e.g., it can find this regardless off intervening blanks, whitespace, newlines or comments. The query tokens I, N, F, S, C represent I(dentifier), Natural (number), F(loat), S(tring) and C(omment) respectively. The OP's original question, of finding all the floats, is thus the nearly trivial query F Similarly for finding all String literals ("S") and integral literals ("N"). If you wanted to find just copies of values near Pi, you'd add low and upper bound constraints: F>3.14<3.16 (It is pretty funny to run this on large Fortran codes; you see all kinds of bad approximations of Pi). SCSE won't find a Float in a comment or a string, because it intimately knows the difference. Writing a grep-style expression to handle all the strange combinations to eliminate whitespace or surrounding quotes and commente delimiters should be obviously a lot more painful. Grep ain't the way to do this.
finding all float literals in Python code
I am trying to find all occurrences of a literal float value in Python code. Can I do that in Komodo (or in any other way)? In other words, I want to find every line where something like 0.0 or 1.5 or 1e5 is used, assuming it is interpreted by Python as a float literal (so no comments, for example). I'm using Komodo 6.0 with Python 3.1. If possible, a way to find string and integer literals would be nice to have as well.
[ "You could do that by selecting what you need with regular expressions.\nThis command (run it on a terminal) should do the trick:\nsed -r \"s/^([^#]*)#.*$/\\1/g\" YOUR_FILE | grep -P \"[^'\\\"\\w]-?[1-9]\\d*[.e]\\d*[^'\\\"\\w]\"\n\nYou'll probably need to tweak it to get a better result.\n`sed' cuts out comments, w...
[ 1, 1 ]
[]
[]
[ "ide", "komodo", "python" ]
stackoverflow_0004092595_ide_komodo_python.txt
Q: How can I save / copy classes & functions I've written in the python interpreter? How can you save functions/ classes you've writing in a python interactive session to a file? Specifically, is there a way in pydev / eclipse's interactive session (on a mac) to do this? I just started learning python - and am enjoying using the interpreter's interactive session for testing and playing with modules I've written. However, I find myself writing functions in the interpreter, which I think, oh it would be cool to save that to my script files. How do I do this? I tried: import pickle pickle.dump(my_function, open("output.p", "w")) But it seems to be more of a binary serialization, or at least nothing that I could copy and paste into my code... Are there ways to see the code behind classes & functions I've defined in the interpreter? And then copy them out of the interpreter? Update: Ok, here's what I've learned so far: I missed the easiest of all - PyDev's interactive session in eclipse allows you to right click and save your session. Still have to remove >>>'s, but gets the job done. IPython is apparently the way to go to do this. How to save a Python interactive session? has more details. A: The best environment for interactive coding sessions has to be IPython, in my opinion. It's built on and extends the basic Python interpreter with a lot of magic, including history. For example, you can issue the command %logstart to dump all subsequent input to a file, which still needs to be edited afterward before it will be a script, but gives you a lot to work with. When installing IPython, don't forget pyreadline. In general, however, it is best to write code in an IDE and then run it. IPython helps here as well. If you write and save the script, then use the IPython "run" command to run it, the entire global namespace of the script will be available for inspection in your IPython session. Additionally, you can use the -d argument to run to trigger the pdb debugger immediately on any unhandled exception. If you're more of a straightlaced IDE and debugger kind of guy, then the easiest and best lightweight environment has to be PyScripter. A: I think the answer is to change your workflow. What I do is write my functions in an editor (emacs), and then press a key combination (Ctrl-c Ctrl-e) to send the region of text to the (i)python interpreter. That way I can save the function if I want, and also play with it in an interpreter. Emacs is central to how I do it, but I'm sure there must be similar approaches with many editors (vim, gedit, etc) and IDEs. PS. Finding a good editor is crucial when working with Python. The editor must be able to move blocks of code to the left and right easily, or the whitespace issue becomes too onerous. I dislike typing blocks of code in the python interpreter because it doesn't allow me to shift blocks easily. You'll like Python even more when you find the right editor. A: You can setup a python history file which stores everything you type into the interpreter. Here's how: http://docs.python.org/tutorial/interactive.html A: I think it can't be done. Python can perform instrospection with the inspect module, but the inspect.getsource function won't work without a source file.
How can I save / copy classes & functions I've written in the python interpreter?
How can you save functions/ classes you've writing in a python interactive session to a file? Specifically, is there a way in pydev / eclipse's interactive session (on a mac) to do this? I just started learning python - and am enjoying using the interpreter's interactive session for testing and playing with modules I've written. However, I find myself writing functions in the interpreter, which I think, oh it would be cool to save that to my script files. How do I do this? I tried: import pickle pickle.dump(my_function, open("output.p", "w")) But it seems to be more of a binary serialization, or at least nothing that I could copy and paste into my code... Are there ways to see the code behind classes & functions I've defined in the interpreter? And then copy them out of the interpreter? Update: Ok, here's what I've learned so far: I missed the easiest of all - PyDev's interactive session in eclipse allows you to right click and save your session. Still have to remove >>>'s, but gets the job done. IPython is apparently the way to go to do this. How to save a Python interactive session? has more details.
[ "The best environment for interactive coding sessions has to be IPython, in my opinion. It's built on and extends the basic Python interpreter with a lot of magic, including history. For example, you can issue the command %logstart to dump all subsequent input to a file, which still needs to be edited afterward b...
[ 5, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004093088_python.txt
Q: Python error calculating I am having a problem with my code here. The error that I am receiving is on the bottom. I have to enter payroll in and calculate pay with overtime or without. enter code here ####################### Functions ######################## def Input(): try: name=raw_input("Enter your first and last name: ") titlename=name.title() except: return Input def Hours(): try: wHours=raw_input("Enter the hours you worked this week: ") except: if wHours < 1 or wHours > 60: print "Employees' can't work less than 1 hour or more than 60 hours." return lstEmp def Pay(): try: pRate=raw_input("Enter your hourly wage: ") except: if pRate < 6 or pRate > 20: print "Employees' wages can't be lower than $6.00 or greater than $20.00." return pay def calcHours(pr,h): if h <= 40: pr * h else: (h -40) *(pr *1.5) + pr * 40 return lstEmp def end(): empDone=raw_input("Please type DONE when you are finished with employees' information: ") empDone.upper() == "DONE" #################### MAINLINE CODE lstEmp=[] Names="" while True: Names=Input() WorkHours=Hours() Wages=Pay() gPay=calcHours(WorkHours, Wages) Done=end() if end(): break Traceback (most recent call last): File "J:\11-2-10.py", line 53, in gPay=calcHours(WorkHours, Wages) File "J:\11-2-10.py", line 29, in calcHours pr * h TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType' A: In Input, Hours and Pay, you assign to a variable of the same name as the functions; perhaps you mean to return these values instead? A: gPay=calcHours(Hours, Pay) You meant WorkHours, which is what you called the variable; Hours is still the function, that returned it. There are plenty of other places in the code where you've changed the variable names so they don't match any more. Also +1 gnibbler's comment. That's really not what try does, and you should never use except without a particular Exception. The bit you might want to put in the try is a conversion to integer: def getHours(): while True: hours= raw_input("Enter the hours you worked this week: ") try: hours= int(hours) except ValueError: print "That's not a number, type it proper." continue if not 1<=hours<=60: print "Employees must work between 1 and 60 hours." continue return hours
Python error calculating
I am having a problem with my code here. The error that I am receiving is on the bottom. I have to enter payroll in and calculate pay with overtime or without. enter code here ####################### Functions ######################## def Input(): try: name=raw_input("Enter your first and last name: ") titlename=name.title() except: return Input def Hours(): try: wHours=raw_input("Enter the hours you worked this week: ") except: if wHours < 1 or wHours > 60: print "Employees' can't work less than 1 hour or more than 60 hours." return lstEmp def Pay(): try: pRate=raw_input("Enter your hourly wage: ") except: if pRate < 6 or pRate > 20: print "Employees' wages can't be lower than $6.00 or greater than $20.00." return pay def calcHours(pr,h): if h <= 40: pr * h else: (h -40) *(pr *1.5) + pr * 40 return lstEmp def end(): empDone=raw_input("Please type DONE when you are finished with employees' information: ") empDone.upper() == "DONE" #################### MAINLINE CODE lstEmp=[] Names="" while True: Names=Input() WorkHours=Hours() Wages=Pay() gPay=calcHours(WorkHours, Wages) Done=end() if end(): break Traceback (most recent call last): File "J:\11-2-10.py", line 53, in gPay=calcHours(WorkHours, Wages) File "J:\11-2-10.py", line 29, in calcHours pr * h TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
[ "In Input, Hours and Pay, you assign to a variable of the same name as the functions; perhaps you mean to return these values instead?\n", "gPay=calcHours(Hours, Pay)\n\nYou meant WorkHours, which is what you called the variable; Hours is still the function, that returned it. There are plenty of other places in t...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004093803_python.txt
Q: Learning Glade along with PyGTK I've got my self sort of familiar with pygtk. I find it to be a lot of work to build GUI from code. So I turned to Glade. I'm trying to follow tutorials for Glade and PyGTK, and how they work together, however, I can't seems to find any tutorial for the GTKBuilder format. I found a couple tutorials, like http://www.wmlug.org/pdf/Intro%20to%20PyGTK.pdf, http://www.linuxjournal.com/article/6586?page=0,2 These helped me get into Glade, but I'm unsure how to proceed from there as libglade is deprecated. A: libglade has been replaced by GTK Builder which is basically a slight modification of libglade's API that's part of GTK+ proper. Here are some links which should help you with that: GTK+ and Glade3 GUI Programming Tutorial - Part 1 Libglade to GtkBuilder F.A.Q. learnpygtk.org - libglade vs gtkbuilder PyGTK Class Reference - gtk.Builder StackOverflow - What are the steps to convert from using libglade to GtkBuilder? (Python)
Learning Glade along with PyGTK
I've got my self sort of familiar with pygtk. I find it to be a lot of work to build GUI from code. So I turned to Glade. I'm trying to follow tutorials for Glade and PyGTK, and how they work together, however, I can't seems to find any tutorial for the GTKBuilder format. I found a couple tutorials, like http://www.wmlug.org/pdf/Intro%20to%20PyGTK.pdf, http://www.linuxjournal.com/article/6586?page=0,2 These helped me get into Glade, but I'm unsure how to proceed from there as libglade is deprecated.
[ "libglade has been replaced by GTK Builder which is basically a slight modification of libglade's API that's part of GTK+ proper.\nHere are some links which should help you with that:\n\nGTK+ and Glade3 GUI Programming Tutorial - Part 1\nLibglade to GtkBuilder F.A.Q.\nlearnpygtk.org - libglade vs gtkbuilder\nPyGTK ...
[ 6 ]
[]
[]
[ "glade", "gtk", "pygtk", "python" ]
stackoverflow_0004093507_glade_gtk_pygtk_python.txt
Q: Python BeautifulSoup XML Parsing I've written a simple script to parse XML chat logs using the BeautifulSoup module. The standard soup.prettify() works ok except chat logs have a lot of fluff in them. You can see both the script code and some of the XML input file I'm working with below: Code import sys from BeautifulSoup import BeautifulSoup as Soup def parseLog(file): file = sys.argv[1] handler = open(file).read() soup = Soup(handler) print soup.prettify() if __name__ == "__main__": parseLog(sys.argv[1]) Test XML Input <?xml version="1.0"?> <?xml-stylesheet type='text/xsl' href='MessageLog.xsl'?> <Log FirstSessionID="1" LastSessionID="2"><Message Date="10/31/2010" Time="3:43:48 PM" DateTime="2010-10-31T20:43:48.937Z" SessionID="1"><From><User FriendlyName="Jon"/></From> <To><User FriendlyName="Bill"/></To><Text Style="font-family:Segoe UI; color:#000000; ">hey, what's up?</Text></Message> <Message Date="10/31/2010" Time="3:44:03 PM" DateTime="2010-10-15T20:44:03.421Z" SessionID="1"><From><User FriendlyName="Jon"/></From><To><User FriendlyName="Bill"/></To><Text Style="font-family:Segoe UI; color:#000000; ">Got your message</Text></Message> <Message Date="10/31/2010" Time="3:44:31 PM" DateTime="2010-10-15T20:44:31.390Z" SessionID="2"><From><User FriendlyName="Bill"/></From><To><User FriendlyName="Jon"/></To><Text Style="font-family:Segoe UI; color:#000000; ">oh, great</Text></Message> <Message Date="10/31/2010" Time="3:44:59 PM" DateTime="2010-10-15T20:44:59.281Z" SessionID="2"><From><User FriendlyName="Bill"/></From><To><User FriendlyName="Jon"/></To><Text Style="font-family:Segoe UI; color:#000000; ">hey, i gotta run</Text></Message> I'm wanting to be able to output this into a format like the following or at least something that is more readable than pure XML: Jon: Hey, what's up? [10/31/10 @ 3:43p] Jon: Got your message [10/31/10 @ 3:44p] Bill: oh, great [10/31/10 @ 3:44p] etc.. I've heard some decent things about the PyParsing module, maybe it's time to give it a shot. A: BeautifulSoup makes getting at attributes and values in xml really simple. I tweaked your example function to use these features. import sys from BeautifulSoup import BeautifulSoup as Soup def parseLog(file): file = sys.argv[1] handler = open(file).read() soup = Soup(handler) for message in soup.findAll('message'): msg_attrs = dict(message.attrs) f_user = message.find('from').user f_user_dict = dict(f_user.attrs) print "%s: %s [%s @ %s]" % (f_user_dict[u'friendlyname'], message.find('text').decodeContents(), msg_attrs[u'date'], msg_attrs[u'time']) if __name__ == "__main__": parseLog(sys.argv[1]) A: I'd recommend using the builtin ElementTree module. BeautifulSoup is meant to handle unwell-formed code like hacked up HTML, whereas XML is well-formed and meant to be read by an XML library. Update: some of my recent reading here suggests lxml as a library built on and enhancing the standard ElementTree.
Python BeautifulSoup XML Parsing
I've written a simple script to parse XML chat logs using the BeautifulSoup module. The standard soup.prettify() works ok except chat logs have a lot of fluff in them. You can see both the script code and some of the XML input file I'm working with below: Code import sys from BeautifulSoup import BeautifulSoup as Soup def parseLog(file): file = sys.argv[1] handler = open(file).read() soup = Soup(handler) print soup.prettify() if __name__ == "__main__": parseLog(sys.argv[1]) Test XML Input <?xml version="1.0"?> <?xml-stylesheet type='text/xsl' href='MessageLog.xsl'?> <Log FirstSessionID="1" LastSessionID="2"><Message Date="10/31/2010" Time="3:43:48 PM" DateTime="2010-10-31T20:43:48.937Z" SessionID="1"><From><User FriendlyName="Jon"/></From> <To><User FriendlyName="Bill"/></To><Text Style="font-family:Segoe UI; color:#000000; ">hey, what's up?</Text></Message> <Message Date="10/31/2010" Time="3:44:03 PM" DateTime="2010-10-15T20:44:03.421Z" SessionID="1"><From><User FriendlyName="Jon"/></From><To><User FriendlyName="Bill"/></To><Text Style="font-family:Segoe UI; color:#000000; ">Got your message</Text></Message> <Message Date="10/31/2010" Time="3:44:31 PM" DateTime="2010-10-15T20:44:31.390Z" SessionID="2"><From><User FriendlyName="Bill"/></From><To><User FriendlyName="Jon"/></To><Text Style="font-family:Segoe UI; color:#000000; ">oh, great</Text></Message> <Message Date="10/31/2010" Time="3:44:59 PM" DateTime="2010-10-15T20:44:59.281Z" SessionID="2"><From><User FriendlyName="Bill"/></From><To><User FriendlyName="Jon"/></To><Text Style="font-family:Segoe UI; color:#000000; ">hey, i gotta run</Text></Message> I'm wanting to be able to output this into a format like the following or at least something that is more readable than pure XML: Jon: Hey, what's up? [10/31/10 @ 3:43p] Jon: Got your message [10/31/10 @ 3:44p] Bill: oh, great [10/31/10 @ 3:44p] etc.. I've heard some decent things about the PyParsing module, maybe it's time to give it a shot.
[ "BeautifulSoup makes getting at attributes and values in xml really simple. I tweaked your example function to use these features. \nimport sys\nfrom BeautifulSoup import BeautifulSoup as Soup\n\ndef parseLog(file):\n file = sys.argv[1]\n handler = open(file).read()\n soup = Soup(handler)\n for message ...
[ 37, 8 ]
[]
[]
[ "beautifulsoup", "parsing", "python", "xml" ]
stackoverflow_0004071696_beautifulsoup_parsing_python_xml.txt
Q: how to extract values of different field from the string in python I am newbie in python, i have to extract values from a string: str='x:10 y:12 time : 01/01/2010 11:55:55' now i have to create a dictionary in which value is stored in such a way that: x=10 y=12 time=01/01/2010 11:55:55 Please let me know how to do this? A: Have you tried anything yet? If not, here are some ideas... Using the built-in string manipulation tools For x and y: >>> s = 'x:10 y:12 time : 01/01/2010 11:55:55' >>> [pair.split(':') for pair in s.split(' ',2)[0:2]] [['x', '10'], ['y', '12']] and let's say that you then assigned that to a variable: >>> lol = [x.split(':') for x in s.split(' ',2)[0:2]] >>> d = {} >>> for i,j in lol: ... d[i] = int(j) ... >>> d {'y': 12, 'x': 10} For time maybe you can start like this: >>> [term.strip() for term in s.split(' ',2)[-1].split(':',1)] ['time', '01/01/2010 11:55:55'] Regular expressions >>> import re >>> re.findall('(\w+):(\d+)',s)[0:2] [('x', '10'), ('y', '12')] and then I'd probably just use strptime() for the final datetime portion: >>> from datetime import datetime >>> datetime.strptime([term.strip() for term in s.split(' ',2)[-1].split(':',1)][1], '%m/%d/%Y %H:%M:%S') datetime.datetime(2010, 1, 1, 11, 55, 55)
how to extract values of different field from the string in python
I am newbie in python, i have to extract values from a string: str='x:10 y:12 time : 01/01/2010 11:55:55' now i have to create a dictionary in which value is stored in such a way that: x=10 y=12 time=01/01/2010 11:55:55 Please let me know how to do this?
[ "Have you tried anything yet?\nIf not, here are some ideas... \nUsing the built-in string manipulation tools\nFor x and y: \n>>> s = 'x:10 y:12 time : 01/01/2010 11:55:55'\n>>> [pair.split(':') for pair in s.split(' ',2)[0:2]]\n[['x', '10'], ['y', '12']]\n\nand let's say that you then assigned that to a variable:...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004093935_python.txt
Q: Python3:Save File to Specified Location I have a rather simple program that writes HTML code ready for use. It works fine, except that if one were to run the program from the Python command line, as is the default, the HTML file that is created is created where python.exe is, not where the program I wrote is. And that's a problem. Do you know a way of getting the .write() function to write a file to a specific location on the disc (e.g. C:\Users\User\Desktop)? Extra cool-points if you know how to open a file browser window. A: The first problem is probably that you are not including the full path when you open the file for writing. For details on opening a web browser, read this fine manual. import os target_dir = r"C:\full\path\to\where\you\want\it" fullname = os.path.join(target_dir,filename) with open(fullname,"w") as f: f.write("<html>....</html>") import webbrowser url = "file://"+fullname.replace("\\","/") webbrowser.open(url,True,True) BTW: the code is the same in python 2.6. A: I'll admit I don't know Python 3, so I may be wrong, but in Python 2, you can just check the __file__ variable in your module to get the name of the file it was loaded from. Just create your file in that same directory (preferably using os.path.dirname and os.path.join to remain platform-independent).
Python3:Save File to Specified Location
I have a rather simple program that writes HTML code ready for use. It works fine, except that if one were to run the program from the Python command line, as is the default, the HTML file that is created is created where python.exe is, not where the program I wrote is. And that's a problem. Do you know a way of getting the .write() function to write a file to a specific location on the disc (e.g. C:\Users\User\Desktop)? Extra cool-points if you know how to open a file browser window.
[ "The first problem is probably that you are not including the full path when you open the file for writing. For details on opening a web browser, read this fine manual.\nimport os\ntarget_dir = r\"C:\\full\\path\\to\\where\\you\\want\\it\"\n\nfullname = os.path.join(target_dir,filename)\nwith open(fullname,\"w\") ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004093387_python.txt
Q: How can this very long if-statement be simplified? How can this if-statement be simplified? It makes a plus sign: http://i.stack.imgur.com/PtHO1.png If the statement is completed, then a block is set at the x and y coordinates. for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \ (y%5 == 2 or y%5 == 3 or y%5 == 4) and \ not(x%5 == 2 and y%5 == 2) and \ not(x%5 == 4 and y%5 == 2) and \ not(x%5 == 2 and y%5 == 4) and \ not(x%5 == 4 and y%5 == 4): ... A: This is the same: if (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1): A: Basically you're tiling a 5x5 binary pattern. Here's a clear expression of that: pattern = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 0]] for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if pattern[x%5][y%5]: ... This is a very simple and general approach which would allow the pattern to be easily modified. A: There are two trivial fixes: Cache the result of x % 5 and y % 5 Use in or chained < to test the values: Additionally, the test for <= 4 (or < 5) is actually redundant because every value of lx and ly will be < 5. for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): lx = x % 5 # for local-x ly = y % 5 # for local-y if lx > 1 and y > 1 and \ not (lx == 2 and ly == 2) and \ not (lx == 4 and ly == 2) and \ not (lx == 2 and ly == 4) and \ not (lx == 4 and ly == 4): Or you may just keep a list of the actually allowed tuples: cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)] for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if (x % 5, y % 5) in cross_fields: A: Building on Konrad's answer, you can simplify it further: for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): lx = x % 5 # for local-x ly = y % 5 # for local-y if (1 < lx < 5 and 1 < y < 5 and (lx, ly) not in ((2, 2), (4, 2), (2, 4), (4, 2))): A: Konrad's second answer:- cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)] for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if (x % 5, y % 5) in cross_fields: is probably the best one. However, I'll contribute:- for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): lx = x % 5 ly = y % 5 if (lx > 1 and ly == 3) or (ly > 1 and lx == 3): A: The general solution to optimizing a logic function like this is a Karnaugh map. Your truth table would be the literal plus shape you want with rows and columns being your modular tests.
How can this very long if-statement be simplified?
How can this if-statement be simplified? It makes a plus sign: http://i.stack.imgur.com/PtHO1.png If the statement is completed, then a block is set at the x and y coordinates. for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \ (y%5 == 2 or y%5 == 3 or y%5 == 4) and \ not(x%5 == 2 and y%5 == 2) and \ not(x%5 == 4 and y%5 == 2) and \ not(x%5 == 2 and y%5 == 4) and \ not(x%5 == 4 and y%5 == 4): ...
[ "This is the same:\nif (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1): \n\n", "Basically you're tiling a 5x5 binary pattern. Here's a clear expression of that:\npattern = [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0],\n [0, 0, 1, 1, 1],\n [0, 0, 0, 1, 0]]...
[ 15, 12, 7, 2, 1, 0 ]
[]
[]
[ "graphics", "if_statement", "modulus", "python", "simplification" ]
stackoverflow_0004088145_graphics_if_statement_modulus_python_simplification.txt
Q: What is the difference between Mac OS X pre-installed Python and the one from Python.org? I am a new Mac (Snow Leopard) user and I found that Python is pre-installed in Mac OS X. What is the difference between Mac OS X pre-installed Python and the one from Python.org? If I install the one from Python.org, will it break anything? Will it be redundant? EDIT What would be a good reason to prefer the Python.org version, comparing identical version numbers head-to-head? A: The Apple-supplied Python 2.6 in Mac OS X 10.6 (Snow Leopard) is currently 2.6.1 (and, based on previous OS X releases, it is unlikely Apple will update it to a newer version in a 10.6.x maintenance release). The most recent (and likely final) release of Python 2.6 is 2.6.6. So if you install the most recent python.org release, you will get the benefit of a large number of bug fixes that have been made over the lifetime of Python 2.6. There are some other differences. The python.org 2.6.x versions are built as 32-bit-only. The Apple-suppled version is built as a 32-bit/64-bit universal and will, by default, prefer to run in 64-bit mode when possible. Either one can lead to some issues when installing third-party packages with C extension modules that depend on other 3rd-party libraries. There needs to be at least one common architecture (be it 32-bit, i386, or 64-bit, x86_64) among all the components. Another difference is that the Apple-suppled 2.6 is linked with a new version of Tk 8.5; there are reported problems with the IDLE that comes with 10.6 and possibly with other applications using Tkinter. If you plan to use either, you may be better off with the python.org 2.6 which is linked with Tk 8.4. On OS X, it is particularly easy and common to install multiple Python versions even of the same major version. If you do install the python.org version, by default the installer will modify your shell search PATH so that the python.org version is found first. It will also be available via the absolute path /usr/local/bin/python2.6. The Apple-suppled version will remain available as /usr/bin/python2.6. FYI: Be aware that Python 2.7 has already been released and there are OS X installers for it available from python.org. A new, not upwards-compatible version of Python, Python 3, is also available (currently 3.1.2 with 3.2 coming in a few months) and is expected to gradually replace Python 2 in popularity as new features are only being added to Python 3. A: It's impossible to tell without knowing which version(s) you're comparing. You're best off doing python --version on your default OS X install, and then checking release notes from that version to subsequent versions. My guess (I don't have OS X) is that you're likely running 2.4.x or 2.5.x. There'll be very few regressive differences from 2.4.x forward on the 2.x version tree. Python 3.x introduces syntax changes, which will break some existing code. Perhaps the most visible change is print becomes a function in 3.0, while still a statement in 2.x. In general, amongst 2.x, syntax is only enhanced, not broken. The changes are going to be more in the libraries (i.e. the md5 module is deprecated at 2.6 in favor of the hashlib module).
What is the difference between Mac OS X pre-installed Python and the one from Python.org?
I am a new Mac (Snow Leopard) user and I found that Python is pre-installed in Mac OS X. What is the difference between Mac OS X pre-installed Python and the one from Python.org? If I install the one from Python.org, will it break anything? Will it be redundant? EDIT What would be a good reason to prefer the Python.org version, comparing identical version numbers head-to-head?
[ "The Apple-supplied Python 2.6 in Mac OS X 10.6 (Snow Leopard) is currently 2.6.1 (and, based on previous OS X releases, it is unlikely Apple will update it to a newer version in a 10.6.x maintenance release). The most recent (and likely final) release of Python 2.6 is 2.6.6. So if you install the most recent pyt...
[ 3, 0 ]
[]
[]
[ "osx_snow_leopard", "python" ]
stackoverflow_0004093015_osx_snow_leopard_python.txt
Q: dot product in python Does this Python code actually find the dot product of two vectors? import operator vector1 = (2,3,5) vector2 = (3,4,6) dotProduct = reduce( operator.add, map( operator.mul, vector1, vector2)) A: Yes it does. Here is another way >>> sum(map( operator.mul, vector1, vector2)) 48 and another that doesn't use operator at all >>> vector1 = (2,3,5) >>> vector2 = (3,4,6) >>> sum(p*q for p,q in zip(vector1, vector2)) 48 A: You can also use the numpy implementation of dot product which has large array optimizations in native code to make computations slightly faster. Even better unless you are specifically trying to write a dot product routine or avoid dependencies, using a tried tested widely used library is much better than rolling your own.
dot product in python
Does this Python code actually find the dot product of two vectors? import operator vector1 = (2,3,5) vector2 = (3,4,6) dotProduct = reduce( operator.add, map( operator.mul, vector1, vector2))
[ "Yes it does. Here is another way\n>>> sum(map( operator.mul, vector1, vector2))\n48\n\nand another that doesn't use operator at all\n>>> vector1 = (2,3,5)\n>>> vector2 = (3,4,6)\n>>> sum(p*q for p,q in zip(vector1, vector2))\n48\n\n", "You can also use the numpy implementation of dot product which has large arra...
[ 48, 7 ]
[]
[]
[ "dot_product", "python" ]
stackoverflow_0004093989_dot_product_python.txt
Q: Pyjamas framework significance I am learning Pyjamas framework of python to generate the frontend which is basically a javascript code generated by Pyjamas. Though, being a new concept and a GWT equivalent in python I am interested in learning it, but I can not really find out what is the actual significance of it? I mean we are coding in python, compiling the code and generating javascript, which allows us to put CSS classes with the code. So, basically it does not removes the need of a designer as well. Also, is it a good idea to use Pyjamas with Django? Please suggest. Thanks in advance A: GWT and Pyjamas were created to remove the drugery of coding Javascript and compensating for all of the different browser implementations and object models. Yes, you still need a designer. Yes, you can code in python and not have to learn Javascript (in theory). No, you won't have to recode to work around "features" of the Javascript implementations in new browsers or old browsers.
Pyjamas framework significance
I am learning Pyjamas framework of python to generate the frontend which is basically a javascript code generated by Pyjamas. Though, being a new concept and a GWT equivalent in python I am interested in learning it, but I can not really find out what is the actual significance of it? I mean we are coding in python, compiling the code and generating javascript, which allows us to put CSS classes with the code. So, basically it does not removes the need of a designer as well. Also, is it a good idea to use Pyjamas with Django? Please suggest. Thanks in advance
[ "GWT and Pyjamas were created to remove the drugery of coding Javascript and compensating for all of the different browser implementations and object models.\n\nYes, you still need a designer. \nYes, you can code in python and not\nhave to learn Javascript (in theory).\nNo, you won't have to recode to work \naroun...
[ 3 ]
[]
[]
[ "pyjamas", "python" ]
stackoverflow_0004093982_pyjamas_python.txt
Q: why my os.listdir return the same folder? sory, if my english bad... i'm trying to get a list of my dir this way: import os, os.path _path = "/opt/local"#this because i use mac _dir_path = os.listdir(_path) _tmp_attr = {"name":"","type":""} _tmp_data =[] for _dir_name in _dir_path: _tmp_attr["name"] = _dir_name if os.path.isdir(_path+'/'+_dir_name): _tmp_attr["type"] = "Dictionary" _tmp_data.append(_tmp_attr) print _tmp_data but it print only the last directory [{'type': 'Dictionary', 'name': 'www'}, {'type': 'Dictionary', 'name': 'www'}, ... ] A: You're re-using the same "_tmp_attr" dictionary in every loop iteration, so you're just re-adding the same instance to the _tmp_data collection and overwriting its contents in every iteration. You need to initialize a new dictionary in every iteration: _tmp_attr = { } A: What you have here is an object referencing issue. The _tmp_attr you are adding to the list are infact the same object. Each iteration of the loop simply updates it. You need to create a new _tmp_attr object for each iteration in-order for the list elements to be unique. When the loop falls through you are simply left with multiple references in the list to the same object. doing this in the loop may help: type = "" if os.path.isdir(os.path.join(_path,_dir_name)): type = "Dictionary" _tmp_data.append({"type":type,"name":_dir_name}) A: you may also want to look at os.walk
why my os.listdir return the same folder?
sory, if my english bad... i'm trying to get a list of my dir this way: import os, os.path _path = "/opt/local"#this because i use mac _dir_path = os.listdir(_path) _tmp_attr = {"name":"","type":""} _tmp_data =[] for _dir_name in _dir_path: _tmp_attr["name"] = _dir_name if os.path.isdir(_path+'/'+_dir_name): _tmp_attr["type"] = "Dictionary" _tmp_data.append(_tmp_attr) print _tmp_data but it print only the last directory [{'type': 'Dictionary', 'name': 'www'}, {'type': 'Dictionary', 'name': 'www'}, ... ]
[ "You're re-using the same \"_tmp_attr\" dictionary in every loop iteration, so you're just re-adding the same instance to the _tmp_data collection and overwriting its contents in every iteration.\nYou need to initialize a new dictionary in every iteration:\n_tmp_attr = { }\n\n", "What you have here is an object r...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004094190_python.txt
Q: Downloading Pyscripter problem? I keep trying to download Pyscripter on my 32bit Netbook, and I keep getting a range of errors such as "The installation package could not be opened". Any clue on how to make pyscripter work? A: Make sure your download is not corrupt: >>> import hashlib >>> f = open("PyScripter-v2.3.3-Setup.exe","rb") >>> s = hashlib.sha1(f.read()) >>> f.close() >>> s.hexdigest() 'dda9da0bb466c28db804c7989d14329c25cdcec8' >>>
Downloading Pyscripter problem?
I keep trying to download Pyscripter on my 32bit Netbook, and I keep getting a range of errors such as "The installation package could not be opened". Any clue on how to make pyscripter work?
[ "Make sure your download is not corrupt:\n>>> import hashlib\n>>> f = open(\"PyScripter-v2.3.3-Setup.exe\",\"rb\")\n>>> s = hashlib.sha1(f.read())\n>>> f.close()\n>>> s.hexdigest()\n'dda9da0bb466c28db804c7989d14329c25cdcec8'\n>>>\n\n" ]
[ 0 ]
[]
[]
[ "download", "pyscripter", "python" ]
stackoverflow_0004094215_download_pyscripter_python.txt
Q: Why does Google Search return HTTP Error 403? Consider the following Python code: 30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" 31 url_object = urllib.request.urlopen(url); 32 print(url_object.read()); When this is run, an Exception is thrown: File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden However, when this is put into a browser, the search returns as expected. What's going on here? How can I overcome this so I can search Google programmatically? Any thoughts? A: this should do the trick user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" headers={'User-Agent':user_agent,} request=urllib2.Request(url,None,headers) //The assembled request response = urllib2.urlopen(request) data = response.read() // The data u need A: If you want to do Google searches "properly" through a programming interface, take a look at Google APIs. Not only are these the official way of searching Google, they are also not likely to change if Google changes their result page layout. A: As lacqui suggested, the Google API's are the way they want you to make requests from code. Unfortunately, I found their documentation was aimed at people writing AJAX web pages, not making raw HTTP requests. I used LiveHTTP Headers to trace the HTTP requests that the samples made, and I found ddipaolo's blog post helpful. One more thing that messed me up: they limit you to the first 64 results from a query. Usually not a problem if you are just providing web users with a search box, but not helpful if you're trying to use Google to go data mining. I guess they don't want you to go data mining using their API. That 64 number has changed over time and varies between search products. Update: It appears they definitely do not want you to go data mining. Eventually, you get a 403 error with a link to this API access notice. Please review the Terms of Use for the API(s) you are using (linked in the right sidebar) and ensure compliance. It is likely that we blocked you for one of the following Terms of Use violations: We received automated requests, such as scraping and prefetching. Automated requests are prohibited; all requests must be made as a result of an end-user action. They also list other violations, but I think that's the one that triggered for me. I may have to investigate Yahoo's BOSS service. It doesn't seem to have as many restrictions. A: You're doing it too often. Google has limits in place to prevent getting swamped by search bots. You can also try setting the user-agent to something that more closely resembles a normal browser.
Why does Google Search return HTTP Error 403?
Consider the following Python code: 30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" 31 url_object = urllib.request.urlopen(url); 32 print(url_object.read()); When this is run, an Exception is thrown: File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden However, when this is put into a browser, the search returns as expected. What's going on here? How can I overcome this so I can search Google programmatically? Any thoughts?
[ "this should do the trick\nuser_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'\n\nurl = \"http://www.google.com/search?hl=en&safe=off&q=Monkey\"\nheaders={'User-Agent':user_agent,} \n\nrequest=urllib2.Request(url,None,headers) //The assembled request\nresponse =...
[ 27, 26, 2, 0 ]
[]
[]
[ "google_search", "python" ]
stackoverflow_0000600536_google_search_python.txt
Q: how to send a ajax not using open the webpage on google app engine you know send a ajax you can use javascript lib like: jquery $.ajax or $.post .. but this need to open the webpage but how to send a ajax and get the ajax return value not using open the webpage on google app engine thanks( i use python) updated class CounterHandler(BaseRequestHandler): def get(self): self.render_template('counters.html',{'counters': Counter.all()}) def post(self): key = self.request.get('key') # Add the task to the default queue. for loop in range(0,2): a=taskqueue.add(url='/worker', params={'key': key},method="GET") self.redirect('/') my mean is : how to send ajax and get the return value using python(on gae), not using javascript , because i was using task queue (task queue can't add a task which want to send ajax). updated2 1.i want to get the return value from a microblog like twitter, 2.so i have to send a ajax to the microblog for get the return value 3.i want to get the return string per hour , so i have to use task queue on google app engine 4.but task queue cant get the return string only use taskqueue.add(url='/worker', params={'key': key},method="GET") 5.so i have to edit the worker hander like this : class CounterWorker(BaseRequestHandler): def get(self): self.render_template('ajax.html') and the ajax.html is : <script type="text/javascript"> $.get("http:/www.digu.com/api", function(data){ $.post("/save",{ajax:data}) }) </script> A: You can use app engine's urlfetch library to fetch a url from another server (ie the blog you want to fetch a value from).
how to send a ajax not using open the webpage on google app engine
you know send a ajax you can use javascript lib like: jquery $.ajax or $.post .. but this need to open the webpage but how to send a ajax and get the ajax return value not using open the webpage on google app engine thanks( i use python) updated class CounterHandler(BaseRequestHandler): def get(self): self.render_template('counters.html',{'counters': Counter.all()}) def post(self): key = self.request.get('key') # Add the task to the default queue. for loop in range(0,2): a=taskqueue.add(url='/worker', params={'key': key},method="GET") self.redirect('/') my mean is : how to send ajax and get the return value using python(on gae), not using javascript , because i was using task queue (task queue can't add a task which want to send ajax). updated2 1.i want to get the return value from a microblog like twitter, 2.so i have to send a ajax to the microblog for get the return value 3.i want to get the return string per hour , so i have to use task queue on google app engine 4.but task queue cant get the return string only use taskqueue.add(url='/worker', params={'key': key},method="GET") 5.so i have to edit the worker hander like this : class CounterWorker(BaseRequestHandler): def get(self): self.render_template('ajax.html') and the ajax.html is : <script type="text/javascript"> $.get("http:/www.digu.com/api", function(data){ $.post("/save",{ajax:data}) }) </script>
[ "You can use app engine's urlfetch library to fetch a url from another server (ie the blog you want to fetch a value from).\n" ]
[ 1 ]
[]
[]
[ "ajax", "google_app_engine", "javascript", "jquery", "python" ]
stackoverflow_0004094114_ajax_google_app_engine_javascript_jquery_python.txt
Q: python re - split a string before a character how to split a string at positions before a character? split a string before 'a' input: "fffagggahhh" output: ["fff", "aggg", "ahhh"] the obvious way doesn't work: >>> h=re.compile("(?=a)") >>> h.split("fffagggahhh") ['fffagggahhh'] >>> A: Ok, not exactly the solution you want but I thought it will be a useful addition to problem here. Solution without re Without re: >>> x = "fffagggahhh" >>> k = x.split('a') >>> j = [k[0]] + ['a'+l for l in k[1:]] >>> j ['fff', 'aggg', 'ahhh'] >>> A: >>> rx = re.compile("(?:a|^)[^a]*") >>> rx.findall("fffagggahhh") ['fff', 'aggg', 'ahhh'] >>> rx.findall("aaa") ['a', 'a', 'a'] >>> rx.findall("fgh") ['fgh'] >>> rx.findall("") [''] A: >>> r=re.compile("(a?[^a]+)") >>> r.findall("fffagggahhh") ['fff', 'aggg', 'ahhh'] EDIT: This won't handle correctly double as in the string: >>> r.findall("fffagggaahhh") ['fff', 'aggg', 'ahhh'] KennyTM's re seems better suited. A: import re def split_before(pattern,text): prev = 0 for m in re.finditer(pattern,text): yield text[prev:m.start()] prev = m.start() yield text[prev:] if __name__ == '__main__': print list(split_before("a","fffagggahhh")) re.split treats the pattern as a delimiter. >>> print list(split_before("a","afffagggahhhaab")) ['', 'afff', 'aggg', 'ahhh', 'a', 'ab'] >>> print list(split_before("a","ffaabcaaa")) ['ff', 'a', 'abc', 'a', 'a', 'a'] >>> print list(split_before("a","aaaaa")) ['', 'a', 'a', 'a', 'a', 'a'] >>> print list(split_before("a","bbbb")) ['bbbb'] >>> print list(split_before("a","")) [''] A: This one works on repeated a's >>> re.findall("a[^a]*|^[^a]*", "aaaaa") ['a', 'a', 'a', 'a', 'a'] >>> re.findall("a[^a]*|[^a]+", "ffaabcaaa") ['ff', 'a', 'abc', 'a', 'a', 'a'] Approach: the main chunks that you are looking for are an a followed by zero or more not-a. That covers all possibilities except for zero or more not-a. That can happen only at the start of the input string.
python re - split a string before a character
how to split a string at positions before a character? split a string before 'a' input: "fffagggahhh" output: ["fff", "aggg", "ahhh"] the obvious way doesn't work: >>> h=re.compile("(?=a)") >>> h.split("fffagggahhh") ['fffagggahhh'] >>>
[ "Ok, not exactly the solution you want but I thought it will be a useful addition to problem here.\n\nSolution without re\n\nWithout re:\n>>> x = \"fffagggahhh\"\n>>> k = x.split('a')\n>>> j = [k[0]] + ['a'+l for l in k[1:]]\n>>> j\n['fff', 'aggg', 'ahhh']\n>>> \n\n", ">>> rx = re.compile(\"(?:a|^)[^a]*\")\n>>> r...
[ 21, 5, 4, 3, 1 ]
[ ">>> foo = \"abbcaaaabbbbcaaab\"\n>>> bar = foo.split(\"c\")\n>>> baz = [bar[0]] + [\"c\"+x for x in bar[1:]]\n>>> baz\n['abb', 'caaaabbbb', 'caaab']\n\nDue to how slicing works, this will work properly even if there are no occurrences of c in foo.\n", "split() takes an argument for the character to split on:\n>>...
[ -1, -3 ]
[ "python", "regex", "split" ]
stackoverflow_0004094382_python_regex_split.txt
Q: Python error: builtin function or method object has no attribute 'StringIO' I just want to download an image. Then upload it to Amazon S3. But it's not working. 'builtin_function_or_method' object has no attribute 'StringIO' Traceback (most recent call last): File "flickrDump.py", line 16, in <module> imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket="fabletest") File "../lib/s3.py", line 52, in upload_thumbnail k.set_contents_from_string(thumbnail_data) File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 539, in set_contents_from_string self.set_contents_from_file(fp, headers, replace, cb, num_cb, policy) File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 455, in set_contents_from_file self.send_file(fp, headers, cb, num_cb) File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 366, in send_file return self.bucket.connection.make_request('PUT', self.bucket.name, AttributeError: 'str' object has no attribute 'connection' My code to download it and upload it is this: tdata = tools.download("http://farm5.static.flickr.com/4148/5124630813_c11b05e6da_z.jpg") imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket="fabletest") print imgpath The library I'm using is the s3 library. I downloaded this somewhere, so it should be standard. from boto.s3.connection import S3Connection from boto.s3.key import Key from boto.s3.bucket import Bucket import datetime ACCESSKEY = 'MYKEY' SECRETKEY = 'MYSECRET' def get_bucket_path(bucket,filename,https=False): path = None if isinstance(bucket, Bucket): path = bucket.name else: path = bucket if https: return "https://s3.amazonaws.com/%s/%s" % (path, filename) else: return "http://s3.amazonaws.com/%s/%s" % (path, filename) def _aws_keys(): return ACCESSKEY, SECRETKEY def _conn(): key,secret = _aws_keys() return S3Connection(key,secret) def cache_bucket(conn = _conn()): bucket = conn.create_bucket('mimvicache') bucket.make_public() return bucket class AwsException(Exception): def __init__(self,value): self.errorval = value def __str__(self): return repr(self.errorval) def upload_thumbnail(thumbnail_name,thumbnail_data=None,thumbnail_path=None,bucket=cache_bucket (),conn=_conn(),notes=None,image_id=None): k = Key(bucket) k.key = thumbnail_name if notes is not None: k.set_metadata("notes",notes) if image_id is not None: k.set_metadata("image_id",image_id) if thumbnail_data is not None: k.set_contents_from_string(thumbnail_data) elif thumbnail_path is not None: k.set_contents_from_filename(thumbnail_path) else: raise AwsException("No file name") k.set_acl('public-read') return get_bucket_path(bucket.name,k.key) Can someone help me upload this image to S3? A: In your code: return self.bucket.connection.make_request('PUT', self.bucket.name,...... AttributeError: 'str' object has no attribute 'connection' This means that some how self.bucket is evaluated to a string and you can not obviously call method "connection" on it. So for further analysis, look at the function upload_thumbnail, it expects bucket=cache_bucket() as argument. That is it expects a bucket object. def upload_thumbnail(thumbnail_name,thumbnail_data=None,thumbnail_path=None,bucket=cache_bucket (),conn=_conn(),notes=None,image_id=None) What you are passing in your code is string !! -> (bucket="fabletest") imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket="fabletest") Your code should be some thing like this. you might have to sanitize this. But the key is to pass the bucket and connection object to function upload_thumbnail function. import S3 connection = S3.AWSAuthConnection('your access key', 'your secret key') buck = connection.create_bucket('mybucketname') tdata = tools.download("http://farm5.static.flickr.com/4148/5124630813_c11b05e6da_z.jpg") imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket=buck, conn=connection) print imgpath
Python error: builtin function or method object has no attribute 'StringIO'
I just want to download an image. Then upload it to Amazon S3. But it's not working. 'builtin_function_or_method' object has no attribute 'StringIO' Traceback (most recent call last): File "flickrDump.py", line 16, in <module> imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket="fabletest") File "../lib/s3.py", line 52, in upload_thumbnail k.set_contents_from_string(thumbnail_data) File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 539, in set_contents_from_string self.set_contents_from_file(fp, headers, replace, cb, num_cb, policy) File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 455, in set_contents_from_file self.send_file(fp, headers, cb, num_cb) File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 366, in send_file return self.bucket.connection.make_request('PUT', self.bucket.name, AttributeError: 'str' object has no attribute 'connection' My code to download it and upload it is this: tdata = tools.download("http://farm5.static.flickr.com/4148/5124630813_c11b05e6da_z.jpg") imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket="fabletest") print imgpath The library I'm using is the s3 library. I downloaded this somewhere, so it should be standard. from boto.s3.connection import S3Connection from boto.s3.key import Key from boto.s3.bucket import Bucket import datetime ACCESSKEY = 'MYKEY' SECRETKEY = 'MYSECRET' def get_bucket_path(bucket,filename,https=False): path = None if isinstance(bucket, Bucket): path = bucket.name else: path = bucket if https: return "https://s3.amazonaws.com/%s/%s" % (path, filename) else: return "http://s3.amazonaws.com/%s/%s" % (path, filename) def _aws_keys(): return ACCESSKEY, SECRETKEY def _conn(): key,secret = _aws_keys() return S3Connection(key,secret) def cache_bucket(conn = _conn()): bucket = conn.create_bucket('mimvicache') bucket.make_public() return bucket class AwsException(Exception): def __init__(self,value): self.errorval = value def __str__(self): return repr(self.errorval) def upload_thumbnail(thumbnail_name,thumbnail_data=None,thumbnail_path=None,bucket=cache_bucket (),conn=_conn(),notes=None,image_id=None): k = Key(bucket) k.key = thumbnail_name if notes is not None: k.set_metadata("notes",notes) if image_id is not None: k.set_metadata("image_id",image_id) if thumbnail_data is not None: k.set_contents_from_string(thumbnail_data) elif thumbnail_path is not None: k.set_contents_from_filename(thumbnail_path) else: raise AwsException("No file name") k.set_acl('public-read') return get_bucket_path(bucket.name,k.key) Can someone help me upload this image to S3?
[ "In your code:\nreturn self.bucket.connection.make_request('PUT', self.bucket.name,......\nAttributeError: 'str' object has no attribute 'connection'\n\nThis means that some how self.bucket is evaluated to a string and you can not obviously call method \"connection\" on it. \nSo for further analysis, look at the fu...
[ 3 ]
[]
[]
[ "amazon_s3", "debugging", "http", "image", "python" ]
stackoverflow_0004094537_amazon_s3_debugging_http_image_python.txt
Q: Steps to install py2cairo? Seems that pycairo was branched to py2cairo for 2.x versions back in May. There are no pip or easy_install installation options for py2cairo. I've grabbed the latest py2cairo tar, as well as the cairo 1.8.10 package which is registered as a dependency. When I try to configure cairo first, it errors out at the end that it needs pkg-config. However, I also can't find a pkg-config install option in pip or easy_install. I'm at a complete loss as to how to get py2cairo installed. I'm doing this on Mac Snow Leopard. A: pkg-config is a helper tool used when compiling applications and libraries. If you are using macports then the package name is pkgconfig. port install pkgconfig See the portfile at : http://trac.macports.org/browser/trunk/dports/devel/pkgconfig/Portfile The details are at : http://pkg-config.freedesktop.org/wiki/FrontPage
Steps to install py2cairo?
Seems that pycairo was branched to py2cairo for 2.x versions back in May. There are no pip or easy_install installation options for py2cairo. I've grabbed the latest py2cairo tar, as well as the cairo 1.8.10 package which is registered as a dependency. When I try to configure cairo first, it errors out at the end that it needs pkg-config. However, I also can't find a pkg-config install option in pip or easy_install. I'm at a complete loss as to how to get py2cairo installed. I'm doing this on Mac Snow Leopard.
[ "pkg-config is a helper tool used when compiling applications and libraries.\nIf you are using macports then the package name is pkgconfig.\nport install pkgconfig\n\nSee the portfile at : http://trac.macports.org/browser/trunk/dports/devel/pkgconfig/Portfile\nThe details are at : http://pkg-config.freedesktop.org/...
[ 1 ]
[]
[]
[ "cairo", "easy_install", "pip", "pycairo", "python" ]
stackoverflow_0004094777_cairo_easy_install_pip_pycairo_python.txt
Q: Is there a standard function to iterate over base classes? I would like to be able to iterate over all the base classes, both direct and indirect, of a given class, including the class itself. This is useful in the case where you have a metaclass that examines an internal Options class of all its bases. To do this, I wrote the following: def bases(cls): yield cls for direct_base in cls.__bases__: for base in bases(direct_base): yield base Is there a standard function to do this for me? A: There is a method that can return them all, in Method Resolution Order (MRO): inspect.getmro. See here: http://docs.python.org/library/inspect.html#inspect.getmro It returns them as a tuple, which you can then iterate over in a single loop yourself: import inspect for base_class in inspect.getmro(cls): # do something This has the side benefit of only yielding each base class once, even if you have diamond-patterned inheritance. A: Amber has the right answer for the real world, but I'll show one correct way to do this. Your solution will include some classes twice if two base classes themselves inherit from the same base class. def bases(cls): classes = [cls] i = 0 while 1: try: cls = classes[i] except IndexError: return classes i += 1 classes[i:i] = [base for base in cls.__bases__ if base not in classes] The only slightly tricky part is where we use the slice. That's necessary to perform this sort of depth first search without using recursion. All it does is take the base classes of the class currently being examined and insert them immediately after it so that the first base class is the next class examined. A very readable solution (that has it's own ugliness) is available in the implementation of inspect.getmro in the standard library. A: I don't know exactly if it is what you're looking for, but have a look at someclass.__mro__, mro being Method Resolution Order http://docs.python.org/library/stdtypes.html?highlight=mro#class.__mro__
Is there a standard function to iterate over base classes?
I would like to be able to iterate over all the base classes, both direct and indirect, of a given class, including the class itself. This is useful in the case where you have a metaclass that examines an internal Options class of all its bases. To do this, I wrote the following: def bases(cls): yield cls for direct_base in cls.__bases__: for base in bases(direct_base): yield base Is there a standard function to do this for me?
[ "There is a method that can return them all, in Method Resolution Order (MRO): inspect.getmro. See here:\nhttp://docs.python.org/library/inspect.html#inspect.getmro\nIt returns them as a tuple, which you can then iterate over in a single loop yourself:\nimport inspect\nfor base_class in inspect.getmro(cls):\n # ...
[ 16, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004094624_python.txt
Q: has any easy way to get full url using python on gae this is my code: url = "/aa" result = urlfetch.fetch(url) but it will be error , because you have to get the full url , like this :http://digu.com so any easy way to get the full url in my code , thanks A: Do you mean the full URL of your own app? You might want self.request.host (which would be eg digu.com) or self.request.host_url (which would be eg http://digu.com). See the documentation for the app engine Request class, and also the WebOb Request class it is based on. However, why would you make a urlfetch to your own app?
has any easy way to get full url using python on gae
this is my code: url = "/aa" result = urlfetch.fetch(url) but it will be error , because you have to get the full url , like this :http://digu.com so any easy way to get the full url in my code , thanks
[ "Do you mean the full URL of your own app?\nYou might want self.request.host (which would be eg digu.com) or self.request.host_url (which would be eg http://digu.com).\nSee the documentation for the app engine Request class, and also the WebOb Request class it is based on.\nHowever, why would you make a urlfetch to...
[ 5 ]
[]
[]
[ "google_app_engine", "python", "url" ]
stackoverflow_0004094715_google_app_engine_python_url.txt
Q: Extract fields from the string in python I have text line by line which contains many field name and their value seperated by : , if any line does not have any field value then that field would not exist in that line for example First line: A:30 B: 40 TS:1/1/1990 22:22:22 Second line A:30 TS:1/1/1990 22:22:22 third line A:30 B: 40 But it is confirmed that at max 3 fields are possible in single line and their name will be A,B,TS. while writing python script for this, i am facing below issues: 1) I have to extract from each line which are the field exist and what are their values 2) Field value of field TS also have seperator ' '(SPACE).so unable retrieve full value of TS(1/1/1990 22:22:22) Output valueshould be extracted like that First LIne: A=30 B=40 TS=1/1/1990 22:22:22 Second Line: A=30 TS=1/1/1990 22:22:22 Third Line A=30 B=40 Please help me in solving this issue. A: import re a = ["A:30 B: 40 TS:1/1/1990 22:22:22", "A:30 TS:1/1/1990 22:22:22", "A:30 B: 40"] regex = re.compile(r"^\s*(?:(A)\s*:\s*(\d+))?\s*(?:(B)\s*:\s*(\d+))?\s*(?:(TS)\s*:\s*(.*))?$") for item in a: matches = regex.search(item).groups() print {k:v for k,v in zip(matches[::2], matches[1::2]) if k} will output {'A': '30', 'B': '40', 'TS': '1/1/1990 22:22:22'} {'A': '30', 'TS': '1/1/1990 22:22:22'} {'A': '30', 'B': '40'} Explanation of the regex: ^\s* # match start of string, optional whitespace (?: # match the following (optionally, see below) (A) # identifier A --> backreference 1 \s*:\s* # optional whitespace, :, optional whitespace (\d+) # any number --> backreference 2 )? # end of optional group \s* # optional whitespace (?:(B)\s*:\s*(\d+))?\s* # same with identifier B and number --> backrefs 3 and 4 (?:(TS)\s*:\s*(.*))? # same with id. TS and anything that follows --> 5 and 6 $ # end of string A: You could use regular expressions, something like this would work if the order was assumed the same every time, otherwise you would have to match each part individually if you're unsure of the order. import re def parseInput(input): m = re.match(r"A:\s*(\d+)\s*B:\s*(\d+)\s*TS:(.+)", input) return {"A": m.group(1), "B": m.group(2), "TS": m.group(3)} print parseInput("A:30 B: 40 TS:1/1/1990 22:22:22") This prints out {'A': '30', 'B': '40', 'TS': '1/1/1990 22:22:22'} Which is just a dictionary containing the values. P.S. You should accept some answers and familiarize yourself with the etiquette of site and people will be more willing to help you out.
Extract fields from the string in python
I have text line by line which contains many field name and their value seperated by : , if any line does not have any field value then that field would not exist in that line for example First line: A:30 B: 40 TS:1/1/1990 22:22:22 Second line A:30 TS:1/1/1990 22:22:22 third line A:30 B: 40 But it is confirmed that at max 3 fields are possible in single line and their name will be A,B,TS. while writing python script for this, i am facing below issues: 1) I have to extract from each line which are the field exist and what are their values 2) Field value of field TS also have seperator ' '(SPACE).so unable retrieve full value of TS(1/1/1990 22:22:22) Output valueshould be extracted like that First LIne: A=30 B=40 TS=1/1/1990 22:22:22 Second Line: A=30 TS=1/1/1990 22:22:22 Third Line A=30 B=40 Please help me in solving this issue.
[ "import re\na = [\"A:30 B: 40 TS:1/1/1990 22:22:22\", \"A:30 TS:1/1/1990 22:22:22\", \"A:30 B: 40\"]\nregex = re.compile(r\"^\\s*(?:(A)\\s*:\\s*(\\d+))?\\s*(?:(B)\\s*:\\s*(\\d+))?\\s*(?:(TS)\\s*:\\s*(.*))?$\")\nfor item in a:\n matches = regex.search(item).groups()\n print {k:v for k,v in zip(matches[::2], ma...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004094979_python.txt
Q: Set field value in Django Form clean() method, if this field not passed in constructor I need set field value, not passed to Django Form constructor. I have model and form like this: class Message(models.Model): created = models.DateTimeField() text = models.CharField(max_length=200, blank=True, null=True) active = models.BooleanField(default=False) class MessageForm(forms.ModelForm): class Meta: model = Message exclude = ('created', 'active') def clean(self): # check if user is blocked if user.is_admin(): self.cleaned_data['active'] = True return self.cleaned_data Expected: if current user is admin - I need automatically set message as active. User should not pass this parameter by form. Actual: I see that saved message always have flag "False" (I can delete condition and in this case I also see that message is not active). Please help me understand, how can I do set this "active" flag in clean() method. A: The previous answer would work, but I like encapsulating all the form's internal operations like what to show and what not, within the form. I know you mentioned you don't want to send a field value to the constructor, but if you don't mind sending the user, your solution would work. i.e., your constructor: def __init__(self, user): self.user = user super(BaseForm, self).__init__() then in your clean, you just change the user to self.user. There is another added benefit to this. Say tomorrow you want to assign more fields based on your user, you don't need to add anything to the views, you can simply add it to the form. EDIT: When you add a field to exclude, it is not available in the cleaned data. Instead, set its widget as hidden. active = forms.BooleanField(widget=forms.HiddenInput) EDIT 2: If you really don't want the field in the form In this case, instead of overriding the clean, why don't you override the save? def save (self): super(BaseForm, self).save() if user.is_admin(): self.instance.active=True super(BaseForm, self).save() A: Don't do this in the form's clean() method, do this in the view. def your_view(request): if request.method == 'POST': form = MessageForm(data=request.POST) if form.is_valid(): new_message = form.save(commit=False) if user.is_admin(): new_message.active = True However, if you also want to handle the case where your user is not admin using the same form, you can look at incorporating similar logic in the form's init() instead of the view, probably by passing info about the user from the view to the form's init() A: Use this: def message_form_factory(user): class MessageForm(forms.ModelForm): def clean(self): # check if user is blocked if user.is_admin(): self.cleaned_data['active'] = True return self.cleaned_data return MessageForm And in your view use: form = message_form_factory(request.user)() form = message_form_factory(request.user)(request.POST)
Set field value in Django Form clean() method, if this field not passed in constructor
I need set field value, not passed to Django Form constructor. I have model and form like this: class Message(models.Model): created = models.DateTimeField() text = models.CharField(max_length=200, blank=True, null=True) active = models.BooleanField(default=False) class MessageForm(forms.ModelForm): class Meta: model = Message exclude = ('created', 'active') def clean(self): # check if user is blocked if user.is_admin(): self.cleaned_data['active'] = True return self.cleaned_data Expected: if current user is admin - I need automatically set message as active. User should not pass this parameter by form. Actual: I see that saved message always have flag "False" (I can delete condition and in this case I also see that message is not active). Please help me understand, how can I do set this "active" flag in clean() method.
[ "The previous answer would work, but I like encapsulating all the form's internal operations like what to show and what not, within the form. I know you mentioned you don't want to send a field value to the constructor, but if you don't mind sending the user, your solution would work.\ni.e., your constructor:\ndef ...
[ 5, 3, 1 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0004088309_django_django_forms_django_models_python.txt
Q: where is my code error using urlfetch on google app engine this is my code: class save(BaseRequestHandler): def get(self): counter = Counter.get_by_key_name('aa-s') counter.count += 1 url = "http://www.google.com" result = urlfetch.fetch(url) if result.status_code == 200: counter.ajax = result.content counter.put() self.redirect('/') and the error is : Traceback (most recent call last): File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__ handler.get(*groups) File "F:\ss\Task Queue\main.py", line 48, in get counter.ajax = result.content File "D:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 542, in __set__ value = self.validate(value) File "D:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 2453, in validate raise BadValueError('Property %s is not multi-line' % self.name) BadValueError: Property ajax is not multi-line INFO 2010-11-04 08:24:29,905 dev_appserver.py:3283] "GET /save HTTP/1.1" 500 - so i cant find the error , did you . thanks A: You're attempting to store the result into counter.ajax, which is a StringProperty that does not have multiline=True. Either set multiline=True in the definition of 'ajax', or replace it with a TextProperty(). The latter is almost certainly the correct answer - TextProperties can be longer, and aren't indexed. A: The error is in your Counter model. "ajax" needs to be a multiline string property. See the Types and Property Classes documentation. You'll want to do: ajax = db.StringProperty(multiline=True) Also note that db.StringProperty can only be used for strings of 500 characters or less.
where is my code error using urlfetch on google app engine
this is my code: class save(BaseRequestHandler): def get(self): counter = Counter.get_by_key_name('aa-s') counter.count += 1 url = "http://www.google.com" result = urlfetch.fetch(url) if result.status_code == 200: counter.ajax = result.content counter.put() self.redirect('/') and the error is : Traceback (most recent call last): File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__ handler.get(*groups) File "F:\ss\Task Queue\main.py", line 48, in get counter.ajax = result.content File "D:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 542, in __set__ value = self.validate(value) File "D:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 2453, in validate raise BadValueError('Property %s is not multi-line' % self.name) BadValueError: Property ajax is not multi-line INFO 2010-11-04 08:24:29,905 dev_appserver.py:3283] "GET /save HTTP/1.1" 500 - so i cant find the error , did you . thanks
[ "You're attempting to store the result into counter.ajax, which is a StringProperty that does not have multiline=True. Either set multiline=True in the definition of 'ajax', or replace it with a TextProperty(). The latter is almost certainly the correct answer - TextProperties can be longer, and aren't indexed.\n",...
[ 5, 3 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0004094896_google_app_engine_python_urlfetch.txt
Q: How do I see what the "type" of an object is, in Python? I don't know what type it is. How do I check and print it out to console? A: a type is basically a value kind and operations that are valid on that value type(object) #gives you the type if you want to test for a type import types class foo(object): pass >>> foo is types.ClassType # test if foo is a class True A: Call the type() function. See the types module for a list of type names you can use with type(). A: type(variable) will tell you what type something is. A: While you can use type() to perform introspection I have to wonder what you're really trying to accomplish. In Python it's considered to be far better practice to focus on object behavior ... API ... than on type. Do you care if the object at hand is a Foo() ... or will some subclass of Foo() or some sort of proxy for Foo() (some object containing a Foo()-like object and delegating the requisite functionality to it) do? The usual advice I see is to use Python's exception handling ... try to use the desired interfaces as if the object is of the correct type and be prepared to handle the exceptions that may be thrown if the object doesn't support that usage. (Most often that will be a TypeError or AttributeError, of course). Another option is judicious use of hasattr() to see if the object has the necessary attributes (usually methods) to be used like the desired object. (The main caveat there is that there may be method name collisions with completely incompatible semantics in unrelated classes of objects). Recent versions of Python have introduced the support for "abstract base classes" (ABCs). This basically allows you to use isinstance() and issubclass() in a way that refers to the intended semantics of the objects being tested rather than on their literal instantiation and class hierarchical artifacts. When used with an ABC isinstance() returns a value which indicates whether class supports the signature methods that are considered definitive of the intended semantics. You can read more about the most commonly used ABCs in the Python Docs: collections module (section 8.3.6). Unfortunately it's possible you could still confuse the ABCs if you re-use certain method names which have a conventional meaning in the existing Python core or standard libraries. For example if you create some UI class and define methods of .next() (perhaps to go with some hypothetical .previous()). Doing so, without further effort, would mean that a call like: isinstance(foo, collections.Iterable) would return True even though the semantics you implemented (presumably something like proceeding to the next page in your UI) are completely orthogonal to those that are intended by the collections.Iterable ABC. I think it's possible to disambiguate by creating some other abstract base class and specifically registering your class as implementing that abstraction. However, I don't know exactly how that would work. A: print object.__class__.__name__ Should do the trick.
How do I see what the "type" of an object is, in Python?
I don't know what type it is. How do I check and print it out to console?
[ "a type is basically a value kind and operations that are valid on that value\n\ntype(object) #gives you the type\n\nif you want to test for a type\n\n\nimport types\nclass foo(object):\n pass\n\n>>> foo is types.ClassType # test if foo is a class\nTrue\n\n", "Call the type() function. See the types module for...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004094626_python.txt
Q: Limit urls to a domain - Django I need to lock down various urls to a certain domain. Any ideas? A: In the view, check the get_host result on the request. If it's a bad host, return either HttpResponseNotFound or HttpResponseForbidden (depending on your specific need). Edit: perhaps you want to lock down based on the client domain. Then you should check REMOTE_HOST. A: You could also consider altering URLconf per request, in custom middleware, depending on request domain (i.e. request.get_host()). Documentation is here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.urlconf .
Limit urls to a domain - Django
I need to lock down various urls to a certain domain. Any ideas?
[ "In the view, check the get_host result on the request. If it's a bad host, return either HttpResponseNotFound or HttpResponseForbidden (depending on your specific need). \nEdit: perhaps you want to lock down based on the client domain. Then you should check REMOTE_HOST.\n", "You could also consider altering URLc...
[ 2, 1 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0004083068_django_django_urls_python.txt
Q: Python - print until marker (a la PHP)? In PHP I can do this: print <<<END This uses the "here document" syntax to output multiple lines END; Is there a way to do something similar in Python? I want to dump a big chunk of HTML without worrying about escaping e.g. angle brackets. A: Python doesn't have heredocs with arbitrary start/end markers. You can use triple quotes (either single or double) to achieve something very similar: print ''' This uses the "here document" syntax to output multiple lines ''' Add an r to make it a raw string so that backslash is also not treated specially. r'''....'''
Python - print until marker (a la PHP)?
In PHP I can do this: print <<<END This uses the "here document" syntax to output multiple lines END; Is there a way to do something similar in Python? I want to dump a big chunk of HTML without worrying about escaping e.g. angle brackets.
[ "Python doesn't have heredocs with arbitrary start/end markers. You can use triple quotes (either single or double) to achieve something very similar:\nprint '''\nThis uses the \"here document\" syntax to output\nmultiple lines\n'''\n\nAdd an r to make it a raw string so that backslash is also not treated specially...
[ 4 ]
[]
[]
[ "escaping", "heredoc", "python" ]
stackoverflow_0004095533_escaping_heredoc_python.txt
Q: Think in python, Chapter 8(lists) As an exercise, describe the relationship between string.join(string.split(song)) and song. (they both refer to a string) Are they the same for all strings? When would they be different? I am a little ashamed to ask such a question for a likely simple question but, I don't get it, what is/are the exception(s)? when are they are different? A: By default the split method groups consecutive delimiters together, so if you have them in your original string they'll be lost: >>> import string >>> song = "I am the Walrus" >>> string.join(string.split(song)) 'I am the Walrus' However, if you specify delimiters to split on then consecutive delimiters are not grouped so you can keep the strings the same: >>> string.join(string.split(song,' ')) 'I am the Walrus' A: split actually splits on one or more occurrences of the delimiter. So " a b c ".split() and "a b c".split() both result in the same list i.e. ['a','b','c']. join only adds a single instance of the delimiter in between consecutive elements of the list. " ".join(['a','b','c'])gives us"a b c"`, which matches out second string but not the first string. >>> original=" a b c " >>> " ".join(original.split()) 'a b c' BTW, using string.split and string.join is deprecated. Simply call them as methods of the string you are working on (as in my examples).
Think in python, Chapter 8(lists)
As an exercise, describe the relationship between string.join(string.split(song)) and song. (they both refer to a string) Are they the same for all strings? When would they be different? I am a little ashamed to ask such a question for a likely simple question but, I don't get it, what is/are the exception(s)? when are they are different?
[ "By default the split method groups consecutive delimiters together, so if you have them in your original string they'll be lost:\n>>> import string\n>>> song = \"I am the Walrus\"\n>>> string.join(string.split(song))\n'I am the Walrus'\n\nHowever, if you specify delimiters to split on then consecutiv...
[ 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004095634_list_python.txt
Q: Simple / Smart, Pythonic database solution, can use Python types + syntax? (Key / Value Dict, Array, maybe Ordered Dict) Looking for solutions that push the envelope and: Avoid Manually writing SQL queries(Python can be more OO not passing DSL strings) Using non-Python datatypes for a supposedly required model definition Using a new class of types rather than perfectly good native Python types Boast Using Python objects Using Object Oriented and key based retrieval and creation Quick protoyping No SQL table to make Model /Type inference or no model Less lines and characters to type Easily output to and from JSON, maybe XML or even Protocol Buffers. I do web, desktop and mobile software development so the more portable the better. python >> from someAmazingDB import * >> db.taskList = [] >> db['taskList'].append({title:'Beat old sql interfaces','done':False}) >> db.taskList.append({title:'Illustrate different syntax modes','done':True}) #at this point it should autosave #we should be able to reload the console and access like: python >> from someAmazingDB import * >> print 'Done tasks' >> for task in db.taskList: >> if task.done: >> print task 'Illustrate different syntax modes' Here is the challenge: The above code should work with very little modification or thinking required. Like a different import statement and maybe a little more but Django Models and SQLAlchemy DO NOT CUT IT. I'm looking for more interesting library suggestions than just "Try Shelve" or "use pickle" I'm not opposed to Python classes being used for models but they should be really straight forward, unlike the stuff you see with Django and similar. A: I've was actually working on something like this earlier today. There is no readme or sufficient tests yet, but... http://github.com/mikeboers/LiteMap/blob/master/litemap.py The LiteMap class behaves much like the builtin dict, but it persists into a SQLite database. You did not indicate what particular database you were interested in, but this could be almost trivially modified to any back end. It also does not track changes to mutable classes (e.g. like appending to the list in your example), but the API is really simple. A: Database access doesn't get better than SQLAlchemy. A: Care to explain what about Django's models you don't find straightforward? Here's how I'd do what you have in Django: from django.db import models class Task(models.Model): title = models.CharField(max_length=...) is_done = models.BooleanField() def __unicode__(self): return self.title ---- from mysite.tasks.models import Task t = Task(title='Beat old sql interfaces', is_done=True) t.save() ---- from mysite.tasks.models import Task print 'Done tasks' for task in Task.objects.filter(is_done=True): print task Seems pretty straightforward to me! Also, results in a slightly cleaner table/object naming scheme IMO. The trickier part is using Django's DB module separate from the rest of Django, if that's what you're after, but it can be done. A: Using web2py: >>> from gluon.sql import DAL, Field >>> db=DAL('sqlite://stoarge.db') >>> db.define_table('taskList',Field('title'),Field('done','boolean')) # creates the table >>> db['taskList'].insert(title='Beat old sql interfaces',done=False) >>> db.taskList.insert(title='Beat old sql interfaces',done=False) >> for task in db(db.taskList.done==True).select(): >> print task.title Supports 10 different database back-ends + google app engine. A: Question looks strikingly similar to http://api.mongodb.org/python/1.9%2B/tutorial.html So answer is pymongo, what else ;) from pymongo import Connection connection = Connection() connection = Connection('localhost', 27017) tasklist = db['test-tasklist'] tasklist.append({title:'Beat old sql interfaces','done':False}) db.tasklist.append({title:'Illustrate different syntax modes','done':True}) for task in db.tasklist.find({done:True}): print task.title I haven't tested the code but wont be very different than this BTW Redish is also interesting and fun.
Simple / Smart, Pythonic database solution, can use Python types + syntax? (Key / Value Dict, Array, maybe Ordered Dict)
Looking for solutions that push the envelope and: Avoid Manually writing SQL queries(Python can be more OO not passing DSL strings) Using non-Python datatypes for a supposedly required model definition Using a new class of types rather than perfectly good native Python types Boast Using Python objects Using Object Oriented and key based retrieval and creation Quick protoyping No SQL table to make Model /Type inference or no model Less lines and characters to type Easily output to and from JSON, maybe XML or even Protocol Buffers. I do web, desktop and mobile software development so the more portable the better. python >> from someAmazingDB import * >> db.taskList = [] >> db['taskList'].append({title:'Beat old sql interfaces','done':False}) >> db.taskList.append({title:'Illustrate different syntax modes','done':True}) #at this point it should autosave #we should be able to reload the console and access like: python >> from someAmazingDB import * >> print 'Done tasks' >> for task in db.taskList: >> if task.done: >> print task 'Illustrate different syntax modes' Here is the challenge: The above code should work with very little modification or thinking required. Like a different import statement and maybe a little more but Django Models and SQLAlchemy DO NOT CUT IT. I'm looking for more interesting library suggestions than just "Try Shelve" or "use pickle" I'm not opposed to Python classes being used for models but they should be really straight forward, unlike the stuff you see with Django and similar.
[ "I've was actually working on something like this earlier today. There is no readme or sufficient tests yet, but... http://github.com/mikeboers/LiteMap/blob/master/litemap.py\nThe LiteMap class behaves much like the builtin dict, but it persists into a SQLite database. You did not indicate what particular database ...
[ 2, 1, 1, 1, 1 ]
[]
[]
[ "database", "nosql", "python" ]
stackoverflow_0002970382_database_nosql_python.txt
Q: Pylint doesn't handle imports when several projects have same base module name We've got a series of code projects in different parts of our source tree that all have a base package company_name, and some of them import functionality from eachother. This works just fine when running the code, setuptools and declare_namespace handle peicing together the modules. However, pylint doesn't seem to be feeling the mojo, so a large number of files have large high-prio errors Unable to import X from company_name. PYTHONPATH doesn't help, maybe some magic in pylints --init-hook=? Any hints and ideas super welcome! A: I have similar problem with import directory-based settings from many projects at once. My dirty solution is to make symlinks, each with different name (eg. projectA/settings -> projA_settings, projectB/settings -> projB_settings) and then use that import: import projA_settings or import projB_settings
Pylint doesn't handle imports when several projects have same base module name
We've got a series of code projects in different parts of our source tree that all have a base package company_name, and some of them import functionality from eachother. This works just fine when running the code, setuptools and declare_namespace handle peicing together the modules. However, pylint doesn't seem to be feeling the mojo, so a large number of files have large high-prio errors Unable to import X from company_name. PYTHONPATH doesn't help, maybe some magic in pylints --init-hook=? Any hints and ideas super welcome!
[ "I have similar problem with import directory-based settings from many projects at once.\nMy dirty solution is to make symlinks, each with different name (eg. projectA/settings -> projA_settings, projectB/settings -> projB_settings) and then use that import:\nimport projA_settings\n\nor\nimport projB_settings\n\n" ...
[ 0 ]
[]
[]
[ "import", "pylint", "python" ]
stackoverflow_0004087966_import_pylint_python.txt
Q: Combinatorics in Python I have a sort of a one level tree structure as: Where p are parent nodes, c are child nodes and b are hypothetical branches. I want to find all combinations of branches under the constraint that only one parent can branch to only one child node, and two branches can not share parent and/or child. E.g. if combo is the set of combinations: combo[0] = [b[0], b[3]] combo[1] = [b[0], b[4]] combo[2] = [b[1], b[4]] combo[3] = [b[2], b[3]] I think that's all of them. =) How can this be achived automaticly in Python for arbitrary trees of this structures i.e. the number of p:s, c:s and b:s are arbitrary. EDIT: It is not a tree but rather a bipartite directed acyclic graph A: Here's one way to do it. There are lot's of micro-optimizations that could be made but their efficacy would depend on the sizes involved. import collections as co import itertools as it def unique(list_): return len(set(list_)) == len(list_) def get_combos(branches): by_parent = co.defaultdict(list) for branch in branches: by_parent[branch.p].append(branch) combos = it.product(*by_parent.values()) return it.ifilter(lambda x: unique([b.c for b in x]), combos) I'm pretty sure that this is at least hitting optimal complexity as I don't see a way to avoid looking at every combination that is unique by parent. A: Look at itertools combinatoric generators: product() permutations() combinations() combinations_with_replacement() Looks like you can write an iterator to achieve what you want.
Combinatorics in Python
I have a sort of a one level tree structure as: Where p are parent nodes, c are child nodes and b are hypothetical branches. I want to find all combinations of branches under the constraint that only one parent can branch to only one child node, and two branches can not share parent and/or child. E.g. if combo is the set of combinations: combo[0] = [b[0], b[3]] combo[1] = [b[0], b[4]] combo[2] = [b[1], b[4]] combo[3] = [b[2], b[3]] I think that's all of them. =) How can this be achived automaticly in Python for arbitrary trees of this structures i.e. the number of p:s, c:s and b:s are arbitrary. EDIT: It is not a tree but rather a bipartite directed acyclic graph
[ "Here's one way to do it. There are lot's of micro-optimizations that could be made but their efficacy would depend on the sizes involved.\nimport collections as co\nimport itertools as it\n\ndef unique(list_):\n return len(set(list_)) == len(list_)\n\ndef get_combos(branches):\n by_parent = co.defaultdict(li...
[ 5, 4 ]
[]
[]
[ "bipartite", "combinatorics", "directed_acyclic_graphs", "python" ]
stackoverflow_0004095749_bipartite_combinatorics_directed_acyclic_graphs_python.txt
Q: How To Build a Template Engine I'll be building this in Google App Engine and I'll be Building it using Python. What I'd like to do is have a template that holds each section. With the sections probably being header, sidebar, content and footer. The way I would build it is so that I can call page.header(arg) and it will load the header that the arg specifies. I know there are a lot of frameworks, but I want to try and build a website based on the MVC idea my self. I figure it will probably take 6 months or more to build, but at least I'll learn something along the way. What else do I need to think about building a template engine? A: I would check out Webpy sources; webpy templating uses a syntax similar to yours, calling the views with something like: name = 'Bob' return render.index(name) where index is the templating file to render. Have a look to templating.py specifically.
How To Build a Template Engine
I'll be building this in Google App Engine and I'll be Building it using Python. What I'd like to do is have a template that holds each section. With the sections probably being header, sidebar, content and footer. The way I would build it is so that I can call page.header(arg) and it will load the header that the arg specifies. I know there are a lot of frameworks, but I want to try and build a website based on the MVC idea my self. I figure it will probably take 6 months or more to build, but at least I'll learn something along the way. What else do I need to think about building a template engine?
[ "I would check out Webpy sources;\nwebpy templating uses a syntax similar to yours, calling the views with something like:\nname = 'Bob' \nreturn render.index(name)\n\nwhere index is the templating file to render.\nHave a look to templating.py specifically.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "template_engine" ]
stackoverflow_0004092920_google_app_engine_python_template_engine.txt
Q: python: how to make threads wait for specific response? could anyone please provide on how to achieve below scenario ? 2 queues - destination queue, response queue thread picks task up from destination queue finds out needs more details submits new task to destination queue waits for his request to be processed and result appear in response queue or monitors response queue for response to his task but does not actually pick any response so it is available to the other threads waiting for other responses ? thank you A: If a threads waits for a specific task completion, i.e it shouldn't pick any completed task except that one it put, you can use locks to wait for the task: def run(self): # get a task, do somethings, put a new task newTask.waitFor() ... class Task: ... def waitFor(self): self._lock.acquire() def complete(self): self._lock.release() def failedToComplete(self, err): self._error = err self._lock.release() This will help to avoid time.sleep()-s on response queue monitoring. Task completion errors handling should be considered here. But this is uncommon approach. Is it some specific algorithm where the thread which puts a new task, should wait for it? Even so, you can implement that logic into a Task class, and not in the thread that processes it. And why the thread picks a task from the destination queue and puts a new task back to the destination queue? If you have n steps of processing, you can use n queues for it. A group of threads serves the first queue, gets a task, processes it, puts the result (a new task) to the next queue. The group of final response-handler threads gets a response and sends it back to the client. The tasks encapsulate details concerning themselves, the threads don't distinguish a task from another. And there is not need to wait for a particular task.
python: how to make threads wait for specific response?
could anyone please provide on how to achieve below scenario ? 2 queues - destination queue, response queue thread picks task up from destination queue finds out needs more details submits new task to destination queue waits for his request to be processed and result appear in response queue or monitors response queue for response to his task but does not actually pick any response so it is available to the other threads waiting for other responses ? thank you
[ "If a threads waits for a specific task completion, i.e it shouldn't pick any completed task except that one it put, you can use locks to wait for the task:\n\n def run(self):\n # get a task, do somethings, put a new task\n newTask.waitFor()\n ...\nclass Task:\n ...\n def waitFor(self):\n self._lock....
[ 1 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0004095925_multithreading_python_queue.txt
Q: adding a doRead() method to an existing socket object is there any way to add a doRead() method to an existing socket object? the socket needs a doRead method to be able to be passed to twisted's reactor via the addWriter method. i've tried using the new module's instance method but it doesn't seem to work... >>> c <socket._socketobject object at 0x7fcb03cc8b40> >>> c.doRead = new.instancemethod(doRead, c, socket._socketobject) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_socketobject' object has no attribute 'doRead' A: It's not new.instancemethod that's failing here. It's the fact that you have a socket._socketobject, an instance of an extension type, which doesn't have a __dict__ so cannot be given arbitrary new attributes. The typical way in which you make one kind of object look like another kind of object is to use wrapping. Create a new class that has all the methods you want and gets a reference to your socket. For example: class Connection: def __init__(self, socket, protocol): self.socket = socket self.protocol = protocol def doRead(self): try: data = self.socket.recv(self.bufferSize) except socket.error, se: if se.args[0] == EWOULDBLOCK: return else: return main.CONNECTION_LOST if not data: return main.CONNECTION_DONE return self.protocol.dataReceived(data) This is copied straight from Twisted, of course - it is the solution to exactly the problem you are trying to solve. :) Re-implementing the guts of Twisted might be a useful exercise to make sure you understand how all the pieces work and fit together, but when you get stuck, the Twisted source itself makes a pretty good reference to help you on your way.
adding a doRead() method to an existing socket object
is there any way to add a doRead() method to an existing socket object? the socket needs a doRead method to be able to be passed to twisted's reactor via the addWriter method. i've tried using the new module's instance method but it doesn't seem to work... >>> c <socket._socketobject object at 0x7fcb03cc8b40> >>> c.doRead = new.instancemethod(doRead, c, socket._socketobject) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_socketobject' object has no attribute 'doRead'
[ "It's not new.instancemethod that's failing here. It's the fact that you have a socket._socketobject, an instance of an extension type, which doesn't have a __dict__ so cannot be given arbitrary new attributes.\nThe typical way in which you make one kind of object look like another kind of object is to use wrappin...
[ 2 ]
[]
[]
[ "python", "sockets", "twisted" ]
stackoverflow_0004095473_python_sockets_twisted.txt
Q: django import with csvimport.py fails when trying to create a reference to a foreign key current django project is a mini shop thing. im trying to create the concept of having products which could have a foreign key of a Brand and a Category. however the import im using is this one http://djangosnippets.org/snippets/788/ and it fails when trying to create the object on the foreign key field. it puts the error message ValueError: Cannot assign "'Brand.dubkorps'": "Product.brand1" must be a "Brand" instance. I get that im not putting the right value in the csv file for the foreign key i'm trying to reference, my question is, how do i work out what the value is for this particular foreign key? love to hear from anyone who has done something similar with csvimport. A: if in the import file you have the ID of an existing brand you have two choiches: brand = Brand.objects.get(pk= csv_val) product.brand = brand or Product.brand_id = csv_val hope it helps
django import with csvimport.py fails when trying to create a reference to a foreign key
current django project is a mini shop thing. im trying to create the concept of having products which could have a foreign key of a Brand and a Category. however the import im using is this one http://djangosnippets.org/snippets/788/ and it fails when trying to create the object on the foreign key field. it puts the error message ValueError: Cannot assign "'Brand.dubkorps'": "Product.brand1" must be a "Brand" instance. I get that im not putting the right value in the csv file for the foreign key i'm trying to reference, my question is, how do i work out what the value is for this particular foreign key? love to hear from anyone who has done something similar with csvimport.
[ "if in the import file you have the ID of an existing brand you have two choiches:\nbrand = Brand.objects.get(pk= csv_val)\nproduct.brand = brand\n\nor \nProduct.brand_id = csv_val\n\nhope it helps\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004095616_django_python.txt
Q: Django is returning RuntimeError instead of 404 In my Django project I am having RUntimeError when I'm supposed to get a 404. The description says: Exception Value: maximum recursion depth exceeded The error only occurs when I try to access a non-existent page (the correct result would be a 404 page isn't it?). Is this a Django bug or is it my fault? I will provide more information if needed. EDIT: I have tried syncing the database (actually drop the database and sync it from scratch), restarting the server and even commenting out all the urlpatterns in all urls.py files. EDIT: This is what the traceback looks like: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 83. request.path_info) File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) And the last few lines are: File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 216. for pattern in self.url_patterns: File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in _get_url_patterns 245. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) A: I guess this is your fault :). I also had a RuntimeError yesteday. It was caused by giving the wrong class as argument of the super method when inheriting a ModelAdmin class. class MyAdmin(admin.ModelAdmin): def queryset(self, request): qs = super(AnotherAdmin, self).queryset(request) ... I've fixed by: class MyAdmin(admin.ModelAdmin): def queryset(self, request): qs = super(MyAdmin, self).queryset(request) ... I don't know if you have the same problem but it is something to check. I hope it helps A: try not loading all middleware modules, just comment them all in the settings and see if the problem is somewhere there.
Django is returning RuntimeError instead of 404
In my Django project I am having RUntimeError when I'm supposed to get a 404. The description says: Exception Value: maximum recursion depth exceeded The error only occurs when I try to access a non-existent page (the correct result would be a 404 page isn't it?). Is this a Django bug or is it my fault? I will provide more information if needed. EDIT: I have tried syncing the database (actually drop the database and sync it from scratch), restarting the server and even commenting out all the urlpatterns in all urls.py files. EDIT: This is what the traceback looks like: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 83. request.path_info) File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) And the last few lines are: File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve 216. for pattern in self.url_patterns: File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in _get_url_patterns 245. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
[ "I guess this is your fault :). I also had a RuntimeError yesteday. It was caused by giving the wrong class as argument of the super method when inheriting a ModelAdmin class.\nclass MyAdmin(admin.ModelAdmin):\n def queryset(self, request):\n qs = super(AnotherAdmin, self).queryset(request)\n ...\n...
[ 0, 0 ]
[]
[]
[ "django", "http_status_code_404", "python", "runtime_error" ]
stackoverflow_0004093541_django_http_status_code_404_python_runtime_error.txt
Q: What's the advantage of stack-less Python's microthread than Lua's coroutine in state machine implementation for game? Any advantage on stack-less python implentation than Lua's coroutine? What's the difference of them? A: stackless python and tasklets (I haven't done any programming with stackless python, but I have read some of the details about how it is implemented): Pros: Lightweight most of the time. Has scheduler to manage which tasklet get resume next after the current one yields. Support for Preemptive Scheduling. (i.e. run for X instructions) Channels for communication between tasklets. Cons: Sometimes need C-stack when yielding from a tasklet. (i.e. when yielding from some C callbacks) Lua 5.1 with plain coroutines: Pros: Lightweight. resume()/yield() functions allow consumer/producer model of communication. Cons: No built-in scheduler. You have to manage resuming & yielding coroutines. Can't yield from a C function, a metamethod, or an iterator. (Lua 5.2 will remove most of these restrictions, LuaJIT 1.1 provides lightweight c-stack switching to yield from anywhere) No built-in Preemptive Scheduling support. (would have to use debug hooks) Lua 5.1 with ConcurrentLua: Pros: Lightweight. Scheduler with cooperative context switching. Has Erlang style of message passing communication between tasks. Support for transparent distributed message passing between nodes. Cons: Can't yield from a C function, a metamethod, or an iterator. (again most of these restrictions go-away with Lua 5.2 and LuaJIT) No built-in Preemptive Scheduling support. (would have to use debug hooks) LuaJIT 2.0 Beta with ConcurrentLua: Pros: Lightweight. Scheduler with cooperative context switching. Has Erlang style of message passing communication between tasks. Support for transparent distributed message passing between nodes. Very fast JIT support makes Lua much faster then Python Cons: Might not be able to yield from a C function right now. This might be supported in future releases. No built-in Preemptive Scheduling support. (would have to use debug hooks)
What's the advantage of stack-less Python's microthread than Lua's coroutine in state machine implementation for game?
Any advantage on stack-less python implentation than Lua's coroutine? What's the difference of them?
[ "stackless python and tasklets (I haven't done any programming with stackless python, but I have read some of the details about how it is implemented):\nPros:\n\nLightweight most of the time.\nHas scheduler to manage which tasklet get resume next after the current one yields.\nSupport for Preemptive Scheduling. (i...
[ 9 ]
[]
[]
[ "coroutine", "lua", "python", "python_stackless", "stackless" ]
stackoverflow_0004064594_coroutine_lua_python_python_stackless_stackless.txt
Q: Where's the standard python exception list for programmes to raise? There is a list standard python exceptions that we should watch out, but I don't think these are the ones we should raise ourselves, cause they are rarely applicable. I'm curious if there exists a list within standard python library, with exceptions similar to .NET's ApplicationException, ArgumentNullException, ArgumentOutOfRangeException, InvalidOperationException — exceptions that we can raise ourselves? Or is there different, more pythonic way to handle common error cases, than raising standard exceptions? EDIT: I'm not asking on how to handle exceptions but what types I can and should raise where needed. A: If the error matches the description of one of the standard python exception classes, then by all means throw it. Common ones to use are TypeError and ValueError, the list you linked to already is the standard list. If you want to have application specific ones, then subclassing Exception or one of it's descendants is the way to go. To reference the examples you gave from .NET ApplicationException is closest to RuntimeError ArgumentNullException will probably be an AttributeError (try and call the method you want, let python raise the exception a la duck typing) AttributeOutOfRange is just a more specific ValueError InvalidOperationException could be any number of roughly equivalent exceptions form the python standard lib. Basically, pick one that reflects whatever error it is you're raising based on the descriptions from the http://docs.python.org/library/exceptions.html page. A: First, Python raises standard exceptions for you. It's better to ask forgiveness than to ask permission Simply attempt the operation and let Python raise the exception. Don't bracket everything with if would_not_work(): raise Exception. Never worth writing. Python already does this in all cases. If you think you need to raise a standard exception, you're probably writing too much code. You may have to raise ValueError. def someFunction( arg1 ): if arg1 <= 0.0: raise ValueError( "Guess Again." ) Once in a while, you might need to raise a TypeError, but it's rare. def someFunctionWithConstraints( arg1 ): if isinstance(arg1,float): raise TypeError( "Can't work with float and can't convert to int, either" ) etc. Second, you almost always want to create your own, unique exceptions. class MyException( Exception ): pass That's all it takes to create something distinctive and unique to your application. A: I seem to recall being trained by the documentation that it is ok to raise predefined exceptions, as long as they are appropriate. For example, the recommended way to terminate is no longer to call exit() but rather to raise SystemExit. Another example given is to reuse the IndexError exception on custom container types. Of course, your application should define its own exceptions rather than to actually repurpose system exceptions. I'm just saying there's no prohibition from reusing them where appropriate. A: The Pythonic way is just let the exceptions pass through from Python itself. For example, instead of: def foo(arg): if arg is None: raise SomeNoneException bar = arg.param Just do: def foo(arg): bar = arg.param If arg is None or doesn't have the param attribute, you will get an exception from Python itself. In the Python glossary this is called "EAFP": Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL (Look Before You Leap) style common to many other languages such as C. And it works well in tandem with Python's inherent duck typing philosophy. This doesn't mean you should not create exceptions of your own, of course, just that you don't need to wrap the already existing Python exceptions. For your own exceptions, create classes deriving from Exception and throw them when it's suitable.
Where's the standard python exception list for programmes to raise?
There is a list standard python exceptions that we should watch out, but I don't think these are the ones we should raise ourselves, cause they are rarely applicable. I'm curious if there exists a list within standard python library, with exceptions similar to .NET's ApplicationException, ArgumentNullException, ArgumentOutOfRangeException, InvalidOperationException — exceptions that we can raise ourselves? Or is there different, more pythonic way to handle common error cases, than raising standard exceptions? EDIT: I'm not asking on how to handle exceptions but what types I can and should raise where needed.
[ "If the error matches the description of one of the standard python exception classes, then by all means throw it.\nCommon ones to use are TypeError and ValueError, the list you linked to already is the standard list.\nIf you want to have application specific ones, then subclassing Exception or one of it's descenda...
[ 15, 14, 5, 2 ]
[]
[]
[ "error_handling", "exception", "python" ]
stackoverflow_0004096087_error_handling_exception_python.txt
Q: Python syntax and other things checking? I wrote a nice little script to do some lightweight work. I set it to run all night, and when I eagerly checked it this morning, I found that I had left a module name prefix out of one of its variables. Is there any way to check for this kind of chicanery statically? The trouble is that this thing sleeps a lot, so running it isn't the best way to find out. A: There are three most popular tools: pylint, pyflakes and pycheker. Pyflakes will show you unused imports, variables, variable usage before assignment, syntax errors and things like that. Pychecker, AFAIK is similar to pyflakes. Pylint, on the other hand, is a much more comprehensive tool: apart from the listed above, it also checks for PEP8 compatibility, variable names, docstrings, proper indentation, checks for maximum line and module length, number of local variables and class methods and so on. It gives a more or less complete report with a universal score of your code. However, because of the outstanding amount of errors it shows, without proper configuration it is quite tedious to use. A: PyLint PyChecker PyFlakes (if you use Emacs you can integrated it via Flymake)
Python syntax and other things checking?
I wrote a nice little script to do some lightweight work. I set it to run all night, and when I eagerly checked it this morning, I found that I had left a module name prefix out of one of its variables. Is there any way to check for this kind of chicanery statically? The trouble is that this thing sleeps a lot, so running it isn't the best way to find out.
[ "There are three most popular tools: pylint, pyflakes and pycheker.\nPyflakes will show you unused imports, variables, variable usage before assignment, syntax errors and things like that. Pychecker, AFAIK is similar to pyflakes.\nPylint, on the other hand, is a much more comprehensive tool: apart from the listed a...
[ 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004096751_python.txt
Q: operating on lists, find index, python I should find out an index of an item from a list of words. The function: def index(lst_words, word): should return the index of word in lst_words. e.g. >>> index (['how, 'to', 'find'], ['how']) shoud return 0 why this one doesn't work for me? def index (lst_words, word): find = lst_words.index(word) return find A: You probably meant ['how', 'to', 'find'].index('how'). NOT ['how', 'to', 'find'].index(['how']) This is not searching for a string, it's searching for a list. It would have matched ['how', 'to', 'find', ['how']].index(['how']) A: >>> def index(lst_words, word): find = lst_words.index(word) return find >>> x = ['hello', 'foo', 'bar'] >>> index(x, 'bar') 2 This is what you probably meant. When you want to find the position of bar, you pass bar as a string parameter, not a list. Cause the list you have, is a list of strings. The difference is: >>> x = ['bar'] >>> type(x) <type 'list'> >>> x = 'bar' >>> type(x) <type 'str'> So what you are trying to do, will work if the element within the list was another list. >>> x = ['hello', 'foo', ['bar']] >>> index(x, ['bar']) # since bar is a list not a string 2
operating on lists, find index, python
I should find out an index of an item from a list of words. The function: def index(lst_words, word): should return the index of word in lst_words. e.g. >>> index (['how, 'to', 'find'], ['how']) shoud return 0 why this one doesn't work for me? def index (lst_words, word): find = lst_words.index(word) return find
[ "You probably meant \n\n\n\n['how', 'to', 'find'].index('how').\n\n\n\nNOT \n\n\n\n['how', 'to', 'find'].index(['how'])\n\n\n\nThis is not searching for a string, it's searching for a list. It would have matched\n\n\n\n['how', 'to', 'find', ['how']].index(['how'])\n\n\n\n", ">>> def index(lst_words, word):\n ...
[ 3, 1 ]
[]
[]
[ "find", "indexing", "python" ]
stackoverflow_0004096964_find_indexing_python.txt
Q: How can I retrieve a single record from the Google App Engine Datastore? Using Google App Engine and GQL and Python: in my datastore I have something like the following class Thing(db.Model): domain = db.StringProperty(required=True) name = db.StringProperty() ...more... and in my handler I have currentThing = db.GqlQuery("SELECT * FROM Thing WHERE domain=:1 LIMIT 1", "example.com") I know this will at MOST return one Thing but I can't seem to find a way to collect that one thing in a Thing object without going through a looping process which seems a bit odd to me. I've also tried using the Thing.gql("WHERE domain=:1 LIMIT 1", "example.com") syntax to no avail. They all seem to return collections. I'm coming from a .NET background and am new to Python and App Engine, but I'm looking for something similar to the .FirstOrDefault() functionality. A: Just add a .get() onto the end of either of your queries. From the docs: Executes the query, then returns the first result, or None if the query returned no results. get() implies a "limit" of 1, and overrides the LIMIT clause of the GQL query, if any. At most 1 result is fetched from the datastore. See also .fetch(limit, offset=0), which will allow you to retrieve limit results from the query.
How can I retrieve a single record from the Google App Engine Datastore?
Using Google App Engine and GQL and Python: in my datastore I have something like the following class Thing(db.Model): domain = db.StringProperty(required=True) name = db.StringProperty() ...more... and in my handler I have currentThing = db.GqlQuery("SELECT * FROM Thing WHERE domain=:1 LIMIT 1", "example.com") I know this will at MOST return one Thing but I can't seem to find a way to collect that one thing in a Thing object without going through a looping process which seems a bit odd to me. I've also tried using the Thing.gql("WHERE domain=:1 LIMIT 1", "example.com") syntax to no avail. They all seem to return collections. I'm coming from a .NET background and am new to Python and App Engine, but I'm looking for something similar to the .FirstOrDefault() functionality.
[ "Just add a .get() onto the end of either of your queries. From the docs:\n\nExecutes the query, then returns the first result, or None if the query returned no results.\nget() implies a \"limit\" of 1, and overrides the LIMIT clause of the GQL query, if any. At most 1 result is fetched from the datastore.\n\nSee ...
[ 7 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004096948_google_app_engine_python.txt
Q: Python equivalent to Java's Class.getResource I have some XML files on my PYTHONPATH that I would like to load using their path on the PYTHONPATH, rather than their (relative or absolute) path on the filesystem. I could simply inline them as strings in a Python module (yay multiline string literals), and then load them using a regular import statement, but I'd like to keep them separated out as regular XML files, if possible. In Java world, the solution to this would be to use the Class.getResource method, and I'm wondering if something similar exists in Python. A: Take a look at pkg_resources, it includes apis for the inclusion to generic resources. It is thought to work with python eggs and so it could be much more of you need. Just an example taken from the doc: import pkg_resources my_data = pkg_resources.resource_string(__name__, "foo.dat") A: I don't know of anything built-in, but something like the following should emulate the behavior (assuming the files are on a local disk -- I don't believe that PYTHONPATH support non-local file paths, whereas the Java classpath can contain URLs to remote resources). def get_pypath_resource(resource_name): for path in sys.path: if os.path.exists(os.path.join(path, resource_name)): return os.path.join(path, resource_name) raise Exception('Resource %s could not be found' % resource_name)
Python equivalent to Java's Class.getResource
I have some XML files on my PYTHONPATH that I would like to load using their path on the PYTHONPATH, rather than their (relative or absolute) path on the filesystem. I could simply inline them as strings in a Python module (yay multiline string literals), and then load them using a regular import statement, but I'd like to keep them separated out as regular XML files, if possible. In Java world, the solution to this would be to use the Class.getResource method, and I'm wondering if something similar exists in Python.
[ "Take a look at pkg_resources, it includes apis for the inclusion to generic resources. It is thought to work with python eggs and so it could be much more of you need.\nJust an example taken from the doc:\nimport pkg_resources\nmy_data = pkg_resources.resource_string(__name__, \"foo.dat\")\n\n", "I don't know of...
[ 8, 7 ]
[]
[]
[ "java", "module", "python", "resources", "xml" ]
stackoverflow_0004096770_java_module_python_resources_xml.txt
Q: sending random data with Twisted I'm trying to create an application that maxes out the user's downstream by continuously sending data. Is there a variable that tells how many bytes are in the out buffer? And I say "out buffer," but is there a better term for the data that is being buffered before its sent to the client? Am I going about this the right way? It doesn't seem practical to self.transport.write() 100 megabytes. A: The way Twisted exposes this information is with a pair of APIs commonly referred to as "producers" and "consumers". You can find a document about them on the Twisted site. In your case, a "pull producer" is probably appropriate, since your random data probably isn't coming from an event source, but can be generated on demand. A rough sketch might look something like this (and hopefully the above linked document will explain why this works): from os import urandom from zope.interface import implements from twisted.internet.interfaces import IPullProducer class RandomProducer(object): implements(IPullProducer) def __init__(self, consumer): self.consumer = consumer def resumeProducing(self): self.consumer.write(urandom(2 ** 16)) def stopProducing(self): pass So, for example, when a connection is set up, you can register this producer with the transport: from twisted.internet.protocol import Protocol class RandomProtocol(Protocol): def connectionMade(self): self.transport.registerProducer(RandomProducer(self.transport), False) This will send random data at the client as fast as possible.
sending random data with Twisted
I'm trying to create an application that maxes out the user's downstream by continuously sending data. Is there a variable that tells how many bytes are in the out buffer? And I say "out buffer," but is there a better term for the data that is being buffered before its sent to the client? Am I going about this the right way? It doesn't seem practical to self.transport.write() 100 megabytes.
[ "The way Twisted exposes this information is with a pair of APIs commonly referred to as \"producers\" and \"consumers\". You can find a document about them on the Twisted site.\nIn your case, a \"pull producer\" is probably appropriate, since your random data probably isn't coming from an event source, but can be...
[ 2 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0004096836_python_twisted.txt
Q: Python networkx DFS or BFS missing? I am interested in finding a path (not necessarily shortest) in a short amount of time. Dijsktra and AStar in networkx is taking too long. Why is there no DFS or BFS in networkx? I plan to write my own DFS and BFS search (I am leaning more towards BFS because my graph is pretty deep). Is there anything that I can use in networkx's lib to speed me up? A: The Traversal module has multiple depth-first-search variations. Breadth-first-search is implemented in the connected components functions, also in that module. Either use that, or if you need custom behaviour, re-implement your own using that as the example. A: There is now a depth-first search and breadth-first search here These are modified from Eppstein's code at www.ics.uci.edu/~eppstein/PADS which is also a good place to look for Python graph algorithms.
Python networkx DFS or BFS missing?
I am interested in finding a path (not necessarily shortest) in a short amount of time. Dijsktra and AStar in networkx is taking too long. Why is there no DFS or BFS in networkx? I plan to write my own DFS and BFS search (I am leaning more towards BFS because my graph is pretty deep). Is there anything that I can use in networkx's lib to speed me up?
[ "The Traversal module has multiple depth-first-search variations. Breadth-first-search is implemented in the connected components functions, also in that module. Either use that, or if you need custom behaviour, re-implement your own using that as the example.\n", "There is now a depth-first search and breadth-fi...
[ 4, 4 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0002449382_networkx_python.txt
Q: How can I take an image and get a 3x2 ratio image cropped from the center? Is there an easy way to do this? In Python, I created a script to get a "square box" from an image...based on the center. However, that killed some of my brain cells. Is there an easy way to do this for a 3x2 (3 width, 2 height), based on the center? This is my "square box" script, but I don't feel like modifying it for the 3x2. def letterbox(f,thumb_w=None,thumb_h=None): try: im = Image.open(StringIO(f)) imagex = int(im.size[0]) imagey = int(im.size[1]) thumb_size = (thumb_w,thumb_h) #what if it is too small!?? fix it. if imagex > imagey: setlen = imagey left = (imagex - setlen)/2 top = 0 height = setlen width = setlen if imagey > imagex: setlen = imagex left = 0 top = (imagey - setlen)/2 heigth = setlen width = setlen if imagex == imagey: left = 0 top = 0 height = imagey width = imagex box = (left,top,left+width,top+height) im = im.crop(box) #im.thumbnail(thumb_size,Image.ANTIALIAS) new_file = StringIO() im.save(new_file,'JPEG') new_file.seek(0) except Exception, e: pass return new_file Is there a script online that can do what I need? A: Use an aspect ratio which is defined as imagex/imagey, so you use 3/2 for 3:2, 16/9 for 16:9 etc. def letterbox(f,aspect_ratio=1): try: im = Image.open(StringIO(f)) imagex = int(im.size[0]) imagey = int(im.size[1]) width = min(imagex, imagey*aspect_ratio) height = min(imagex/aspect_ratio, imagey) left =(imagex - width)/2 top = (imagey - height)/2 box = (left,top,left+width,top+height) im = im.crop(box) new_file = StringIO() im.save(new_file,'JPEG') new_file.seek(0) except Exception, e: pass return new_file You might want to check for roundoff errors at some point, but otherwise this does it. A: First of all, the name of your function is misleading because what it does is not letterbox images (regardless of the specific height/width [aspect ratio] involved) -- so here it's been renamed aspectcrop() to better describe what it does. def aspectcrop(f, ratio=1.0): try: im = Image.open(StringIO(f)) imagewidth,imageheight = im.size # determine the dimensions of a crop area # which is no wider or taller than the image if int(imagewidth*ratio) > imageheight: cropheight,cropwidth = imageheight,int(imageheight/ratio) else: cropwidth,cropheight = imagewidth,int(imagewidth*ratio) # center the crop area on the image (dx and/or dy will be zero) dx,dy = (imagewidth-cropwidth)/2,(imageheight-cropheight)/2 # crop, save, and return image data im = im.crop((dx,dy,cropwidth+dx,cropheight+dy)) new_file = StringIO() im.save(new_file,'JPEG') new_file.seek(0) except Exception, e: new_file = None # prevent exception on return pass return new_file If any aspect ratio argument you pass to it is not naturally a whole number, make sure it's in floating point, as in 3./2. not 3/2. The default (1.0) could have been integer, but I explicitly made it floating point as a reminder. It might be better to pass it in as two separate integers and compute the ratio internally. Lastly, I noticed that your example script had some visible traces of what looks like an attempt to create a thumbnail of the image, so my answer to the related question What's the simplest way in Python to resize an image to a given bounded area? might also be of interest (and could probably be integrated into this function without too much trouble).
How can I take an image and get a 3x2 ratio image cropped from the center?
Is there an easy way to do this? In Python, I created a script to get a "square box" from an image...based on the center. However, that killed some of my brain cells. Is there an easy way to do this for a 3x2 (3 width, 2 height), based on the center? This is my "square box" script, but I don't feel like modifying it for the 3x2. def letterbox(f,thumb_w=None,thumb_h=None): try: im = Image.open(StringIO(f)) imagex = int(im.size[0]) imagey = int(im.size[1]) thumb_size = (thumb_w,thumb_h) #what if it is too small!?? fix it. if imagex > imagey: setlen = imagey left = (imagex - setlen)/2 top = 0 height = setlen width = setlen if imagey > imagex: setlen = imagex left = 0 top = (imagey - setlen)/2 heigth = setlen width = setlen if imagex == imagey: left = 0 top = 0 height = imagey width = imagex box = (left,top,left+width,top+height) im = im.crop(box) #im.thumbnail(thumb_size,Image.ANTIALIAS) new_file = StringIO() im.save(new_file,'JPEG') new_file.seek(0) except Exception, e: pass return new_file Is there a script online that can do what I need?
[ "Use an aspect ratio which is defined as imagex/imagey, so you use 3/2 for 3:2, 16/9 for 16:9 etc.\ndef letterbox(f,aspect_ratio=1):\n try:\n im = Image.open(StringIO(f))\n imagex = int(im.size[0])\n imagey = int(im.size[1])\n width = min(imagex, imagey*aspect_ratio)\n height =...
[ 2, 0 ]
[]
[]
[ "algorithm", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0004094744_algorithm_image_processing_python_python_imaging_library.txt
Q: How to find links with all uppercase text using Python (without a 3rd party parser)? I am using BeautifulSoup in a simple function to extract links that have all uppercase text: def findAllCapsUrls(page_contents): """ given HTML, returns a list of URLs that have ALL CAPS text """ soup = BeautifulSoup.BeautifulSoup(page_contents) all_urls = node_with_links.findAll(name='a') # if the text for the link is ALL CAPS then add the link to good_urls good_urls = [] for url in all_urls: text = url.find(text=True) if text.upper() == text: good_urls.append(url['href']) return good_urls Works well most of the time, but a handful of pages will not parse correctly in BeautifulSoup (or lxml, which I also tried) due to malformed HTML on the page, resulting in an object with no (or only some) links in it. A "handful" might sound like not-a-big-deal, but this function is being used in a crawler so there could be hundreds of pages that the crawler will never find... How can the above function be refactored to not use a parser like BeautifulSoup? I've searched around for how to do this using regex, but all the answers say "use BeautifulSoup." Alternatively, I started looking at how to "fix" the malformed HTML so that is parses, but I don't think that is the best route... What is an alternative solution, using re or something else, that can do the same as the function above? A: If the html pages are malformed, there is not a lot of solutions that can really help you. BeautifulSoup or other parsing library are the way to go to parse html files. If you want to avoir the library path, you could use a regexp to match all your links see regular-expression-to-extract-url-from-an-html-link using a range of [A-Z] A: When I need to parse a really broken html and speed is not the most important factor I automate a browser with selenium & webdriver. This is the most resistant way of html parsing I know. Check this tutorial it shows how to extract google suggestion using webdriver (the code is in java but it can be changed to python). A: I ended up with a combination of regex and BeautifulSoup: def findAllCapsUrls2(page_contents): """ returns a list of URLs that have ALL CAPS text, given the HTML from a page. Uses a combo of RE and BeautifulSoup to handle malformed pages. """ # get all anchors on page using regex p = r'<a\s+href\s*=\s*"([^"]*)"[^>]*>(.*?(?=</a>))</a>' re_urls = re.compile(p, re.DOTALL) all_a = re_urls.findall(page_contents) # if the text for the anchor is ALL CAPS then add the link to good_urls good_urls = [] for a in all_a: href = a[0] a_content = a[1] a_soup = BeautifulSoup.BeautifulSoup(a_content) text = ''.join([s.strip() for s in a_soup.findAll(text=True) if s]) if text and text.upper() == text: good_urls.append(href) return good_urls This is working for my use cases so far, but I wouldn't guarantee it to work on all pages. Also, I only use this function if the original one fails.
How to find links with all uppercase text using Python (without a 3rd party parser)?
I am using BeautifulSoup in a simple function to extract links that have all uppercase text: def findAllCapsUrls(page_contents): """ given HTML, returns a list of URLs that have ALL CAPS text """ soup = BeautifulSoup.BeautifulSoup(page_contents) all_urls = node_with_links.findAll(name='a') # if the text for the link is ALL CAPS then add the link to good_urls good_urls = [] for url in all_urls: text = url.find(text=True) if text.upper() == text: good_urls.append(url['href']) return good_urls Works well most of the time, but a handful of pages will not parse correctly in BeautifulSoup (or lxml, which I also tried) due to malformed HTML on the page, resulting in an object with no (or only some) links in it. A "handful" might sound like not-a-big-deal, but this function is being used in a crawler so there could be hundreds of pages that the crawler will never find... How can the above function be refactored to not use a parser like BeautifulSoup? I've searched around for how to do this using regex, but all the answers say "use BeautifulSoup." Alternatively, I started looking at how to "fix" the malformed HTML so that is parses, but I don't think that is the best route... What is an alternative solution, using re or something else, that can do the same as the function above?
[ "If the html pages are malformed, there is not a lot of solutions that can really help you. BeautifulSoup or other parsing library are the way to go to parse html files. \nIf you want to avoir the library path, you could use a regexp to match all your links see regular-expression-to-extract-url-from-an-html-link us...
[ 2, 1, 0 ]
[]
[]
[ "html", "parsing", "python" ]
stackoverflow_0004097095_html_parsing_python.txt
Q: How to change edges' weight by designated rule? I have a weighted graph: F=nx.path_graph(10) G=nx.Graph() for (u, v) in F.edges(): G.add_edge(u,v,weight=1) Get the nodes list: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)] I want to change each edge's weight by this rule: Remove one node, such as node 5, clearly, edge (4, 5), and (5, 6) will be delete, and the weight of each edge will turn to: {# these edges are nearby the deleted edge (4, 5) and (5, 6) (3,4):'weight'=1.1, (6,7):'weight'=1.1, #these edges are nearby the edges above mentioned (2,3):'weight'=1.2, (7,8):'weight'=1.2, #these edges are nearby the edges above mentioned (1,2):'weight'=1.3, (8,9):'weight'=1.3, # this edge is nearby (1,2) (0,1):'weight'=1.4} How to write this algorithm? path_graph is just an example. I need a program to suit any graph type. Furthermore, the program need to be iterable, it means I can remove one node from the origin graph each time. A: You can access the edge weight as G[u][v]['weight'] or by iterating over the edge data. So you can e.g. In [1]: import networkx as nx In [2]: G=nx.DiGraph() In [3]: G.add_edge(1,2,weight=10) In [4]: G.add_edge(2,3,weight=20) In [5]: G[2][3]['weight'] Out[5]: 20 In [6]: G[2][3]['weight']=200 In [7]: G[2][3]['weight'] Out[7]: 200 In [8]: G.edges(data=True) Out[8]: [(1, 2, {'weight': 10}), (2, 3, {'weight': 200})] In [9]: for u,v,d in G.edges(data=True): ...: d['weight']+=7 ...: ...: In [10]: G.edges(data=True) Out[10]: [(1, 2, {'weight': 17}), (2, 3, {'weight': 207})]
How to change edges' weight by designated rule?
I have a weighted graph: F=nx.path_graph(10) G=nx.Graph() for (u, v) in F.edges(): G.add_edge(u,v,weight=1) Get the nodes list: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)] I want to change each edge's weight by this rule: Remove one node, such as node 5, clearly, edge (4, 5), and (5, 6) will be delete, and the weight of each edge will turn to: {# these edges are nearby the deleted edge (4, 5) and (5, 6) (3,4):'weight'=1.1, (6,7):'weight'=1.1, #these edges are nearby the edges above mentioned (2,3):'weight'=1.2, (7,8):'weight'=1.2, #these edges are nearby the edges above mentioned (1,2):'weight'=1.3, (8,9):'weight'=1.3, # this edge is nearby (1,2) (0,1):'weight'=1.4} How to write this algorithm? path_graph is just an example. I need a program to suit any graph type. Furthermore, the program need to be iterable, it means I can remove one node from the origin graph each time.
[ "You can access the edge weight as G[u][v]['weight'] or by iterating over the edge data. So you can e.g.\nIn [1]: import networkx as nx\n\nIn [2]: G=nx.DiGraph()\n\nIn [3]: G.add_edge(1,2,weight=10)\n\nIn [4]: G.add_edge(2,3,weight=20)\n\nIn [5]: G[2][3]['weight']\nOut[5]: 20\n\nIn [6]: G[2][3]['weight']=200\n\nIn...
[ 36 ]
[]
[]
[ "algorithm", "edge_list", "networkx", "python" ]
stackoverflow_0003965360_algorithm_edge_list_networkx_python.txt
Q: Fibers in Python I'm looking for a very simple way to implement fibers in Python. I'm sure there's a really simple way to do it using generators, but my mind is crapping out on me. This isn't for a huge application, so I don't need the fanciness (or the overhead) of something like Diesel or Tornado or Twisted, I just want a neat little way to do fibers. Any ideas/suggestions? A: Google around for Python coroutines. There's a lot of stuff out there with varying levels of complexity. A: I've discovered that Greenlets do pretty much exactly what I've been looking to do. Sweet!
Fibers in Python
I'm looking for a very simple way to implement fibers in Python. I'm sure there's a really simple way to do it using generators, but my mind is crapping out on me. This isn't for a huge application, so I don't need the fanciness (or the overhead) of something like Diesel or Tornado or Twisted, I just want a neat little way to do fibers. Any ideas/suggestions?
[ "Google around for Python coroutines. There's a lot of stuff out there with varying levels of complexity.\n", "I've discovered that Greenlets do pretty much exactly what I've been looking to do. Sweet!\n" ]
[ 0, 0 ]
[]
[]
[ "fibers", "generator", "python" ]
stackoverflow_0004029236_fibers_generator_python.txt
Q: Odd error when helping a friend install apsw First off, I don't know if this goes on stackoverflow or one of the other related sites. So, I have apsw on my system, and am using python 2.6 32 bit. My friend is using Python 64 bit, and when I tried to install apsw on his system, we got a multitude of errors, depending on how we installed it. First off, installing via exe gave us a "This application is not a valid win32 program" When we manually installed it from my system, we got a "ImportError: DLL load failed: %1 is not a valid Win32 application." And we have some complications with building the module too with sqlite3.dll and sqlite3.lib. A: Disclosure: I am the APSW author The APSW web site includes an entire page listing reasons why you'd use APSW over pysqlite. Also note that the pysqlite included in the standard library is even older than current pysqlite code. Currently I only provide compiled Windows APSW extensions for 32 bit Pythons. You can run 32 and 64 bit Python on 64 bit Windows if you install them to different directories. However the bitness of extensions must match the bitness of the Python you are using it with. Your short term solution is to also install 32 bit Python on the 64 bit machine. Alternatively you can compile a 64 bit extension yourself. In theory this is as simple as installing Visual Studio 2008 Express from http://www.microsoft.com/express/Downloads/#2008-All (note use 2008 version not 2010 version), downloading the APSW source zip from http://code.google.com/p/apsw/downloads/list and then running python setup.py fetch --all build --enable-all-extensions install Edit (2010-Nov-07) If you have Visual Studio 2008 Professional installed then that should just work. Express did not include the 64 bit compilers originally although they are now included but Python's distutils and most of the rest of VS 2008 doesn't know about them. Email me if you want to do the build yourself and I'll give more detailed information. The next APSW release will include Windows 64 bit binaries for Python 2.6 and above including the Python 3 series. Edit (2010-Dec-15) APSW 3.7.4-r1 now includes official 64 bit Windows binary downloads over at http://code.google.com/p/apsw/downloads/list A: 32-bit and 64-bit binaries are different animals, and can be mixed only if you know what you are doing. Did you try installing python 2.6 32-bit on your friend's machine? Why are you using apsw instead of the standard library sqlite3?
Odd error when helping a friend install apsw
First off, I don't know if this goes on stackoverflow or one of the other related sites. So, I have apsw on my system, and am using python 2.6 32 bit. My friend is using Python 64 bit, and when I tried to install apsw on his system, we got a multitude of errors, depending on how we installed it. First off, installing via exe gave us a "This application is not a valid win32 program" When we manually installed it from my system, we got a "ImportError: DLL load failed: %1 is not a valid Win32 application." And we have some complications with building the module too with sqlite3.dll and sqlite3.lib.
[ "Disclosure: I am the APSW author\nThe APSW web site includes an entire page listing reasons why you'd use APSW over pysqlite. Also note that the pysqlite included in the standard library is even older than current pysqlite code.\nCurrently I only provide compiled Windows APSW extensions for 32 bit Pythons. You c...
[ 5, 2 ]
[]
[]
[ "installation", "module", "python" ]
stackoverflow_0004093447_installation_module_python.txt
Q: How do I loop through a large dataset in python without getting a MemoryError? I have a large series of raster datasets representing monthly rainfall over several decades. I've written a script in Python that loops over each raster and does the following: Converts the raster to a numpy masked array, Performs lots of array algebra to calculate a new water level, Writes the result to an output raster. Repeats The script is just a long list of array algebra equations enclosed by a loop statement. Everything works well if I just run the script on a small part of my data (say 20 years' worth), but if I try to process the whole lot I get a MemoryError. The error doesn't give any more information than that (except it highlights the line in the code at which Python gave up). Unfortunately, I can't easily process my data in chunks - I really need to be able to do the whole lot at once. This is because, at the end of each iteration, the output (water level) is fed back into the next iteration as the start point. My understanding of programming is very basic at present, but I thought that all of my objects would just be overwritten on each loop. I (stupidly?) assumed that if the code managed to loop successfully once then it should be able to loop indefinitely without using up more and more memory. I've tried reading various bits of documentation and have discovered something called the "Garbage Collector", but I feel like I'm getting out of my depth and my brain's melting! Can anyone offer some basic insight into what actually happens to objects in memory when my code loops? Is there a way of freeing-up memory at the end of each loop, or is there some more "Pythonic" way of coding which avoids this problem altogether? A: You don't need to concern youself with memory management, especially not with the garbage collector that has a very specific task that you most likely don't even use. Python will always collect the memory it can and reuse it. There are just two reasons for your problem: Either the data you try to load is too much to fit into memory or your calculations store data somewhere (a list, dict, something persistent between iterations) and that storage grows and grows. Memory profilers can help finding that. A: a quick way to "force" the garbage collector to clean the temporary loop-only objects is the del statement: for obj in list_of_obj: data = obj.getData() do_stuff(data) del data this forces the interpreter to delete and free the temporary objects. NOTE: this does not make sure the program does not leak or consume memory in other parts of the computation, it's just a quick check
How do I loop through a large dataset in python without getting a MemoryError?
I have a large series of raster datasets representing monthly rainfall over several decades. I've written a script in Python that loops over each raster and does the following: Converts the raster to a numpy masked array, Performs lots of array algebra to calculate a new water level, Writes the result to an output raster. Repeats The script is just a long list of array algebra equations enclosed by a loop statement. Everything works well if I just run the script on a small part of my data (say 20 years' worth), but if I try to process the whole lot I get a MemoryError. The error doesn't give any more information than that (except it highlights the line in the code at which Python gave up). Unfortunately, I can't easily process my data in chunks - I really need to be able to do the whole lot at once. This is because, at the end of each iteration, the output (water level) is fed back into the next iteration as the start point. My understanding of programming is very basic at present, but I thought that all of my objects would just be overwritten on each loop. I (stupidly?) assumed that if the code managed to loop successfully once then it should be able to loop indefinitely without using up more and more memory. I've tried reading various bits of documentation and have discovered something called the "Garbage Collector", but I feel like I'm getting out of my depth and my brain's melting! Can anyone offer some basic insight into what actually happens to objects in memory when my code loops? Is there a way of freeing-up memory at the end of each loop, or is there some more "Pythonic" way of coding which avoids this problem altogether?
[ "You don't need to concern youself with memory management, especially not with the garbage collector that has a very specific task that you most likely don't even use. Python will always collect the memory it can and reuse it.\nThere are just two reasons for your problem: Either the data you try to load is too much...
[ 5, 4 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0004098162_memory_python.txt
Q: Python SQLite3 Problem with? Im currently learning SQLite3 with Python. I'm looking at the manual, and it tells me to do something like the following: data = (tablename, ) c.execute("CREATE TABLE IF NOT EXISTS ?(uid INTEGER PRIMARY KEY, title TEXT NOT NULL, duedate INTEGER NOT NULL, description TEXT, archived INTEGER)", data) I'm getting an error, however. It's stated as follows: sqlite3.OperationalError: near "?": syntax error What's going on? A: sadly the DB-API’s parameter substitution ? don't work with table name , columns name .. and it's the same in all DB API in python. the DB-API’s parameter substitution just work for value like in SELECT * FROM table WHERE id = ?, so you will have to do string formating or just put the name table in the string directly. query = "CREATE TABLE IF NOT EXISTS %s (uid INTEGER PRIMARY KEY, title TEXT NOT NULL, duedate INTEGER NOT NULL, description TEXT, archived INTEGER)" % table_name conn.execute(query)
Python SQLite3 Problem with?
Im currently learning SQLite3 with Python. I'm looking at the manual, and it tells me to do something like the following: data = (tablename, ) c.execute("CREATE TABLE IF NOT EXISTS ?(uid INTEGER PRIMARY KEY, title TEXT NOT NULL, duedate INTEGER NOT NULL, description TEXT, archived INTEGER)", data) I'm getting an error, however. It's stated as follows: sqlite3.OperationalError: near "?": syntax error What's going on?
[ "sadly the DB-API’s parameter substitution ? don't work with table name , columns name .. and it's the same in all DB API in python.\nthe DB-API’s parameter substitution just work for value like in SELECT * FROM table WHERE id = ?, so you will have to do string formating or just put the name table in the string dir...
[ 3 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0004098197_python_sql_sqlite.txt
Q: Google App Engine gives spurious content at beginning of page after quiescent period I'm developing an app in Python for Google App Engine. When I run the deployed app from appspot, it works fine unless I'm accessing it for the first time in over, say, 5 minutes. The problem is that if I haven't accessed the app for a while, the page renders with the message Status: 200 OK Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Expires: Fri, 01 Jan 1990 00:00:00 GMT Content-Length: 15493 prepended at the top. Usually that text is displayed for a second or two before the rest of the page is displayed. If I check the server Logs, I see the info message This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. The problem is easily corrected by refreshing the page. In this case, the page is delivered correctly, and works for subsequent refreshes. But if I wait 5 minutes, the problem comes back. Any explanations, or suggestions on how to troubleshoot this? I've got a vague notion that when GAE "wakes up" after being inactive, there is an incorrect initialization going on. Or perhaps a header from a previous bout of activity is lingering in a buffer somewhere. But self.response.out seems to be empty when the request handler is invoked. A: Somewhere in your top level module code is something that uses Python print statements. Print outputs to standard out, which is what is returned as the response body; if it outputs a pair of newlines, the content before that is treated by the browser as the response header. The 'junk' you're seeing is the real response headers being produced by your webapp. It's only happening on startup requests, because that's the only time the code in question gets executed.
Google App Engine gives spurious content at beginning of page after quiescent period
I'm developing an app in Python for Google App Engine. When I run the deployed app from appspot, it works fine unless I'm accessing it for the first time in over, say, 5 minutes. The problem is that if I haven't accessed the app for a while, the page renders with the message Status: 200 OK Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Expires: Fri, 01 Jan 1990 00:00:00 GMT Content-Length: 15493 prepended at the top. Usually that text is displayed for a second or two before the rest of the page is displayed. If I check the server Logs, I see the info message This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. The problem is easily corrected by refreshing the page. In this case, the page is delivered correctly, and works for subsequent refreshes. But if I wait 5 minutes, the problem comes back. Any explanations, or suggestions on how to troubleshoot this? I've got a vague notion that when GAE "wakes up" after being inactive, there is an incorrect initialization going on. Or perhaps a header from a previous bout of activity is lingering in a buffer somewhere. But self.response.out seems to be empty when the request handler is invoked.
[ "Somewhere in your top level module code is something that uses Python print statements. Print outputs to standard out, which is what is returned as the response body; if it outputs a pair of newlines, the content before that is treated by the browser as the response header. The 'junk' you're seeing is the real res...
[ 6 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004098119_google_app_engine_python.txt
Q: get list item which have count more than specific number by Python I have nested list : ip[0] = ['23:30:42.476071', '55729', '192.168.98.138.49341', '201.20.49.239.80', '562034568', -1] ip[1] = ['23:30:43.110194', '20442', '201.20.49.239.80', '192.168.98.138.49341', '364925831', '562034569'] ip[2] = ['23:30:43.110290', '55730', '192.168.98.138.49341', '201.20.49.239.80', -1, '5840'] ip[3] = ['23:30:43.170344', '55731', '192.168.98.138.49341', '201.20.49.239.80', '562034569:562034972', '364925832'] ip[4] = ['23:30:43.170918', '20443', '201.20.49.239.80', '192.168.98.138.49341', -1, '64240'] ip[5] = ['23:30:44.022511', '20444', '201.20.49.239.80', '192.168.98.138.49341', '364925832:364925978', '562034972'] I want get index and sublist from my original list that have ip[i][2] = 192.168.98.138 for the above list I want get : ip[0] = ['23:30:42.476071', '55729', '192.168.98.138.49341', '201.20.49.239.80', '562034568', -1] ip[2] = ['23:30:43.110290', '55730', '192.168.98.138.49341', '201.20.49.239.80', -1, '5840'] ip[3] = ['23:30:43.170344', '55731', '192.168.98.138.49341', '201.20.49.239.80', '562034569:562034972', '364925832'] A: Thanks for clarifying. Use a list comprehension: >>> ip = [['23:30:42.476071', '55729', '192.168.98.138.49341', '201.20.49.239.80', '562034568', -1], ['23:30:43.110194', '20442', '201.20.49.239.80', '192.168.98.138.49341', '364925831', '562034569'], ['23:30:43.110290', '55730', '192.168.98.138.49341', '201.20.49.239.80', -1, '5840'], ['23:30:43.170344', '55731', '192.168.98.138.49341', '201.20.49.239.80', '562034569:562034972', '364925832'], ['23:30:43.170918', '20443', '201.20.49.239.80', '192.168.98.138.49341', -1, '64240'], ['23:30:44.022511', '20444', '201.20.49.239.80', '192.168.98.138.49341', '364925832:364925978', '562034972']] >>> needle = ip[0][2] >>> [item for item in ip if item[2]==needle] [['23:30:42.476071', '55729', '192.168.98.138.49341', '201.20.49.239.80', '562034568', -1], ['23:30:43.110290', '55730', '192.168.98.138.49341', '201.20.49.239.80', -1, '5840'], ['23:30:43.170344', '55731', '192.168.98.138.49341', '201.20.49.239.80', '562034569:562034972', '364925832']] A: To return results where ip[i][2] == ip[0][2] use a list comprehension: result = [ d for d in ip if d[2] == ip[0][2] ] A: [addr for addr in ip if addr[2].startswith("192.168.98.138"] which is the same as, though much neater than: addrs = [] for addr in ip: if addr[2].startswith("192.168.98.138"): addrs.append(addr) A: If you want to get both the index and the sublist (according to what you describe), then the following might work: >>> print [(index, x) for index, x in enumerate(ip) if x[2] == ip[0][2]] [(0, ['23:30:42.476071', '55729', '192.168.98.138.49341', '201.20.49.239.80', '562034568', -1]), (2, ['23:30:43.110290', '55730', '192.168.98.138.49341', '201.20.49.239.80', -1, '5840']), (3, ['23:30:43.170344', '55731', '192.168.98.138.49341', '201.20.49.239.80', '562034569:562034972', '364925832'])]
get list item which have count more than specific number by Python
I have nested list : ip[0] = ['23:30:42.476071', '55729', '192.168.98.138.49341', '201.20.49.239.80', '562034568', -1] ip[1] = ['23:30:43.110194', '20442', '201.20.49.239.80', '192.168.98.138.49341', '364925831', '562034569'] ip[2] = ['23:30:43.110290', '55730', '192.168.98.138.49341', '201.20.49.239.80', -1, '5840'] ip[3] = ['23:30:43.170344', '55731', '192.168.98.138.49341', '201.20.49.239.80', '562034569:562034972', '364925832'] ip[4] = ['23:30:43.170918', '20443', '201.20.49.239.80', '192.168.98.138.49341', -1, '64240'] ip[5] = ['23:30:44.022511', '20444', '201.20.49.239.80', '192.168.98.138.49341', '364925832:364925978', '562034972'] I want get index and sublist from my original list that have ip[i][2] = 192.168.98.138 for the above list I want get : ip[0] = ['23:30:42.476071', '55729', '192.168.98.138.49341', '201.20.49.239.80', '562034568', -1] ip[2] = ['23:30:43.110290', '55730', '192.168.98.138.49341', '201.20.49.239.80', -1, '5840'] ip[3] = ['23:30:43.170344', '55731', '192.168.98.138.49341', '201.20.49.239.80', '562034569:562034972', '364925832']
[ "Thanks for clarifying. Use a list comprehension:\n>>> ip = [['23:30:42.476071', '55729', '192.168.98.138.49341', '201.20.49.239.80', '562034568', -1], \n['23:30:43.110194', '20442', '201.20.49.239.80', '192.168.98.138.49341', '364925831', '562034569'],\n['23:30:43.110290', '55730', '192.168.98.138.49341', '201.20....
[ 2, 2, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004098309_list_python.txt
Q: MySQL Update reports error, What am I missing? I noticed a few posts on SO regarding MySQL updates using python and still cannot seem to get this correct. def updateEmployee(employee): print employee["firstName"]+" "+employee["lastName"]+" "+employee["nameN"] cursor = db.cursor() if(len(employee["nameN"]) > 0): cursor.execute(""" UPDATE `employee` SET `employeeID`=%s, `parentID`=%s, `firstName`=%s, `title`=%s, `locCode`=%s, (25) WHERE `employee`.`nameN`=%s """, (employee["employeeID"], employee["parentID"], employee["firstName"], employee["title"], employee["locCode"], employee["nameN"])) if(cursor.rowcount > 0 ): print "updated" else: c.execute(""" INSERT INTO `employee` (`employeeID`, `parentID`, `nameN`, `firstName`, `alias`, `lastName`, `title`, `department`, `phone`, `areaMission`, `leadershipStyle`, `employeeType`, `coreFunc1`, `coreFunc2`, `coreFunc3`, `address`, `locCode`,`posOrg`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """, (employee["employeeID"], employee["parentID"], employee["nameN"], employee["firstName"], "", employee["lastName"], employee["title"], "", employee["phone"], '', '', '', '', '', '', '', employee["locCode"], '')) if(c.rowcount > 0): db.commit() print "inserted" else: print "insert failed" else: print "missing nameN" Resulting Error which appaers on line 25 (updateEmployee) which for reference has (25) in front of the line above. [chris@apps ~]$ ./adjust.py Linda Adam adam.804 Traceback (most recent call last): File "./adjust.py", line 89, in <module> processCSV(fileName) File "./adjust.py", line 14, in processCSV updateEmployee(employee) File "./adjust.py", line 25, in updateEmployee WHERE `employee`.`nameN`=%s """, (employee["employeeID"], employee["parentID"], employee["firstName"], employee["title"], employee["locCode"], employee["nameN"])) File "/usr/lib/python2.5/site-packages/MySQLdb/cursors.py", line 166, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.5/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `employee`.`nameN`='adam.804'' at line 3") It appears I am ending up with an extra ' at the "WHERE clause" but I do not understand how this could be? The employee object I am using when this fails is defined as: { 'employeeID': '1111', 'firstName': 'Linda', 'title': 'Systems Manager', 'nameN': 'adam.804', 'lastName': 'Adam', 'locCode': 'TNC', 'phone': '555-555-5555', 'parentID': '2222', 'room': '' } A: I think you have an extra comma before your WHERE clause. An update should look like this: update foo set a = 1, b = 2 where type = 0 I think yours looks like this: update foo set a = 1, b = 2, where type = 0
MySQL Update reports error, What am I missing?
I noticed a few posts on SO regarding MySQL updates using python and still cannot seem to get this correct. def updateEmployee(employee): print employee["firstName"]+" "+employee["lastName"]+" "+employee["nameN"] cursor = db.cursor() if(len(employee["nameN"]) > 0): cursor.execute(""" UPDATE `employee` SET `employeeID`=%s, `parentID`=%s, `firstName`=%s, `title`=%s, `locCode`=%s, (25) WHERE `employee`.`nameN`=%s """, (employee["employeeID"], employee["parentID"], employee["firstName"], employee["title"], employee["locCode"], employee["nameN"])) if(cursor.rowcount > 0 ): print "updated" else: c.execute(""" INSERT INTO `employee` (`employeeID`, `parentID`, `nameN`, `firstName`, `alias`, `lastName`, `title`, `department`, `phone`, `areaMission`, `leadershipStyle`, `employeeType`, `coreFunc1`, `coreFunc2`, `coreFunc3`, `address`, `locCode`,`posOrg`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """, (employee["employeeID"], employee["parentID"], employee["nameN"], employee["firstName"], "", employee["lastName"], employee["title"], "", employee["phone"], '', '', '', '', '', '', '', employee["locCode"], '')) if(c.rowcount > 0): db.commit() print "inserted" else: print "insert failed" else: print "missing nameN" Resulting Error which appaers on line 25 (updateEmployee) which for reference has (25) in front of the line above. [chris@apps ~]$ ./adjust.py Linda Adam adam.804 Traceback (most recent call last): File "./adjust.py", line 89, in <module> processCSV(fileName) File "./adjust.py", line 14, in processCSV updateEmployee(employee) File "./adjust.py", line 25, in updateEmployee WHERE `employee`.`nameN`=%s """, (employee["employeeID"], employee["parentID"], employee["firstName"], employee["title"], employee["locCode"], employee["nameN"])) File "/usr/lib/python2.5/site-packages/MySQLdb/cursors.py", line 166, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.5/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `employee`.`nameN`='adam.804'' at line 3") It appears I am ending up with an extra ' at the "WHERE clause" but I do not understand how this could be? The employee object I am using when this fails is defined as: { 'employeeID': '1111', 'firstName': 'Linda', 'title': 'Systems Manager', 'nameN': 'adam.804', 'lastName': 'Adam', 'locCode': 'TNC', 'phone': '555-555-5555', 'parentID': '2222', 'room': '' }
[ "I think you have an extra comma before your WHERE clause.\nAn update should look like this:\nupdate foo\nset a = 1,\nb = 2\nwhere type = 0\n\nI think yours looks like this:\nupdate foo\nset a = 1,\nb = 2,\nwhere type = 0\n\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004098463_mysql_python.txt
Q: Using gtk dialog chooser widget to list files of a remote destination Well the question says it all.I am trying to create a file transfer application using python, and pygtk for UI.Most of the code is complete,the only problem being the UI for listing remote host's file list. I really like the Gtk Dialog Chooser widget,and already use it to list the local machine file list.I really would like to use the same widget to list files of the remote destination.Is it possible? A: From the paramiko tag, I assume you're using that to work with SSH. The GTK+ file chooser can't be populated manually, so what you're trying to do is not possible. However, most GTK+ packages come with GIO+GVFS [1]. This is a completely separate framework from Paramiko, but you should be able to use both (or even completely drop Paramiko). [1] One big caveat is that GVFS still doesn't exist in Windows (and probably won't ever exist). If you need to support Windows, you may be able to use the older GnomeVFS, but I don't know how. To use GIO with the GTK+ file chooser: uri = 'sftp://foo.example.org/a/b/c' Mount the volume (or you can run gvfs-mount to test first). To use the linked code: f = gio.File(uri) mount(f) file_chooser.set_current_folder_uri(uri)
Using gtk dialog chooser widget to list files of a remote destination
Well the question says it all.I am trying to create a file transfer application using python, and pygtk for UI.Most of the code is complete,the only problem being the UI for listing remote host's file list. I really like the Gtk Dialog Chooser widget,and already use it to list the local machine file list.I really would like to use the same widget to list files of the remote destination.Is it possible?
[ "From the paramiko tag, I assume you're using that to work with SSH. The GTK+ file chooser can't be populated manually, so what you're trying to do is not possible.\nHowever, most GTK+ packages come with GIO+GVFS [1]. This is a completely separate framework from Paramiko, but you should be able to use both (or even...
[ 2 ]
[]
[]
[ "gtk", "paramiko", "pygtk", "python" ]
stackoverflow_0004097319_gtk_paramiko_pygtk_python.txt
Q: Strange result in python Could someone explain me this strange result on python 2.6.6 ? >>> a = "xx" >>> b = "xx" >>> a.__hash__() == b.__hash__() True >>> a is b True # ok.. was just to be sure >>> a = "x" * 2 >>> b = "x" * 2 >>> a.__hash__() == b.__hash__() True >>> a is b True # yeah.. looks ok so far ! >>> n = 2 >>> a = "x" * n >>> b = "x" * n >>> a.__hash__() == b.__hash__() True # still okay.. >>> a is b False # hey! What the F... ? A: The is operator tells you whether two variables point to the same object in memory. It is rarely useful and often confused with the == operator, which tells you whether two objects "look the same". It is particularly confusing when used with things like short string literals, because the Python compiler interns these for efficiency. In other words, when you write "xx" the compiler (emits bytecode that) creates one string object in memory and causes all literals "xx" to point to it. This explains why your first two comparisons are True. Notice that you can get the id of the strings by calling id on them, which (at least on CPython is probably) their address in memory: >>> a = "xx" >>> b = "xx" >>> id(a) 38646080 >>> id(b) 38646080 >>> a is b True >>> a = "x"*10000 >>> b = "x"*10000 >>> id(a) 38938560 >>> id(b) 38993504 >>> a is b False The third is because the compiler hasn't interned the strings a and b, for whatever reason (probably because it isn't smart enough to notice that the variable n is defined once and then never modified). You can in fact force Python to intern strings by, well, asking it to. This will give you a piddling amount of performance increase and might help. It's probably useless. Moral: don't use is with string literals. Or int literals. Or anywhere you don't mean it, really. A: To understand this, you need to understand a few different things. a is b returns true if a and b are the same object, not merely if they have the same value. Strings can have the same value but be a different instance of that value. When you say a = "x", what you're actually doing is creating a string constant "x" and then assigning a name to it, a. String constants are strings which are written literally in the code, and not calculated programmatically. String constants are always interned, which means they're stored in a table for reuse: if you say a = "a"; b = "a", it's actually the same as saying a = "a"; b = a, as they'll use the same interned string "a". That's why the first a is b is True. When you say a = "x" * 2, the Python compiler is actually optimizing this. It calculates the string at compile-time--it generates code as if you had written a = "xx". Thus, the resulting string "xx' is interned. That's why the second a is b is true. When you say a = "x" * n, the Python compiler doesn't know what n is at compile time. Therefore, it's forced to actually output the string "x" and then perform the string multiplication at runtime. Since that's performed at runtime, while "x" is interned the resulting string "xx" is not. As a result, each of these strings are different instances of "xx", so the final a is b is False. You can see the difference yourself: def a1(): a = "x" def a2(): a = "x" * 2 def a3(): n = 2 a = "x" * n import dis print "a1:" dis.dis(a1) print "a2:" dis.dis(a2) print "a3:" dis.dis(a3) In CPython 2.6.4, this outputs: a1: 4 0 LOAD_CONST 1 ('x') 3 STORE_FAST 0 (a) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE a2: 6 0 LOAD_CONST 3 ('xx') 3 STORE_FAST 0 (a) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE a3: 8 0 LOAD_CONST 1 (2) 3 STORE_FAST 0 (n) 9 6 LOAD_CONST 2 ('x') 9 LOAD_FAST 0 (n) 12 BINARY_MULTIPLY 13 STORE_FAST 1 (a) 16 LOAD_CONST 0 (None) 19 RETURN_VALUE Finally, note that you can say a = intern(a); b = intern(b) to create interned versions if the strings, which will guarantee that a is b is true. If all you want is to check string equality, however, just use a == b.
Strange result in python
Could someone explain me this strange result on python 2.6.6 ? >>> a = "xx" >>> b = "xx" >>> a.__hash__() == b.__hash__() True >>> a is b True # ok.. was just to be sure >>> a = "x" * 2 >>> b = "x" * 2 >>> a.__hash__() == b.__hash__() True >>> a is b True # yeah.. looks ok so far ! >>> n = 2 >>> a = "x" * n >>> b = "x" * n >>> a.__hash__() == b.__hash__() True # still okay.. >>> a is b False # hey! What the F... ?
[ "The is operator tells you whether two variables point to the same object in memory. It is rarely useful and often confused with the == operator, which tells you whether two objects \"look the same\".\nIt is particularly confusing when used with things like short string literals, because the Python compiler interns...
[ 18, 12 ]
[]
[]
[ "identity", "python", "string" ]
stackoverflow_0004098425_identity_python_string.txt
Q: How to get download progress info from I.D.Manager to python? im working a project lately to get download progress info remotely when im away. i googled a bit but i couldnt find any useful info. on this issue im using Internet Download Manager. please help :/ i appreciate any suggestions im thinking about making software with python but Also C is Ok. if there is a solution A: I dont know exactly how to do it but you can get IDM download progress( such as Transfer rate, TimeLeft... ) by reading the values of the ListView of Internet Download Manager windows (they call it "hook"? ) A: i just found idm has log file for every download in its temporary folder im trying to parse information from log file i dunno if it is possible sync.ly get info..but i'll try
How to get download progress info from I.D.Manager to python?
im working a project lately to get download progress info remotely when im away. i googled a bit but i couldnt find any useful info. on this issue im using Internet Download Manager. please help :/ i appreciate any suggestions im thinking about making software with python but Also C is Ok. if there is a solution
[ "I dont know exactly how to do it but you can get IDM download progress( such as Transfer rate, TimeLeft... ) by reading the values of the ListView of Internet Download Manager windows (they call it \"hook\"? )\n", "i just found idm has log file for every download in its temporary folder im trying to parse inform...
[ 1, 0 ]
[]
[]
[ "download", "python", "status" ]
stackoverflow_0004050653_download_python_status.txt
Q: Apache+django pythonpath confusion: ImportError: Could not import settings 'mysite.settings' I use python 2.4 and django 1.2.2 and apache 2.2.3 Write httpd.conf section like this: <Location "/mysite/"> PythonPath "['/home/usr/www'] + sys.path" SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonDebug On </Location> settings.py path: /home/usr/www/mysite/ but it doesn't work, when i visit http://localhost/mysite/ ImportError: Could not import settings 'mysite.settings' i modified it, change /home/usr/www to /var/www and copy settings.py in /var/www it works. So why apache treat two directories differently? A: Are you using SELinux? Compare the output of ls -laZ /var/www and ls -laZ /home/usr/www Chances are that your home directory cannot be accessed by the apache process. If this is the problem, it might be solved as simply as chcon -R --reference=/var/www /home/usr/www chmod og+x /home/usr /home/usr/www BTW: http://docs.djangoproject.com/en/dev/howto/deployment/modpython/ warns that "Support for mod_python will be deprecated in a future release of Django. If you are configuring a new deployment, you are strongly encouraged to consider using mod_wsgi or any of the other supported backends." A: Add PythonPath "['/home/usr/www/mysite'] + sys.path"
Apache+django pythonpath confusion: ImportError: Could not import settings 'mysite.settings'
I use python 2.4 and django 1.2.2 and apache 2.2.3 Write httpd.conf section like this: <Location "/mysite/"> PythonPath "['/home/usr/www'] + sys.path" SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonDebug On </Location> settings.py path: /home/usr/www/mysite/ but it doesn't work, when i visit http://localhost/mysite/ ImportError: Could not import settings 'mysite.settings' i modified it, change /home/usr/www to /var/www and copy settings.py in /var/www it works. So why apache treat two directories differently?
[ "Are you using SELinux? Compare the output of \nls -laZ /var/www\n\nand \nls -laZ /home/usr/www\n\nChances are that your home directory cannot be accessed by the apache process. If this is the problem, it might be solved as simply as\nchcon -R --reference=/var/www /home/usr/www\nchmod og+x /home/usr /home/usr/www\n...
[ 1, 0 ]
[]
[]
[ "apache", "django", "mod_python", "python" ]
stackoverflow_0004093872_apache_django_mod_python_python.txt
Q: Python urllib2.urlopen returning 302 error even though page exists I am using the Python function urllib2.urlopen to read the http://www.bad.org.uk/ website but I keep getting a 302 error even though when I visit the site it loads ok. Anyone have any idea why? import socket headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } socket.setdefaulttimeout(10) try: req = urllib2.Request('http://www.bad.org.uk/', None, headers) urllib2.urlopen(req) return True # URL Exist except ValueError, ex: print 'URL: %s not well formatted' % 'http://www.bad.org.uk/' return False # URL not well formatted except urllib2.HTTPError, ex: print 'The server couldn\'t fulfill the request for %s.' % 'http://www.bad.org.uk/' print 'Error code: ', ex.code return False except urllib2.URLError, ex: print 'We failed to reach a server for %s.' % 'http://www.bad.org.uk/' print 'Reason: ', ex.reason return False # URL don't seem to be alive Error printed: The server couldn't fulfill the request for http://www.bad.org.uk//site/1/default.aspx. Error code: 302 A: The page at http://www.bad.org.uk/ is broken when cookies are disabled. http://www.bad.org.uk/ returns: HTTP/1.1 302 Found Location: http://www.bad.org.uk/DesktopDefault.aspx Set-Cookie: Esperantus_Language_bad=en-GB; path=/ Set-Cookie: Esperantus_Language_rainbow=en-GB; path=/ Set-Cookie: PortalAlias=rainbow; path=/ Set-Cookie: refreshed=true; expires=Thu, 04-Nov-2010 16:21:23 GMT; path=/ Set-Cookie: .ASPXAUTH=; expires=Mon, 11-Oct-1999 23:00:00 GMT; path=/; HttpOnly Set-Cookie: portalroles=; expires=Mon, 11-Oct-1999 23:00:00 GMT; path=/ If I then request http://www.bad.org.uk/DesktopDefault.aspx without setting these cookies, it gives another 302 and a redirect to itself. urllib2 is ignoring the cookies and sending the new request without cookies, so it causes a redirect loop at that URL. To handle this, you need to add a cookie handler: import urllib2 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) response = opener.open('http://www.bad.org.uk') print response.read() A: Code 302 is a temporary redirect, so you should get the URI from the Location field of the response and request that.
Python urllib2.urlopen returning 302 error even though page exists
I am using the Python function urllib2.urlopen to read the http://www.bad.org.uk/ website but I keep getting a 302 error even though when I visit the site it loads ok. Anyone have any idea why? import socket headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } socket.setdefaulttimeout(10) try: req = urllib2.Request('http://www.bad.org.uk/', None, headers) urllib2.urlopen(req) return True # URL Exist except ValueError, ex: print 'URL: %s not well formatted' % 'http://www.bad.org.uk/' return False # URL not well formatted except urllib2.HTTPError, ex: print 'The server couldn\'t fulfill the request for %s.' % 'http://www.bad.org.uk/' print 'Error code: ', ex.code return False except urllib2.URLError, ex: print 'We failed to reach a server for %s.' % 'http://www.bad.org.uk/' print 'Reason: ', ex.reason return False # URL don't seem to be alive Error printed: The server couldn't fulfill the request for http://www.bad.org.uk//site/1/default.aspx. Error code: 302
[ "The page at http://www.bad.org.uk/ is broken when cookies are disabled.\nhttp://www.bad.org.uk/ returns:\nHTTP/1.1 302 Found\nLocation: http://www.bad.org.uk/DesktopDefault.aspx\nSet-Cookie: Esperantus_Language_bad=en-GB; path=/\nSet-Cookie: Esperantus_Language_rainbow=en-GB; path=/\nSet-Cookie: PortalAlias=rainbo...
[ 20, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004098702_python.txt
Q: Problem to initialize a object I got a weird error when I try to create a Screen object. Before It worked without any problem, but I got this error when I added a new attribute to the User class. This attribute is related to Screen in a relation many to many through user_screens. This is the error: "InvalidRequestError: One or more mappers failed to compile. Exception was probably suppressed within a hasattr() call. Message was: One or more mappers failed to compile. Exception was probably suppressed within a hasattr() call. Message was: Class 'zeppelinlib.screen.ScreenTest.Screen' is not mapped" These are the classes: class Screen(rdb.Model): """Set up screens table in the database""" rdb.metadata(metadata) rdb.tablename("screens") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) ip = Column("ip", String(20)) ... user_screens = Table( "user_screens", metadata, Column("user_id", Integer, ForeignKey("users.id")), Column("screen_id", Integer, ForeignKey("screens.id")) ) class User(rdb.Model): """Set up users table in the database""" rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) ... group = relationship("UserGroup", uselist=False) channels = relationship("Channel", secondary=user_channels, order_by="Channel.titleView", backref="users") mediaGroups = relationship("MediaGroup", secondary=user_media_groups, order_by="MediaGroup.title", backref="users") screens = relationship("Screen", secondary=user_screens, backref="users") I might not added new relation to user because I really don't know what the problem is... Thanks in avance! A: Try to specify the primary join via the primaryjoin keyword argument on one (don't know which one) of your relationships. Sometimes (in complex relationship graphs) SQLAlchemy has a hard time to figure out how it should go about. Worked for me more than once, albeit on 0.5.x.
Problem to initialize a object
I got a weird error when I try to create a Screen object. Before It worked without any problem, but I got this error when I added a new attribute to the User class. This attribute is related to Screen in a relation many to many through user_screens. This is the error: "InvalidRequestError: One or more mappers failed to compile. Exception was probably suppressed within a hasattr() call. Message was: One or more mappers failed to compile. Exception was probably suppressed within a hasattr() call. Message was: Class 'zeppelinlib.screen.ScreenTest.Screen' is not mapped" These are the classes: class Screen(rdb.Model): """Set up screens table in the database""" rdb.metadata(metadata) rdb.tablename("screens") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) ip = Column("ip", String(20)) ... user_screens = Table( "user_screens", metadata, Column("user_id", Integer, ForeignKey("users.id")), Column("screen_id", Integer, ForeignKey("screens.id")) ) class User(rdb.Model): """Set up users table in the database""" rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) ... group = relationship("UserGroup", uselist=False) channels = relationship("Channel", secondary=user_channels, order_by="Channel.titleView", backref="users") mediaGroups = relationship("MediaGroup", secondary=user_media_groups, order_by="MediaGroup.title", backref="users") screens = relationship("Screen", secondary=user_screens, backref="users") I might not added new relation to user because I really don't know what the problem is... Thanks in avance!
[ "Try to specify the primary join via the primaryjoin keyword argument on one (don't know which one) of your relationships. Sometimes (in complex relationship graphs) SQLAlchemy has a hard time to figure out how it should go about. Worked for me more than once, albeit on 0.5.x.\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0004072663_python_sqlalchemy.txt
Q: how to search in line/point shapefile using mapnik? I'm using mapnik in my django app to display esri shapefiles on a map. When a user clicks on an object (polygon, point or line), a popup should appear with info on that particular object. I'm able to search polygons by using the function query_point: mapnik_map = mapnik.Map(400, 400) mapnik_map.layers.append(layer) mapnik_map.append_style(style) feature_set = mapnik_map.query_point(0, x, y) for feature in feature_set.features: print feature When I use above method to search in point/line files, I never get a result feature_set. So the question is: how do I implement a search function for points and lines for shapefiles? Django 1.2.3, Mapnik 0.7.0 on ubuntu 10.04 64 bit. A: This is a bug in Mapnik, which we are aware of: http://trac.mapnik.org/ticket/503 and I am planning to work on soon for inclusion in Mapnik2. In the meantime you can try applying the patch listed their against Mapnik 0.7.x. If you have trouble please comment on that ticket.
how to search in line/point shapefile using mapnik?
I'm using mapnik in my django app to display esri shapefiles on a map. When a user clicks on an object (polygon, point or line), a popup should appear with info on that particular object. I'm able to search polygons by using the function query_point: mapnik_map = mapnik.Map(400, 400) mapnik_map.layers.append(layer) mapnik_map.append_style(style) feature_set = mapnik_map.query_point(0, x, y) for feature in feature_set.features: print feature When I use above method to search in point/line files, I never get a result feature_set. So the question is: how do I implement a search function for points and lines for shapefiles? Django 1.2.3, Mapnik 0.7.0 on ubuntu 10.04 64 bit.
[ "This is a bug in Mapnik, which we are aware of: http://trac.mapnik.org/ticket/503 and I am planning to work on soon for inclusion in Mapnik2. In the meantime you can try applying the patch listed their against Mapnik 0.7.x. If you have trouble please comment on that ticket.\n" ]
[ 0 ]
[]
[]
[ "mapnik", "python", "shapefile" ]
stackoverflow_0004096026_mapnik_python_shapefile.txt
Q: Python error calculating program Ask the user to enter payroll information for the company. Set up a loop that continues to ask for information until they enter “DONE”. For each employee ask three questions: name (first & last) hours worked this week (only allow 1 through 60) hourly wage (only allow 6.00 through 20.00) VALIDATE the hours worked and the hourly wage, and make sure a name is entered. Calculate each employee’s pay, and write it out to a sequential file. Be sure to include file I/O error handling logic. Include only the weekly pay Weekly pay is calculated: For (1-40 hours) it is hourly rate * hours worked For (41-60 hours) it is (hours worked – 40) * (hourly rate * 1.5) + hourly rate * 40 After all the employees are entered, read in the sequential file into a list named PAY for the weekly pay of each employee. Sort the list. Now print the lowest, highest, and average weekly pay for the week. I am having obvious problem with this code while len(eName)>0: eName=raw_input("\nPlease enter the employees' first and last name. ") hWork=raw_input("How many hours did they work this week? ") hoursWork=int(hWork) if hoursWork < 1 or hoursWork > 60: print "Employees' can't work less than 1 hour or more than 60 hours!" else: pRate=raw_input("What is their hourly rate? ") payRate=int(pRate) if payRate < 6 or payRate > 20: print "Employees' wages can't be lower than $6.00 or greater than $20.00!" if hoursWork <=40: grossPay=hoursWork*payRate else: grossPay=((hoursWork-40)*(payRate*1.5))+(40*payRate) lsthours.append(grossPay) print grossPay print lsthours ePass=raw_input("Type DONE when finished with employees' information. ") ePass.upper() == "DONE" if ePass == "DONE": break else: continue A: There's several problems with this code: The indentation is all over the place. For example, the while loop ends at that first if statement The test for the while loop is almost certainly false (since eName isn't initialised), so the loop never enters the code at ePass.upper() == "DONE" is trying to set the ePass variable, which means that test won't work. You need: if ePass.upper() == "DONE": break A: Yu can do something as this: grossPay = 0.0 lsthours = [] eName=raw_input("\nPlease enter the employees' first and last name (type 'PASS' to exit): ") while eName.upper() != "PASS": hWork=raw_input("How many hours did they work this week? ") hoursWork=int(hWork) if hoursWork < 1 or hoursWork > 60: print "Employees' can't work less than 1 hour or more than 60 hours!" else: pRate=raw_input("What is their hourly rate? ") payRate=int(pRate) if payRate < 6 or payRate > 20: print "Employees' wages can't be lower than $6.00 or greater than $20.00!" if hoursWork <=40: grossPay=hoursWork*payRate else: grossPay=((hoursWork-40)*(payRate*1.5))+(40*payRate) lsthours.append(grossPay) print grossPay print lsthours eName=raw_input("\nPlease enter the employees' first and last name. (type 'PASS' to exit): ") A: A few errors as has been pointed out: In python, indentation decides the code blocks while loop: while logic_test: # this is inside while loop .... # this is outside while loop Certain functions on string does not replace the string in place, they return another string via return value upper: >>> a = "done" >>> a.upper() 'DONE' >>> a 'done' >>> Always initialize your variables. If you are using sequence methods, the variable should have been defined as sequence earlier. >>> t.append('ll') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 't' is not defined >>> t = [] >>> t.append('ll') >>> Make your scope explicit lsthours = [] while len(eName)>0: ........ lsthours.append(grossPay) A: try this: lsthours = list() eName = "start" # initialize to something to start the loop while eName: eName = raw_input("\nPlease enter the employees' first and last name. ") if not eName: break #loop will exit also when blank name is inserted hWork = raw_input("How many hours did they work this week? ") hoursWork = int(hWork) if hoursWork < 1 or hoursWork > 60: print "Employees' can't work less than 1 hour or more than 60 hours!" continue #skip pRate = raw_input("What is their hourly rate? ") payRate = int(pRate) if payRate < 6 or payRate > 20: print "Employees' wages can't be lower than $6.00 or greater than $20.00!" continue #skip if hoursWork <= 40: grossPay = hoursWork * payRate else: grossPay = ((hoursWork - 40) * (payRate * 1.5)) + (40 * payRate) lsthours.append(grossPay) print grossPay print lsthours ePass = raw_input("Type DONE when finished with employees' information. ") if ePass.upper() == "DONE": break It still lacks exception checking but should work. The "data error" checks should just short-circuit the main loop, it's simpler, but you can have a more involved code and put them into their own loop.
Python error calculating program
Ask the user to enter payroll information for the company. Set up a loop that continues to ask for information until they enter “DONE”. For each employee ask three questions: name (first & last) hours worked this week (only allow 1 through 60) hourly wage (only allow 6.00 through 20.00) VALIDATE the hours worked and the hourly wage, and make sure a name is entered. Calculate each employee’s pay, and write it out to a sequential file. Be sure to include file I/O error handling logic. Include only the weekly pay Weekly pay is calculated: For (1-40 hours) it is hourly rate * hours worked For (41-60 hours) it is (hours worked – 40) * (hourly rate * 1.5) + hourly rate * 40 After all the employees are entered, read in the sequential file into a list named PAY for the weekly pay of each employee. Sort the list. Now print the lowest, highest, and average weekly pay for the week. I am having obvious problem with this code while len(eName)>0: eName=raw_input("\nPlease enter the employees' first and last name. ") hWork=raw_input("How many hours did they work this week? ") hoursWork=int(hWork) if hoursWork < 1 or hoursWork > 60: print "Employees' can't work less than 1 hour or more than 60 hours!" else: pRate=raw_input("What is their hourly rate? ") payRate=int(pRate) if payRate < 6 or payRate > 20: print "Employees' wages can't be lower than $6.00 or greater than $20.00!" if hoursWork <=40: grossPay=hoursWork*payRate else: grossPay=((hoursWork-40)*(payRate*1.5))+(40*payRate) lsthours.append(grossPay) print grossPay print lsthours ePass=raw_input("Type DONE when finished with employees' information. ") ePass.upper() == "DONE" if ePass == "DONE": break else: continue
[ "There's several problems with this code:\n\nThe indentation is all over the place. For example, the while loop ends at that first if statement\nThe test for the while loop is almost certainly false (since eName isn't initialised), so the loop never enters\nthe code at ePass.upper() == \"DONE\" is trying to set th...
[ 2, 1, 1, 1 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0004099160_loops_python.txt
Q: Great flask / other python micro framework code I could learn from I'd like to look at some good web-app code written in python, just so I can learn some of the patterns / see how I can improve my code. I've already googled around a bit, used google code search and run a search on github too - but haven't come across a well built, comprehensive app. Perhaps a book could work as well. Basically, I'm just trying to find a way to learn the basic programming patterns for web-applications. Any suggestions? A: Why not start with the publicly available flask.pocoo.org? Note: I'm linking to the Github repository on which he has published the code for his website (which runs on flask) rather than the website itself. A: IMHO your time would be better invested learning something like Django, because much of what you could improve in a micro framework is already builtin on a bigger framework.
Great flask / other python micro framework code I could learn from
I'd like to look at some good web-app code written in python, just so I can learn some of the patterns / see how I can improve my code. I've already googled around a bit, used google code search and run a search on github too - but haven't come across a well built, comprehensive app. Perhaps a book could work as well. Basically, I'm just trying to find a way to learn the basic programming patterns for web-applications. Any suggestions?
[ "Why not start with the publicly available flask.pocoo.org? \nNote: I'm linking to the Github repository on which he has published the code for his website (which runs on flask) rather than the website itself.\n", "IMHO your time would be better invested learning something like Django, because much of what you co...
[ 3, 0 ]
[]
[]
[ "flask", "python", "web_applications" ]
stackoverflow_0004083440_flask_python_web_applications.txt
Q: Sequence of vowels count This is not a homework question, it is an exam preparation question. I should define a function syllables(word) that counts the number of syllables in A word in the following way: • a maximal sequence of vowels is a syllable; • a final e in a word is not a syllable (or the vowel sequence it is a part Of). I do not have to deal with any special cases, such as a final e in a One-syllable word (e.g., ’be’ or ’bee’). >>> syllables(’honour’) 2 >>> syllables(’decode’) 2 >>> syllables(’oiseau’) 2 Should I use regular expression here or just list comprehension ? A: I find regular expressions natural for this question. (I think a non-regex answer would take more coding. I use two string methods, 'lower' and 'endswith' to make the answer more clear.) import re def syllables(word): word = word.lower() if word.endswith('e'): word = word[:-1] count = len(re.findall('[aeiou]+', word)) return count for word in ('honour', 'decode', 'decodes', 'oiseau', 'pie'): print word, syllables(word) Which prints: honour 2 decode 2 decodes 3 oiseau 2 pie 1 Note that 'decodes' has one more syllable than 'decode' (which is strange, but fits your definition). Question. How does this help you? Isn't the point of the study question that you work through it yourself? You may get more benefit in the future by posting a failed attempt in your question, so you can learn exactly where you are lacking. A: Use regexps - most languages will let you count the number of matches of a regexp in a string. Then special-case the terminal-e by checking the right-most match group. A: I don't think regex is the right solution here. It seems pretty straightforward to write this treating each string as a list. A: Some pointers: [abc] matches a, b or c. A + after a regex token allows the token to match once or more $ matches the end of the string. (?<=x) matches the current position only if the previous character is an x. (?!x) matches the current position only if the next character is not an x. EDIT: I just saw your comment that since this is not homework, actual code is requested. Well, then: [aeiou]+(?!(?<=e)$) If you don't want to count final vowel sequences that end in e at all (like the u in tongue or the o in toe), then use [aeiou]+(?=[^aeiou])|[aeiou]*[aiou]$ I'm sure you'll be able to figure out how it works if you read the explanation above. A: Here's an answer without regular expressions. My real answer (also posted) uses regular expressions. Untested code: def syllables(word): word = word.lower() if word.endswith('e'): word = word[:-1] vowels = 'aeiou' in_vowel_group = False vowel_groups = 0 for letter in word: if letter in vowels: if not in_vowel_group: in_vowel_group = True vowel_groups += 1 else: in_vowel_group = False return vowel_groups A: Both ways work. You said yourself that it was for exam preparation. Use whichever is going to be on the exam. If they're both on the exam, use which you need more practice for. Just remember: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. ~Jamie Zawinski So in my opinion, don't use regex unless you need the practice. A: Regular expressions would be way too complex, and a list comprehension probably wouldn't be robust enough. You will probably be able to solve this easily using a grammar lexer like PyParsing. Give it a shot! A: Use a regex that matches a,e,i,o, or u, convert the string to a list, then iterate through the list... 1 for first true, 1 for next false, 2 for next true, 2 for next false, etc. To handle the case where the last letter is 'e' following a consonant (as in ate), just check the last two letters of the word before you start. If they match that pattern truncate the final e and process as normal. A: This pattern works for your definition: (?!e$)([aeiouy]+) Just count how many times it occurs.
Sequence of vowels count
This is not a homework question, it is an exam preparation question. I should define a function syllables(word) that counts the number of syllables in A word in the following way: • a maximal sequence of vowels is a syllable; • a final e in a word is not a syllable (or the vowel sequence it is a part Of). I do not have to deal with any special cases, such as a final e in a One-syllable word (e.g., ’be’ or ’bee’). >>> syllables(’honour’) 2 >>> syllables(’decode’) 2 >>> syllables(’oiseau’) 2 Should I use regular expression here or just list comprehension ?
[ "I find regular expressions natural for this question. (I think a non-regex answer would take more coding. I use two string methods, 'lower' and 'endswith' to make the answer more clear.)\nimport re\ndef syllables(word):\n word = word.lower()\n if word.endswith('e'):\n word = word[:-1]\n count = l...
[ 3, 2, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "nlp", "python", "regex" ]
stackoverflow_0004099042_nlp_python_regex.txt
Q: How to find index of an element in Python list? Possible Duplicate: How to find positions of the list maximum? A question from homework: Define a function censor(words,nasty) that takes a list of words, and replaces all the words appearing in nasty with the word CENSORED, and returns the censored list of words. >>> censor([’it’,’is’,’raining’], [’raining’]) [’it’,’is’,’CENSORED’] I see solution like this: find an index of nasty replace words matching that index with "CENSORED" but i get stuck on finding the index.. A: You can find the index of any element of a list by using the .index method. >>> l=['a','b','c'] >>> l.index('b') 1 A: Your approach might work, but it’s unnecessarily complicated. Python allows a very simple syntax to check whether something is contained in a list: censor = [ 'bugger', 'nickle' ] word = 'bugger' if word in censor: print 'CENSORED' With that approach, simply walk over your list of words and test for each words whether it’s in the censor list. To walk over your list of words, you can use the for loop. Since you might need to modify the current word, use an index, like so: for index in len(words)): print index, words[index] Now all you need to do is put the two code fragments together. A: Actually you don't have to operate with indexes here. Just iterate over words list and check if the word is listed in nasty. If it is append 'CENSORED' to the result list, else append the word itself. Or you can involve list comprehension and conditional expression to get more elegant version: A: You could use the handy built-in enumerate() function to step through the items in the list. For example: def censor(words, nasty): for i,word in enumerate(words): if word...
How to find index of an element in Python list?
Possible Duplicate: How to find positions of the list maximum? A question from homework: Define a function censor(words,nasty) that takes a list of words, and replaces all the words appearing in nasty with the word CENSORED, and returns the censored list of words. >>> censor([’it’,’is’,’raining’], [’raining’]) [’it’,’is’,’CENSORED’] I see solution like this: find an index of nasty replace words matching that index with "CENSORED" but i get stuck on finding the index..
[ "You can find the index of any element of a list by using the .index method.\n>>> l=['a','b','c']\n>>> l.index('b')\n1\n\n", "Your approach might work, but it’s unnecessarily complicated.\nPython allows a very simple syntax to check whether something is contained in a list:\ncensor = [ 'bugger', 'nickle' ]\nword ...
[ 38, 1, 1, 0 ]
[]
[]
[ "indexing", "list", "python" ]
stackoverflow_0004097338_indexing_list_python.txt
Q: using a colon in a string in python i am using python 2.6.5 to develop an app for google app engine - i am not too familiar with python, but i'm learning. i am trying to put a url into a string so variable = "string http://domain.name" then i print the string out. the problem is, if the colon (after http) is in the string, i don't get any output and i don't know why. i've tried escaping the string with: """http://domain.name""" r"http://domain.name" "http\://domain.name" "http\://domain.name" "http\\://domain.name" "http:://domain.name" none of them seem to work and i'm not sure what else to try The context is like so variables.py is: ... HOST_URL = "http://domain.name" ... example logout.py import variables import sys ... class Logout(webapp.RequestHandler): """ RequestHandler for when a user wishes to logout from the system.""" def post(self): self.get() def get(self): print(variables.HOST_URL) print('hi') self.redirect(variables.HOST_URL) sys.exit() or in file functions.py import variables import sys ... def sendhome(requesthandler) print 'go to '+variables.HOST_URL requesthandler.redirect(variables.HOST_URL) sys.exit() called from a context like: from functions import sendhome ... class Logout(webapp.RequestHandler): """ RequestHandler for when a user wishes to logout from the system.""" def post(self): self.get() def get(self): sendhome(self) any help would be appreciated thanks A: If I'm not terrible mistaken, GAE uses WSGI, you do not simply print things, you are supposed to return a proper HTTP response object (it is not PHP). I guess that if you access the page using firefox+firebug and look at the network->header you will see that the browser is taking http: as an HTTP header with value "//domain.name". Edited: By the way, should not you be using "self.response.out.write" instead of "print"? A: The problem was the sys.exit() after the call to print or redirect
using a colon in a string in python
i am using python 2.6.5 to develop an app for google app engine - i am not too familiar with python, but i'm learning. i am trying to put a url into a string so variable = "string http://domain.name" then i print the string out. the problem is, if the colon (after http) is in the string, i don't get any output and i don't know why. i've tried escaping the string with: """http://domain.name""" r"http://domain.name" "http\://domain.name" "http\://domain.name" "http\\://domain.name" "http:://domain.name" none of them seem to work and i'm not sure what else to try The context is like so variables.py is: ... HOST_URL = "http://domain.name" ... example logout.py import variables import sys ... class Logout(webapp.RequestHandler): """ RequestHandler for when a user wishes to logout from the system.""" def post(self): self.get() def get(self): print(variables.HOST_URL) print('hi') self.redirect(variables.HOST_URL) sys.exit() or in file functions.py import variables import sys ... def sendhome(requesthandler) print 'go to '+variables.HOST_URL requesthandler.redirect(variables.HOST_URL) sys.exit() called from a context like: from functions import sendhome ... class Logout(webapp.RequestHandler): """ RequestHandler for when a user wishes to logout from the system.""" def post(self): self.get() def get(self): sendhome(self) any help would be appreciated thanks
[ "If I'm not terrible mistaken, GAE uses WSGI, you do not simply print things, you are supposed to return a proper HTTP response object (it is not PHP).\nI guess that if you access the page using firefox+firebug and look at the network->header you will see that the browser is taking http: as an HTTP header with valu...
[ 7, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004092159_google_app_engine_python.txt
Q: Will Python be faster if I put commonly called code into separate methods or files? I thought I once read on SO that Python will compile and run slightly more quickly if commonly called code is placed into methods or separate files. Does putting Python code in methods have an advantage over separate files or vice versa? Could someone explain why this is? I'd assume it has to do with memory allocation and garbage collection or something. A: It doesn't matter. Don't structure your program around code speed; structure it around coder speed. If you write something in Python and it's too slow, find the bottleneck with cProfile and speed it up. How do you speed it up? You try things and profile them. In general, function call overhead in critical loops is high. Byte compiling your code takes a very small amount of time and only needs to be done once. A: No. Regardless of where you put your code, it has to be parsed once and compiled if necessary. Distinction between putting code in methods or different files might have an insignificant performance difference, but you shouldn't worry about it. About the only language right now that you have to worry about structuring "right" is Javascript. Because it has to be downloaded from net to client's computer. That's why there are so many compressors and obfuscators for it. Stuff like this isn't done with Python because it's not needed. A: Two things: Code in separate modules is compiled into bytecode at first runtime and saved as a precompiled .pyc file, so it doesn't have to be recompiled at the next run as long as the source hasn't been modified since. This might result in a small performance advantage, but only at program startup. Also, Python stores variables etc. a bit more efficiently if they are placed inside functions instead of at the top level of a file. But I don't think that's what you're referring to here, is it?
Will Python be faster if I put commonly called code into separate methods or files?
I thought I once read on SO that Python will compile and run slightly more quickly if commonly called code is placed into methods or separate files. Does putting Python code in methods have an advantage over separate files or vice versa? Could someone explain why this is? I'd assume it has to do with memory allocation and garbage collection or something.
[ "It doesn't matter. Don't structure your program around code speed; structure it around coder speed. If you write something in Python and it's too slow, find the bottleneck with cProfile and speed it up. How do you speed it up? You try things and profile them. In general, function call overhead in critical loops is...
[ 4, 2, 1 ]
[]
[]
[ "performance", "python", "runtime" ]
stackoverflow_0004100532_performance_python_runtime.txt
Q: General question regarding wether or not use Twisted in TCP proxy project I need to write simple but effective and scalable TCP proxy, that would accept connections on one IP:PORT and forward the data to, possibly large, number of clients listening on their IP:PORT pairs. The question is, if there is a reason to use Twisted here? Will there be any gain, I cant see now, but will see upon project completion? I am asking this question, mainly because Twisted is very complex, and its docs arent newbies friendly - I have the code more or less done using pure Python sockets and multiprocess module, and getting the same written in Twisted already gave me a solid headache. So, what are your thought on that? Is Twisted a waste of time and overkill, or will it bring some benefits (speed, robustness, scalability and so on)? Maybe there is something else that could be used with greater ease and same success, like Gevent or Eventlet frameworks? A: Twisted will make your code simpler, as it already does a lot of the work for you. For example, here is an echo server using Twisted: from twisted.internet.protocol import Protocol class Echo(Protocol): def dataReceived(self, data): self.transport.write(data) And here's a round-robin TCP load balancer (untested, but should be at least close to correct): from twisted.internet.protocol import Factory from twisted.protocols.portforward import ProxyServer, ProxyFactory class Balancer(Factory): def __init__(self, hostports): self.factories = [] for (host, port) in hostports: self.factories.append(ProxyFactory(host, port)) def buildProtocol(self, addr): nextFactory = self.factories.pop(0) self.factories.append(nextFactory) return nextFactory.buildProtocol(addr) Is your existing multiprocess code this simple? If so, there's still the fact that Twisted will work with platform-specific scalability mechanisms (kqueue on MacOS/BSD, epoll on linux, IOCP on Win32), so you can tune your code to the most appropriate mechanism by using command-line tools, rather than having to actually rewrite your code.
General question regarding wether or not use Twisted in TCP proxy project
I need to write simple but effective and scalable TCP proxy, that would accept connections on one IP:PORT and forward the data to, possibly large, number of clients listening on their IP:PORT pairs. The question is, if there is a reason to use Twisted here? Will there be any gain, I cant see now, but will see upon project completion? I am asking this question, mainly because Twisted is very complex, and its docs arent newbies friendly - I have the code more or less done using pure Python sockets and multiprocess module, and getting the same written in Twisted already gave me a solid headache. So, what are your thought on that? Is Twisted a waste of time and overkill, or will it bring some benefits (speed, robustness, scalability and so on)? Maybe there is something else that could be used with greater ease and same success, like Gevent or Eventlet frameworks?
[ "Twisted will make your code simpler, as it already does a lot of the work for you. For example, here is an echo server using Twisted:\nfrom twisted.internet.protocol import Protocol\nclass Echo(Protocol):\n def dataReceived(self, data):\n self.transport.write(data)\n\nAnd here's a round-robin TCP load b...
[ 4 ]
[]
[]
[ "proxy", "python", "sockets", "twisted" ]
stackoverflow_0004096061_proxy_python_sockets_twisted.txt
Q: Why can my Django app not write to its log file? $ sudo /etc/init.d/apache2 restart * Restarting web server apache2 ... waiting . ...done. username@servername Thu Nov 04 18:54:37 ~/public_html/IDM_app $ sudo tail -n 60 /var/log/apache2/error.log [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] mod_wsgi (pid=28760): Exception occurred processing WSGI script '/home/username/public_html/idm.wsgi'. [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] Traceback (most recent call last): [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/handlers/wsgi.py", line 230, in __call__ [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] self.load_middleware() [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/handlers/base.py", line 33, in load_middleware [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] for middleware_path in settings.MIDDLEWARE_CLASSES: [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/utils/functional.py", line 276, in __getattr__ [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] self._setup() [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/conf/__init__.py", line 40, in _setup [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] self._wrapped = Settings(settings_module) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/conf/__init__.py", line 73, in __init__ [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] mod = importlib.import_module(self.SETTINGS_MODULE) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/utils/importlib.py", line 35, in import_module [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] __import__(name) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/home/username/public_html/IDM_app/settings.py", line 60, in <module> [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] from settings_local import * [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/home/username/public_html/IDM_app/settings_local.py", line 1, in <module> [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] from settings_Slicehost_idm import * [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/home/username/public_html/IDM_app/settings_Slicehost_idm.py", line 12, in <module> [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] format='%(pathname)s TIME: %(asctime)s MSG: %(filename)s:%(funcName)s:%(lineno)d %(message)s', [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/logging/__init__.py", line 1500, in basicConfig [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] hdlr = FileHandler(filename, mode) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/logging/__init__.py", line 889, in __init__ [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] StreamHandler.__init__(self, self._open()) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/logging/__init__.py", line 908, in _open [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] stream = open(self.baseFilename, self.mode) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] IOError: [Errno 13] Permission denied: '/home/username/public_html/IDM_app/log/django.osqa.log' [Thu Nov 04 18:54:36 2010] [notice] caught SIGTERM, shutting down [Thu Nov 04 18:54:37 2010] [notice] Apache/2.2.14 (Ubuntu) mod_wsgi/3.3 Python/2.7 configured -- resuming normal operations username@servername Thu Nov 04 18:54:42 ~/public_html/IDM_app $ ls -l /home/username/public_html/IDM_app/log/django.osqa.log -rw-r--r-- 1 username 0 Nov 4 18:24 /home/username/public_html/IDM_app/log/django.osqa.log username@servername Thu Nov 04 19:08:41 ~/public_html/IDM_app **$ ls -l ~/public_html/idm.wsgi ** -rw-r--r-- 1 username 222 Nov 4 18:53 /home/username/public_html/idm.wsgi username@servername Thu Nov 04 19:10:50 ~/public_html/IDM_app $ cat ~/public_html/idm.wsgi import os import sys sys.path.append('/home/username/public_html/IDM_app/') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() username@servername Thu Nov 04 19:11:02 ~/public_html/IDM_app $ whoami username If Apache2 uses the Virtual Host setup file @ ~/public_html/idm.wsgi, what User does the system think is trying to write the the log file log/django.osqa.log ? Why can my Django app not write to its log file? A: Apache's probably running as the apache user, meaning that it doesn't have write access to the log file. It starts up fine because it only has to read the wsgi file, which has read permissions for all users. either chmod a+w django.osqa.log or chown <apache-user> django.osqa.log. Note: the preferred method would be to chown the file. Note 2: this is distro-dependent, but since that looks Ubuntu-y, the apache user will be www-data.
Why can my Django app not write to its log file?
$ sudo /etc/init.d/apache2 restart * Restarting web server apache2 ... waiting . ...done. username@servername Thu Nov 04 18:54:37 ~/public_html/IDM_app $ sudo tail -n 60 /var/log/apache2/error.log [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] mod_wsgi (pid=28760): Exception occurred processing WSGI script '/home/username/public_html/idm.wsgi'. [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] Traceback (most recent call last): [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/handlers/wsgi.py", line 230, in __call__ [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] self.load_middleware() [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/handlers/base.py", line 33, in load_middleware [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] for middleware_path in settings.MIDDLEWARE_CLASSES: [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/utils/functional.py", line 276, in __getattr__ [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] self._setup() [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/conf/__init__.py", line 40, in _setup [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] self._wrapped = Settings(settings_module) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/conf/__init__.py", line 73, in __init__ [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] mod = importlib.import_module(self.SETTINGS_MODULE) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/utils/importlib.py", line 35, in import_module [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] __import__(name) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/home/username/public_html/IDM_app/settings.py", line 60, in <module> [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] from settings_local import * [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/home/username/public_html/IDM_app/settings_local.py", line 1, in <module> [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] from settings_Slicehost_idm import * [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/home/username/public_html/IDM_app/settings_Slicehost_idm.py", line 12, in <module> [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] format='%(pathname)s TIME: %(asctime)s MSG: %(filename)s:%(funcName)s:%(lineno)d %(message)s', [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/logging/__init__.py", line 1500, in basicConfig [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] hdlr = FileHandler(filename, mode) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/logging/__init__.py", line 889, in __init__ [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] StreamHandler.__init__(self, self._open()) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] File "/usr/local/lib/python2.7/logging/__init__.py", line 908, in _open [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] stream = open(self.baseFilename, self.mode) [Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] IOError: [Errno 13] Permission denied: '/home/username/public_html/IDM_app/log/django.osqa.log' [Thu Nov 04 18:54:36 2010] [notice] caught SIGTERM, shutting down [Thu Nov 04 18:54:37 2010] [notice] Apache/2.2.14 (Ubuntu) mod_wsgi/3.3 Python/2.7 configured -- resuming normal operations username@servername Thu Nov 04 18:54:42 ~/public_html/IDM_app $ ls -l /home/username/public_html/IDM_app/log/django.osqa.log -rw-r--r-- 1 username 0 Nov 4 18:24 /home/username/public_html/IDM_app/log/django.osqa.log username@servername Thu Nov 04 19:08:41 ~/public_html/IDM_app **$ ls -l ~/public_html/idm.wsgi ** -rw-r--r-- 1 username 222 Nov 4 18:53 /home/username/public_html/idm.wsgi username@servername Thu Nov 04 19:10:50 ~/public_html/IDM_app $ cat ~/public_html/idm.wsgi import os import sys sys.path.append('/home/username/public_html/IDM_app/') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() username@servername Thu Nov 04 19:11:02 ~/public_html/IDM_app $ whoami username If Apache2 uses the Virtual Host setup file @ ~/public_html/idm.wsgi, what User does the system think is trying to write the the log file log/django.osqa.log ? Why can my Django app not write to its log file?
[ "Apache's probably running as the apache user, meaning that it doesn't have write access to the log file. It starts up fine because it only has to read the wsgi file, which has read permissions for all users. either chmod a+w django.osqa.log or chown <apache-user> django.osqa.log.\nNote: the preferred method woul...
[ 17 ]
[]
[]
[ "apache2", "django", "mod_wsgi", "python" ]
stackoverflow_0004100584_apache2_django_mod_wsgi_python.txt
Q: Workaround OSError with os.listdir I have a directory with 90K files in it. This is such a preposterously huge number of files that bash functions like ls fail. So of course, does os.listdir() from my python (Mac Python, version 2.5) script; it fails with OSError: [Errno 12] Cannot allocate memory: '.' People will say "Don't put that many files in a single directory! Are you crazy?" -- but I like to pretend that I live in the future, a brilliant, glowing place, where I have gigabytes of memory at my disposal, and don't need to worry too much about where exactly my files go, as long as there's rust left on my spinning platters. So, is there a good workaround for this os.listdir() problem? I've considered just shelling out to find, but that's a bit gross, and unfortunately find is recursive, with no supported maxdepth option on Mac OS X 10.6. Here's what the os.listdir via shelling out to find looks like, roughly: def ls(directory): import os files = os.popen4('find %s' % directory)[1].read().rstrip().split('\n') files.remove(directory) return files # probably want to remove dir prefix from everything in here too Update: os.listdir() succeeds in python 2.6. A: You're hitting a historical artifact in Python: os.listdir should return an iterator, not an array. I think this function predates iterators--it's odd that no os.xlistdir has been added. This has more effects than just memory usage on huge directories. Even on a directory with just a few thousand files, you're going to have to wait for the entire directory scan to complete, and you have to read the entire directory, even if the first entry is the one you were looking for. This is a pretty glaring lack in Python: there appears to be no binding to the low-level opendir/readdir/fdopendir APIs, so it seems like it's not even possible to implement this yourself without writing a native module. This is one of those cases where it's such a huge, gaping hole in the standard library that I doubt myself and suspect I'm just not seeing it--there are low-level open, stat, etc. bindings, and this is in the same category. A: You could try going one level deeper and directly call opendir() and readdir() using ctypes. A: def ls(directory): """full-featured solution, via wrapping find""" import os files = os.popen4('find %s' % directory)[1].read().rstrip().split('\n') files.remove(directory) n = len(directory) if directory[-1] != os.path.sep: n += 1 files = [f[n:] for f in files] # remove dir prefix return [f for f in files if os.path.sep not in f] # remove files in sub-directories A: I get the same IOError on Apple Python 2.5.5 on 10.6 when listing a big directory. It works just fine in Python2.6. Python 2.5.5 (r255:77872, Sep 21 2010, 09:52:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> x = os.listdir('.') OSError: [Errno 12] Cannot allocate memory: '.' This seems to be a bug in Python2.5. See "os.listdir randomly fails on occasions when it shouldn't" and "Sloppy error checking in listdir() for Posix".
Workaround OSError with os.listdir
I have a directory with 90K files in it. This is such a preposterously huge number of files that bash functions like ls fail. So of course, does os.listdir() from my python (Mac Python, version 2.5) script; it fails with OSError: [Errno 12] Cannot allocate memory: '.' People will say "Don't put that many files in a single directory! Are you crazy?" -- but I like to pretend that I live in the future, a brilliant, glowing place, where I have gigabytes of memory at my disposal, and don't need to worry too much about where exactly my files go, as long as there's rust left on my spinning platters. So, is there a good workaround for this os.listdir() problem? I've considered just shelling out to find, but that's a bit gross, and unfortunately find is recursive, with no supported maxdepth option on Mac OS X 10.6. Here's what the os.listdir via shelling out to find looks like, roughly: def ls(directory): import os files = os.popen4('find %s' % directory)[1].read().rstrip().split('\n') files.remove(directory) return files # probably want to remove dir prefix from everything in here too Update: os.listdir() succeeds in python 2.6.
[ "You're hitting a historical artifact in Python: os.listdir should return an iterator, not an array. I think this function predates iterators--it's odd that no os.xlistdir has been added.\nThis has more effects than just memory usage on huge directories. Even on a directory with just a few thousand files, you're ...
[ 8, 4, 2, 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0004098831_macos_python.txt
Q: Can't get Scrapy pipeline to work I have spider that I have written using the Scrapy framework. I am having some trouble getting any pipelines to work. I have the following code in my pipelines.py: class FilePipeline(object): def __init__(self): self.file = open('items.txt', 'wb') def process_item(self, item, spider): line = item['title'] + '\n' self.file.write(line) return item and my CrawlSpider subclass has this line to activate the pipeline for this class. ITEM_PIPELINES = [ 'event.pipelines.FilePipeline' ] However when I run it using scrapy crawl my_spider I get a line that says 2010-11-03 20:24:06+0000 [scrapy] DEBUG: Enabled item pipelines: with no pipelines (I presume this is where the logging should output them). I have tried looking through the documentation but there doesn't seem to be any full examples of a whole project to see if I have missed anything. Any suggestions on what to try next? or where to look for further documentation? A: Got it! The line needs to go in the settings module for the project. Now it works! A: I'm willing to bet that it's a capitalisation difference in the word pipeline somewhere: Pipeline vs. PipeLine I notice 'event.pipelines.FilePipeline' uses the former, whereas your code uses the latter: which do your filenames use? (I have fallen victim to this spelling mistake many times!)
Can't get Scrapy pipeline to work
I have spider that I have written using the Scrapy framework. I am having some trouble getting any pipelines to work. I have the following code in my pipelines.py: class FilePipeline(object): def __init__(self): self.file = open('items.txt', 'wb') def process_item(self, item, spider): line = item['title'] + '\n' self.file.write(line) return item and my CrawlSpider subclass has this line to activate the pipeline for this class. ITEM_PIPELINES = [ 'event.pipelines.FilePipeline' ] However when I run it using scrapy crawl my_spider I get a line that says 2010-11-03 20:24:06+0000 [scrapy] DEBUG: Enabled item pipelines: with no pipelines (I presume this is where the logging should output them). I have tried looking through the documentation but there doesn't seem to be any full examples of a whole project to see if I have missed anything. Any suggestions on what to try next? or where to look for further documentation?
[ "Got it! The line needs to go in the settings module for the project. Now it works!\n", "I'm willing to bet that it's a capitalisation difference in the word pipeline somewhere:\nPipeline vs. PipeLine\nI notice 'event.pipelines.FilePipeline' uses the former, whereas your code uses the latter: which do your filena...
[ 8, 0 ]
[]
[]
[ "pipeline", "python", "scraper", "scrapy", "web_crawler" ]
stackoverflow_0004090795_pipeline_python_scraper_scrapy_web_crawler.txt
Q: How to write Python bindings for command line applications I'm interested in writing a python binding or wrapper for an existing command line utility that I use on Linux, so that I can access its features in my python programs. Is there a standard approach to doing this that someone could point me to? At the moment, I have wrapped the command line executable in a subprocess.Popen call, which works but feels quite brittle, and I'd like to make the integration between the two sides much more stable so that it works in places other than my own computer! A: If you must use a command line interface, then subprocess.Popen is your best bet. Remember that you can use shell=True to let it pick the path variables, you can use os.path.join to use OS-dependent path separators etc. If, however, your command line utility has shared libraries, look at ctypes, which allows you to connect directly to those libraries and expose functionality directly. A: One way would be to re-factor your command line utility so that command line handling is separated and the actual functionality is exposed as shared archive. Then you could expose those function using cython. Write your complete command line utility in python that exploits those functions. This makes distribution hard though. What you are doing is still the best way.
How to write Python bindings for command line applications
I'm interested in writing a python binding or wrapper for an existing command line utility that I use on Linux, so that I can access its features in my python programs. Is there a standard approach to doing this that someone could point me to? At the moment, I have wrapped the command line executable in a subprocess.Popen call, which works but feels quite brittle, and I'd like to make the integration between the two sides much more stable so that it works in places other than my own computer!
[ "If you must use a command line interface, then subprocess.Popen is your best bet. Remember that you can use shell=True to let it pick the path variables, you can use os.path.join to use OS-dependent path separators etc.\nIf, however, your command line utility has shared libraries, look at ctypes, which allows you ...
[ 5, 1 ]
[]
[]
[ "binding", "c", "c++", "python" ]
stackoverflow_0004101130_binding_c_c++_python.txt
Q: Simple server/client string exchange protocol i am looking for an abstract and clean way to exchange strings between two python programs. The protocol is really simple: client/server sends a string to the server/client and it takes the corresponding action - via a handler, i suppose - and replies OR NOT to the other side with another string. Strings can be three things: an acknowledgement, signalling one side that the other on is still alive; a pickled class containing a command, if going from the "client" to the "server", or a response, if going from the "server" to the "client"; and finally a "lock" command, that signals a side of the conversation that the other is working and no further questions should be asked until another lock packet is received. I have been looking at the python's built in SocketServer.TCPServer, but it's way too low level, it does not easily support reconnection and the client has to use the socket interface, which i preferred to be encapsulated. I then explored the twisted framework, particularly the LineOnlyReceiver protocol and server examples, but i found the initial learning curve to be too steep, the online documentation assuming a little too much knowledge and a general lack of examples and good documentation (except the 2005 O'reilly book, is this still valid?). I then tryied the pyliblo library, which is perfect for the task, alas it is monodirectional, there is no way to "answer" a client, and i need the answer to be associated to the specific command. So my question is: is there an existing framework/library/module that allows me to have a client object in the server, to read the commands from and send the replies to, and a server object in the client, to read the replies from and send the commands to, that i can use after a simple setup (client, the server address is host:port, server, you are listening on port X) having the underlying socket, reconnection engine and so on handled? thanks in advance to any answer (pardon my english and inexperience, this is my first question) A: Python also provides an asyncchat module that simplifies much of the server/client behavior common to chat-like communications. A: What you want to do seems a lot like RPC, so the things that come to my mind are XMLRPC or JSON RPC, if you dont want to use XML . Python has a XMLRPC library that you can use, it uses HTTP as the transport so it also solves your problem of not being too low level. However if you could provide more detail in terms of what you exactly want to do perhaps we can give a better solution.
Simple server/client string exchange protocol
i am looking for an abstract and clean way to exchange strings between two python programs. The protocol is really simple: client/server sends a string to the server/client and it takes the corresponding action - via a handler, i suppose - and replies OR NOT to the other side with another string. Strings can be three things: an acknowledgement, signalling one side that the other on is still alive; a pickled class containing a command, if going from the "client" to the "server", or a response, if going from the "server" to the "client"; and finally a "lock" command, that signals a side of the conversation that the other is working and no further questions should be asked until another lock packet is received. I have been looking at the python's built in SocketServer.TCPServer, but it's way too low level, it does not easily support reconnection and the client has to use the socket interface, which i preferred to be encapsulated. I then explored the twisted framework, particularly the LineOnlyReceiver protocol and server examples, but i found the initial learning curve to be too steep, the online documentation assuming a little too much knowledge and a general lack of examples and good documentation (except the 2005 O'reilly book, is this still valid?). I then tryied the pyliblo library, which is perfect for the task, alas it is monodirectional, there is no way to "answer" a client, and i need the answer to be associated to the specific command. So my question is: is there an existing framework/library/module that allows me to have a client object in the server, to read the commands from and send the replies to, and a server object in the client, to read the replies from and send the commands to, that i can use after a simple setup (client, the server address is host:port, server, you are listening on port X) having the underlying socket, reconnection engine and so on handled? thanks in advance to any answer (pardon my english and inexperience, this is my first question)
[ "Python also provides an asyncchat module that simplifies much of the server/client behavior common to chat-like communications. \n", "What you want to do seems a lot like RPC, so the things that come to my mind are XMLRPC or JSON RPC, if you dont want to use XML . \nPython has a XMLRPC library that you can use, ...
[ 0, 0 ]
[]
[]
[ "networking", "protocols", "python", "string" ]
stackoverflow_0004097639_networking_protocols_python_string.txt
Q: Executemany confusion Ok, so I have a function that selects certain rows in a sqlite database based on input from a plugin. I got the plugin to select and fetch rows when just one statement is involved, but since I want to add some flexibility to this, I tried making the function use executemany when encountering lists or tuples. Yet, despite all the things I have fiddled and changed, I a still unable to get this to work, either because the sqlite statement is treating each character in the string as a binding, or because there are too many bindings in the tuple. Here's the code I have so far: def readoffset(self,offset): vartype = type(name) print(vartype) if vartype == int: self.memcursor.execute('''select all id,matbefore,matafter,name,date from main as main where id = ?''',[offset]) undolist = self.memcursor.fetchall() print(undolist) return(undolist) elif vartype == tuple or list: print(vartype) self.memcursor.executemany('''select all id,matbefore,matafter,name,date from main as main where name = (?)''', [offset]) undolist = self.memcursor.fetchall() return(undolist) A: Look at http://www.python.org/dev/peps/pep-0249/ Use of this method for an operation which produces one or more result sets constitutes undefined behavior, and the implementation is permitted So, executemany can be used for INSERT's and UPDATE's but not for SELECT You can try following code: elif isinstance(offset, (tuple, list)): offsets=', '.join(offset) self.memcursor.execute('''select all id,matbefore,matafter,name,date from main as main where name IN (?)''', [offsets]) A: I don't think you need executemany here. Try something like this instead: self.memcursor.execute('''SELECT id, matbefore, matafter, name, date FROM main WHERE name IN (%s)''' % ','.join('?'*len(offset)), (offset,)) Note that the string interpolation is done to place multiple placeholders into the query.
Executemany confusion
Ok, so I have a function that selects certain rows in a sqlite database based on input from a plugin. I got the plugin to select and fetch rows when just one statement is involved, but since I want to add some flexibility to this, I tried making the function use executemany when encountering lists or tuples. Yet, despite all the things I have fiddled and changed, I a still unable to get this to work, either because the sqlite statement is treating each character in the string as a binding, or because there are too many bindings in the tuple. Here's the code I have so far: def readoffset(self,offset): vartype = type(name) print(vartype) if vartype == int: self.memcursor.execute('''select all id,matbefore,matafter,name,date from main as main where id = ?''',[offset]) undolist = self.memcursor.fetchall() print(undolist) return(undolist) elif vartype == tuple or list: print(vartype) self.memcursor.executemany('''select all id,matbefore,matafter,name,date from main as main where name = (?)''', [offset]) undolist = self.memcursor.fetchall() return(undolist)
[ "Look at http://www.python.org/dev/peps/pep-0249/\n\nUse of this method for an operation\n which produces one or\n more result sets constitutes undefined behavior, and\n the implementation is permitted\n\nSo, executemany can be used for INSERT's and UPDATE's but not for SELECT\nYou can try following code:\nelif ...
[ 5, 3 ]
[]
[]
[ "database", "executemany", "python", "sqlite" ]
stackoverflow_0004101076_database_executemany_python_sqlite.txt
Q: urllib2 freezes GUI I'm using PyGTK for a small app I've developing. The usage of URLlib2 through a proxy will freeze my GUI. Is there anyway to prevent that? My code that actually does the work is seperate from the GUI, so I was thinking may be using subprocess to call the python file. However, how would that work if I was to convert the app to an exe file? Thanks A: Calling urllib2 from the main thread blocks the Gtk event loop and consequently freezes the user interface. This is not specific to urllib2, but happens with any longer running function (e.g. subprocess.call). Either use the asynchronous IO facilities from glib or call urllib2 in a separate thread to avoid this issue. A: I'd consider using the multiprocess module, creating a pair of Queue objects ... one for the GUI controller or other components to send requests to the urllib2 process; the other for returning the results. Just a pair of Queue objects would be sufficient for a simple design (just two processes). The urllib2 process simple consumes requests from it's request queue and posts response to the results queue. The process on the other side can operate asynchronously, posting requests and, from anywhere in the event loop (or from a separate thread), pulling responses out and posting them back to a dictionary or dispatching a callback function (probably also maintained as a dictionary). (For example I might have the request model create a callback handling object, store it in a dictionary using the object's ID as the key, and post a tuple of of that ID and the URL to the request queue, then have the response processing pull IDs and response text of the response queue so that the event handling loop can then dispatch the response to the .callback() method of the object which was stored in the dictionary to begin with. The responses could be URL text results but handling for Exception objects could also be implemented (perhaps dispatched to a .errback() method in our hypothetical callback object's interface). Naturally if our main GUI is multi-threaded we have to ensure coherent access to this dictionary. However there should be relatively low contention on that. All access to this dictionary is non-blocking). More complex designs are possible. A pool of urllib2 handling processes could all share one pair of Queue objects (the beauty of these queues is that they handle all the locking and coherency details for us; multiple producers/consumers are supported). If the GUI needed to be fanned out into multiple processes that could share the same urllib2 process or pool then it would be time to look for a message bus (spread or AMQP for example). Share memory and the multiprocess locking primitives could also be used; but that would involve quite a bit more effort.
urllib2 freezes GUI
I'm using PyGTK for a small app I've developing. The usage of URLlib2 through a proxy will freeze my GUI. Is there anyway to prevent that? My code that actually does the work is seperate from the GUI, so I was thinking may be using subprocess to call the python file. However, how would that work if I was to convert the app to an exe file? Thanks
[ "Calling urllib2 from the main thread blocks the Gtk event loop and consequently freezes the user interface. This is not specific to urllib2, but happens with any longer running function (e.g. subprocess.call).\nEither use the asynchronous IO facilities from glib or call urllib2 in a separate thread to avoid this ...
[ 6, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004100628_pygtk_python.txt
Q: can i use panel without a frame in wxpython? there are some people? i have some question about wxpython , can i use panel without a frame? A: The simple answer is "no". The panel is not a TopLevelWindow. Top level windows are Frames and Windows. Panels typically go in Frames, although you can nest panels in panels or frames. Telling us what to do, as Ryan suggested, would be the best way to get a good answer though. A: In the wxpython scheme of things a process creates windows/frames. You can make the decorations (i.e. titlebar and resize/close buttons) hidden such that it looks like a splash screen. But this makes is difficult for the user to easily close the program.
can i use panel without a frame in wxpython?
there are some people? i have some question about wxpython , can i use panel without a frame?
[ "The simple answer is \"no\". The panel is not a TopLevelWindow. Top level windows are Frames and Windows. Panels typically go in Frames, although you can nest panels in panels or frames. Telling us what to do, as Ryan suggested, would be the best way to get a good answer though.\n", "In the wxpython scheme of th...
[ 5, 4 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0004096417_python_wxpython_wxwidgets.txt
Q: Is wx.richtext supported in wxpython 2.8? im using wxpython 2.8 ansi with python 2.6 ,and richtext class seems to not exist as an error message prompts that wx module does not contain richtext attribute, i've searched the web but couldn't find a clear answer,therefore i come to you:) any thoughts? thanks in advance Nataly A: I just downloaded and installed version 2.8.11-ansi. RichTextControl is the first demo listed, and works fine. It sounds like there is something messed up with your installation. Unless you have to support windows 98/ME, I don't know any good reason to prefer the ansi version over unicode. Can you provide the exact text of the error message, and a listing of your site-packages, and the contents of wx.pth A: You access the rich text control like this: import wx.richtext Or you pass the wx.TextCtrl the wx.TE_RICH or wx.TE_RICH2 flag. I've heard that the richtext widget isn't available on *nix though. Did you try the wxPython Demo? That's usually the best place to look to find out how to use a widget.
Is wx.richtext supported in wxpython 2.8?
im using wxpython 2.8 ansi with python 2.6 ,and richtext class seems to not exist as an error message prompts that wx module does not contain richtext attribute, i've searched the web but couldn't find a clear answer,therefore i come to you:) any thoughts? thanks in advance Nataly
[ "I just downloaded and installed version 2.8.11-ansi. RichTextControl is the first demo listed, and works fine.\nIt sounds like there is something messed up with your installation.\nUnless you have to support windows 98/ME, I don't know any good reason to prefer the ansi version over unicode.\nCan you provide the e...
[ 1, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004092333_python_wxpython.txt
Q: "BadValueError: Property xxxx is not multi-line" on db.TextProperty() I'm using python, django and google app engine and I'm getting the error below. However, bookdescription is a TextProperty not a StringProperty so I don't understand why the multi-line error is happening. The error is intermittent, sometimes the page will render fine, sometimes not. I'm new to coding so any and all help is very much appreciated! Model definition looks like this: class Book(db.Model): list = db.ReferenceProperty(List) booktitle = db.StringProperty() bookauthor = db.StringProperty() bookdescription = db.TextProperty() added = db.DateTimeProperty(auto_now_add=True) Full error: Property bookdescription is not multi-line Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/base/data/home/apps/7-books/3.345967110627358311/7books.py", line 279, in get self.response.out.write(template.render(path, template_values)) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/webapp/template.py", line 81, in render return t.render(Context(template_dict)) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/webapp/template.py", line 121, in wrap_render return orig_render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 168, in render return self.nodelist.render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 705, in render bits.append(self.render_node(node, context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 718, in render_node return(node.render(context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/loader_tags.py", line 82, in render return compiled_parent.render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 168, in render return self.nodelist.render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 705, in render bits.append(self.render_node(node, context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 718, in render_node return(node.render(context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/loader_tags.py", line 23, in render result = self.nodelist.render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 705, in render bits.append(self.render_node(node, context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 718, in render_node return(node.render(context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/defaulttags.py", line 99, in render values = list(values) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 2012, in next return self.__model_class.from_entity(self.__iterator.next()) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 1239, in from_entity instance = cls(None, _from_entity=True, **entity_values) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 813, in __init__ prop.__set__(self, value) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 542, in __set__ value = self.validate(value) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 2453, in validate raise BadValueError('Property %s is not multi-line' % self.name) BadValueError: Property bookdescription is not multi-line Class looks like this: class Displaylist(webapp.RequestHandler): def get(self, id): booklist = List.get_by_id(int(id)) books = booklist.book_set list = booklist creator = booklist.user location = getip(self.request.remote_addr) tld = gettld(location) aff = getaff(location) user = users.get_current_user() if user: loginout = users.create_logout_url("/") username = user.email() else: loginout = users.create_login_url("/") username = '' template_values = { 'list': list, 'creator': creator, 'books': books, 'email': username, 'loginout': loginout, 'tld': tld, 'aff': aff, } path = os.path.join(os.path.dirname(__file__), 'templates/list.html') self.response.out.write(template.render(path, template_values)) A: It seems like the runtime environment is somehow referring to a different definition of the Book model which has bookdescription defined as a StringProperty because the error is being raised from the StringProperty.validate() function. Do you have the Book model defined in multiple places by any chance?
"BadValueError: Property xxxx is not multi-line" on db.TextProperty()
I'm using python, django and google app engine and I'm getting the error below. However, bookdescription is a TextProperty not a StringProperty so I don't understand why the multi-line error is happening. The error is intermittent, sometimes the page will render fine, sometimes not. I'm new to coding so any and all help is very much appreciated! Model definition looks like this: class Book(db.Model): list = db.ReferenceProperty(List) booktitle = db.StringProperty() bookauthor = db.StringProperty() bookdescription = db.TextProperty() added = db.DateTimeProperty(auto_now_add=True) Full error: Property bookdescription is not multi-line Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/base/data/home/apps/7-books/3.345967110627358311/7books.py", line 279, in get self.response.out.write(template.render(path, template_values)) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/webapp/template.py", line 81, in render return t.render(Context(template_dict)) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/webapp/template.py", line 121, in wrap_render return orig_render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 168, in render return self.nodelist.render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 705, in render bits.append(self.render_node(node, context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 718, in render_node return(node.render(context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/loader_tags.py", line 82, in render return compiled_parent.render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 168, in render return self.nodelist.render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 705, in render bits.append(self.render_node(node, context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 718, in render_node return(node.render(context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/loader_tags.py", line 23, in render result = self.nodelist.render(context) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 705, in render bits.append(self.render_node(node, context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/__init__.py", line 718, in render_node return(node.render(context)) File "/base/python_runtime/python_lib/versions/third_party/ django-0.96/django/template/defaulttags.py", line 99, in render values = list(values) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 2012, in next return self.__model_class.from_entity(self.__iterator.next()) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 1239, in from_entity instance = cls(None, _from_entity=True, **entity_values) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 813, in __init__ prop.__set__(self, value) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 542, in __set__ value = self.validate(value) File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 2453, in validate raise BadValueError('Property %s is not multi-line' % self.name) BadValueError: Property bookdescription is not multi-line Class looks like this: class Displaylist(webapp.RequestHandler): def get(self, id): booklist = List.get_by_id(int(id)) books = booklist.book_set list = booklist creator = booklist.user location = getip(self.request.remote_addr) tld = gettld(location) aff = getaff(location) user = users.get_current_user() if user: loginout = users.create_logout_url("/") username = user.email() else: loginout = users.create_login_url("/") username = '' template_values = { 'list': list, 'creator': creator, 'books': books, 'email': username, 'loginout': loginout, 'tld': tld, 'aff': aff, } path = os.path.join(os.path.dirname(__file__), 'templates/list.html') self.response.out.write(template.render(path, template_values))
[ "It seems like the runtime environment is somehow referring to a different definition of the Book model which has bookdescription defined as a StringProperty because the error is being raised from the StringProperty.validate() function.\nDo you have the Book model defined in multiple places by any chance?\n" ]
[ 4 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0004101538_django_google_app_engine_python.txt
Q: Multi-dimensional char array (array of strings) in python ctypes I'm trying to pass an array of character arrays to a C function using ctypes. void cfunction(char ** strings) { strings[1] = "bad"; //works not what I need. strings[1][2] = 'd'; //this will segfault. return; } char *input[] = {"foo","bar"}; cfunction(input); Since the array that I throw around is statically defined anyways, I just changed the function declaration and input parameter like so: void cfunction(char strings[2][4]) { //strings[1] = "bad"; //not what I need. strings[1][2] = 'd'; //what I need and now it works. return; } char input[2][4] = {"foo","bar"}; cfunction(input); Now I run into the problem of how to define this multi-dimensional character array in python. I had thought it would go like so: import os from ctypes import * libhello = cdll.LoadLibrary(os.getcwd() + '/libhello.so') input = (c_char_p * 2)() input[0] = create_string_buffer("foo") input[1] = create_string_buffer("bar") libhello.cfunction(input) This gives me TypeError: incompatible types, c_char_Array_4 instance instead of c_char_p instance. If I change it to: for i in input: i = create_string_buffer("foo") Then I get segmentation faults. Also this looks like the wrong way to build the 2d array because if I print input I see None: print input[0] print input[1] # outputs None, None instead of "foo" and "foo" I also run into the issue of using #DEFINE MY_ARRAY_X 2 and #DEFINE MY_ARRAY_Y 4 to keep the array dimensions straight in my C files, but don't know a good way to get these constants out of the libhello.so so that python can reference them when it constructs the datatypes. A: Use something like input = ((c_char * 4) * 2)() input[0].value = "str" input[0][0] == "s" input[0][1] == "t" # and so on... Simple usage: >>> a =((c_char * 4) * 2)() >>> a <__main__.c_char_Array_4_Array_2 object at 0x9348d1c> >>> a[0] <__main__.c_char_Array_4 object at 0x9348c8c> >>> a[0].raw '\x00\x00\x00\x00' >>> a[0].value '' >>> a[0].value = "str" >>> a[0] <__main__.c_char_Array_4 object at 0x9348c8c> >>> a[0].value 'str' >>> a[0].raw 'str\x00' >>> a[1].value '' >>> a[0][0] 's' >>> a[0][0] = 'x' >>> a[0].value 'xtr'
Multi-dimensional char array (array of strings) in python ctypes
I'm trying to pass an array of character arrays to a C function using ctypes. void cfunction(char ** strings) { strings[1] = "bad"; //works not what I need. strings[1][2] = 'd'; //this will segfault. return; } char *input[] = {"foo","bar"}; cfunction(input); Since the array that I throw around is statically defined anyways, I just changed the function declaration and input parameter like so: void cfunction(char strings[2][4]) { //strings[1] = "bad"; //not what I need. strings[1][2] = 'd'; //what I need and now it works. return; } char input[2][4] = {"foo","bar"}; cfunction(input); Now I run into the problem of how to define this multi-dimensional character array in python. I had thought it would go like so: import os from ctypes import * libhello = cdll.LoadLibrary(os.getcwd() + '/libhello.so') input = (c_char_p * 2)() input[0] = create_string_buffer("foo") input[1] = create_string_buffer("bar") libhello.cfunction(input) This gives me TypeError: incompatible types, c_char_Array_4 instance instead of c_char_p instance. If I change it to: for i in input: i = create_string_buffer("foo") Then I get segmentation faults. Also this looks like the wrong way to build the 2d array because if I print input I see None: print input[0] print input[1] # outputs None, None instead of "foo" and "foo" I also run into the issue of using #DEFINE MY_ARRAY_X 2 and #DEFINE MY_ARRAY_Y 4 to keep the array dimensions straight in my C files, but don't know a good way to get these constants out of the libhello.so so that python can reference them when it constructs the datatypes.
[ "Use something like\ninput = ((c_char * 4) * 2)()\ninput[0].value = \"str\"\ninput[0][0] == \"s\"\ninput[0][1] == \"t\" # and so on...\n\nSimple usage:\n>>> a =((c_char * 4) * 2)()\n>>> a\n<__main__.c_char_Array_4_Array_2 object at 0x9348d1c>\n>>> a[0]\n<__main__.c_char_Array_4 object at 0x9348c8c>\n>>> a[0].raw\n'...
[ 9 ]
[]
[]
[ "ctypes", "multidimensional_array", "python" ]
stackoverflow_0004101536_ctypes_multidimensional_array_python.txt
Q: Python 3.1 - Error while adding a library in Blender For this problem (stackoverflow.com/questions/4086435/), I tried to make a Python 3 version of the library python-websocket (github.com/mtah/python-websocket/), here is my code: https://gist.github.com/663175. Blender comes with his own Python 3.1 package, so I added my file directly in its «site-packages» folder. I get this error now: Traceback (most recent call last): File "websocket.py", line 6, in AttributeError: 'module' object has no attribute 'WebSocket' when running this code in Blender: import sys, os, asyncore, websocket def msg_handler(msg): print(msg) socket = websocket.WebSocket('ws://localhost:8080/', onmessage=msg_handler) socket.onopen = lambda: socket.send('Hello world!') try: asyncore.loop() except KeyboardInterrupt: socket.close() I found that a __init__.py is needed so I added but it didn't help… What I am doing wrong here ? Thanks for your help. A: It looks like you called your script websocket.py, so the import of websocket finds the script itself, instead of the installed module by that name. Rename the script to something else (and if it created a websocket.pyc file, delete that.)
Python 3.1 - Error while adding a library in Blender
For this problem (stackoverflow.com/questions/4086435/), I tried to make a Python 3 version of the library python-websocket (github.com/mtah/python-websocket/), here is my code: https://gist.github.com/663175. Blender comes with his own Python 3.1 package, so I added my file directly in its «site-packages» folder. I get this error now: Traceback (most recent call last): File "websocket.py", line 6, in AttributeError: 'module' object has no attribute 'WebSocket' when running this code in Blender: import sys, os, asyncore, websocket def msg_handler(msg): print(msg) socket = websocket.WebSocket('ws://localhost:8080/', onmessage=msg_handler) socket.onopen = lambda: socket.send('Hello world!') try: asyncore.loop() except KeyboardInterrupt: socket.close() I found that a __init__.py is needed so I added but it didn't help… What I am doing wrong here ? Thanks for your help.
[ "It looks like you called your script websocket.py, so the import of websocket finds the script itself, instead of the installed module by that name. Rename the script to something else (and if it created a websocket.pyc file, delete that.)\n" ]
[ 3 ]
[]
[]
[ "blender", "python", "websocket" ]
stackoverflow_0004101621_blender_python_websocket.txt
Q: why did virtualenv not include all of the system paths? I created a virtualenv, and while it has many system paths, it doesn't have others. Specifically, pyshared and dist-packages don't seem to be included. As a result, my system-wide MySQLdb and psycopg2 aren't available. Any ideas why? A: Seems to be related to Ubuntu's messing with python and virtualenv A: The only possible way that i'm aware of, is if you have created your virtualenv with the argument --no-site-packages: from Here: If you build with virtualenv --no-site-packages ENV it will not inherit any packages from /usr/lib/python2.5/site-packages (or wherever your global site-packages directory is). This can be used if you don't have control over site-packages and don't want to depend on the packages there, or you just want more isolation from the global system. so Here is an example to understand more: First i will create a virtualenv normally (without --no-site-package) and you will see that i can always access django that is installed in my system site-packages (or dist-packages): $ virtualenv A New python executable in A/bin/python Installing setuptools............done $ source A/bin/activate (A)$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.__file__ '/usr/local/lib/python2.6/dist-packages/django/__init__.pyc' But now i will create the virtual env using --no-site-package: $ virtualenv B --no-site-package New python executable in B/bin/python Installing setuptools............done. $ source B/bin/activate (B)$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named django now you see that virtaulenv was able to access django from system dist-packages (ubuntu) in my machine. Hope this will help :)
why did virtualenv not include all of the system paths?
I created a virtualenv, and while it has many system paths, it doesn't have others. Specifically, pyshared and dist-packages don't seem to be included. As a result, my system-wide MySQLdb and psycopg2 aren't available. Any ideas why?
[ "Seems to be related to Ubuntu's messing with python and virtualenv\n", "The only possible way that i'm aware of, is if you have created your virtualenv with the argument --no-site-packages:\nfrom Here:\n\nIf you build with virtualenv\n --no-site-packages ENV it will not inherit any packages from\n /usr/lib/pyt...
[ 2, 1 ]
[]
[]
[ "path", "python", "virtualenv" ]
stackoverflow_0004101931_path_python_virtualenv.txt
Q: This my script that check a number is prime or not, but when the number is 99 or 77, the scripyt failed to check, why? how to fix it? num = input("Please enter an integer: ") def is_Prime(): h = num / 2 for x in range(2, h +1): if (num%x) == 0: return False return True def main(): if is_Prime(): print num, "is a prime number" else: print num, "is not a prime number" main() A: You are always returning true or false after checking divisibility with 2: for x in range(2, h + 1): if (num%x) == 0: return False # <<< here else: int(h) != h return True # <<< and here Also I'm not sure what the line int(h) != h is supposed to do. You are evaluating an expression and then discarding the result. Try this instead: for x in range(2, h + 1): if (num % x) == 0: return False return True Regarding the line h = num / 2 the upper limit of num / 2 will work, but actually you only need to check up to math.sqrt(num). A: Try this: def is_Prime(): h = num / 2 for x in range(2, h +1): if (num%x) == 0: return False return True A: You seem to have fixed the problems with your script with your edit. However, there a few more things you could improve. You should really be passing the number you're testing to the function, rather than accessing at as a global variable. The call to input() should really be inside the main() function. Also, you can simplify your loop by using the all function: def is_Prime(num): h = num / 2 return all(num % x != 0 for x in range(2,h+1))
This my script that check a number is prime or not, but when the number is 99 or 77, the scripyt failed to check, why? how to fix it?
num = input("Please enter an integer: ") def is_Prime(): h = num / 2 for x in range(2, h +1): if (num%x) == 0: return False return True def main(): if is_Prime(): print num, "is a prime number" else: print num, "is not a prime number" main()
[ "You are always returning true or false after checking divisibility with 2:\nfor x in range(2, h + 1):\n if (num%x) == 0:\n return False # <<< here\n else:\n int(h) != h\n return True # <<< and here\n\nAlso I'm not sure what the line int(h) != h is supposed to do. You are evaluating an...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004101920_python.txt
Q: Loop control, what is more efficient Which one of the two alternatives below is more efficient? Any recommendations to further improve it? Alternative A: for i in BAR_Items: if BAR_Items[i] != A and SHAPE[i+"_SHP"] != A: continue if i in Selection: Selection.remove(i) BAR_Items[i].clearActions() BAR_Items[i].add(vizact.spinTo(axisAngle=[0,1,0,90],speed=300)) VFrame.SetStatusText(frame, i + " has been deselected. "+ str(Selection)) else: Selection.append(i) BAR_Items[i].add(vizact.spin(0,1,0,90,viz.FOREVER)) VFrame.SetStatusText(frame, i + " selected. " + str(Selection)) break Alternative B: for i in BAR_Items: if BAR_Items[i] == A or SHAPE[i+"_SHP"] == A: if i in Selection: Selection.remove(i) BAR_Items[i].clearActions() BAR_Items[i].add(vizact.spinTo(axisAngle=[0,1,0,90],speed=300)) VFrame.SetStatusText(frame, i + " has been deselected. "+ str(Selection)) else: Selection.append(i) BAR_Items[i].add(vizact.spin(0,1,0,90,viz.FOREVER)) VFrame.SetStatusText(frame, i + " selected. " + str(Selection)) break Ok, I followed the suggestions and found a way of timing it. After measuring it 500 times, B (0.001279264 seconds) is faster than A (0.001966169 seconds) on average (the numbers are the average). A: One of the best ways to test efficiency is with the timeit module. I would put each alternative in a function, run timeit on each function, and compare. A: Ok here is a contrived way to look at the performance. Since we are trying to see the difference between using "continue" or pull the code inside the "if block .." Here is a small experiment. def f(): x = {'a':'b', 'c':'d', 'e':'d'} for l in x: if x[l] != 'd': continue print x def f1(): x = {'a':'b', 'c':'d', 'e':'d'} for l in x: if x[l] == 'd': print x import dis print dis.dis(f) print dis.dis(f1) Most of the operations are same and here is a small difference: In case of f: 56 POP_TOP 57 JUMP_ABSOLUTE 34 60 JUMP_FORWARD 1 (to 64) 63 POP_TOP 64 LOAD_FAST 0 (x) 67 PRINT_ITEM 68 PRINT_NEWLINE 69 JUMP_ABSOLUTE 34 72 POP_BLOCK 73 LOAD_CONST 0 (None) 76 RETURN_VALUE In case of f1: 56 POP_TOP 57 LOAD_FAST 0 (x) 60 PRINT_ITEM 61 PRINT_NEWLINE 62 JUMP_ABSOLUTE 34 65 POP_TOP 66 JUMP_ABSOLUTE 34 69 POP_BLOCK 70 LOAD_CONST 0 (None) 73 RETURN_VALUE Verdict Just one OP difference. Really not much right. There are equivalent. Base your decision on readability rather than performance. A: For code where performance isn't absolutely critical, ask yourself "which is more understandable" and use that as your answer. A difference of a few microseconds just isn't worth the time to fret over in scripted code.
Loop control, what is more efficient
Which one of the two alternatives below is more efficient? Any recommendations to further improve it? Alternative A: for i in BAR_Items: if BAR_Items[i] != A and SHAPE[i+"_SHP"] != A: continue if i in Selection: Selection.remove(i) BAR_Items[i].clearActions() BAR_Items[i].add(vizact.spinTo(axisAngle=[0,1,0,90],speed=300)) VFrame.SetStatusText(frame, i + " has been deselected. "+ str(Selection)) else: Selection.append(i) BAR_Items[i].add(vizact.spin(0,1,0,90,viz.FOREVER)) VFrame.SetStatusText(frame, i + " selected. " + str(Selection)) break Alternative B: for i in BAR_Items: if BAR_Items[i] == A or SHAPE[i+"_SHP"] == A: if i in Selection: Selection.remove(i) BAR_Items[i].clearActions() BAR_Items[i].add(vizact.spinTo(axisAngle=[0,1,0,90],speed=300)) VFrame.SetStatusText(frame, i + " has been deselected. "+ str(Selection)) else: Selection.append(i) BAR_Items[i].add(vizact.spin(0,1,0,90,viz.FOREVER)) VFrame.SetStatusText(frame, i + " selected. " + str(Selection)) break Ok, I followed the suggestions and found a way of timing it. After measuring it 500 times, B (0.001279264 seconds) is faster than A (0.001966169 seconds) on average (the numbers are the average).
[ "One of the best ways to test efficiency is with the timeit module. I would put each alternative in a function, run timeit on each function, and compare.\n", "Ok here is a contrived way to look at the performance. Since we are trying to see the difference between using \"continue\" or pull the code inside the \"i...
[ 5, 3, 0 ]
[]
[]
[ "loops", "performance", "python" ]
stackoverflow_0004101596_loops_performance_python.txt
Q: python memory leak, leaking frames I have this code to get the caller of my function's file name, line number, and function. It seems to be leaking frames though and I don't understand why. Is this just throwing me off and my leak must be elsewhere? rv = "(unknown file)", 0, "(unknown function)" for f in inspect.stack()[1:]: if __file__ in f: continue else: rv = f[1:4] break return rv I'm not saving a reference to the frame anywhere. But it's definitely frames that are leaking: > objcallgraph.show_most_common_types() >tuple 24798 >frame 9601 >... Update: My frames are definitely being leaked. I did the suggestion about gc.set_debug() and frames are very slowly going into the gc.garbage list. Not even close to how many are being created though as show in show_most_common_types(). I have a question about scope though, in the above, doesn't f go out of scope after the for loop? Because I just tried this: for f in range(20): l = 1 print f and it printed 19. So could it be my f in the for loop leaking? This is a reference graph of a frame reference that was in my gc.garbage list: Update2: It looks like the inspect module itself is holding references to the frames. This is an objectgraph of a backreference from a live frame, not one on the garbage list. Link here because it's too wide. Is there a way to clear the inspect module? Where the hell are these frames being saved =\ A: EDIT I just realized that's wrong, the f reference and f_back both point the same way. I'll leave it in case it inspires someone else: Each frame has an f_back pointer, so when you set f = inspect.stack()[1] then inspect.stack()[0][0].f_locals (which contains f) now has a reference to ...stack()[1] and ...stack()[1][0].f_back points to ...stack()[0][0]. So you created a circular reference which must be resolved by GC instead of simply by reference count. The GC is not tuned to deal with your rate of object creation so you consume more and more memory. You could probably eliminate the circular reference just by setting f = None on your way out of the function. That breaks the circular reference. A: Well I think I found the problem. It seems to be an issue with the inspect module and the underlying C code in a multi-threaded app. The module with the code above is being imported from different threads. And that 2nd graph points to the issue. The function listed here in the 3rd node down is inspect.getmodule(). I couldn't fit it all in there and had to do some cropping. (Pdb) objgraph.at(3510928) <cell at 0x359290: dict object at 0x3849c0> And inside the dict is all the frames (Pdb) objgraph.at(0x3849c0) {(<frame object at 0x97a288>, '/lib/python26.zip/logging/__init__.py'): <module 'logging' from '/lib/python26.zip/logging/__init__.py'>, (<frame object at 0x896288>, '/lib/python26.zip/logging/__init__.py'): <module 'logging' from '/lib/python26.zip/logging/__init__.py'>, (<frame object at 0xa621b0>, '/lib/python26.zip/logging/__init__.py'): <module 'logging' from '/lib/python26.zip/logging/__init__.py'>, (<frame object at 0x11266e8>, '/lib/python26.zip/logging/__init__.py'): <module 'logging' from '/lib/python26.zip/logging/__init__.py'>, ...} And if you get the outer frames of all those frames (Pdb) inspect.getouterframes(objgraph.at(0x97a288)) [(<frame object at 0x97a288>, '/lib/python26.zip/logging/__init__.py', 1028, 'debug', [' self._log(DEBUG, msg, args, **kwargs)\n'], 0), (<frame object at 0x794040>, '/lib/python26.zip/logging/__init__.py', 1505, 'debug', [' root.debug(*((msg,)+args), **kwargs)\n'], 0), (<frame object at 0x794e58>, '/mmc/src/core/controller/main.py', 1046, '__startCharge', [' self.chargeLock.release()\n'], 0), (<frame object at 0x5c4260>, '/mmc/src/core/controller/main.py', 1420, 'watchScheduleStartChargeCondition', [' ret = self.__startCharge(0, eventCode=eventCode)\n'], 0), (<frame object at 0x5c0dd0>, '/home/ephibian/Python2/_install/lib/python2.6/threading.py', 484, 'run', None, None), (<frame object at 0x5c3b48>, '/home/ephibian/Python2/_install/lib/python2.6/threading.py', 532, '__bootstrap_inner', None, None), (<frame object at 0x218170>, '/home/ephibian/Python2/_install/lib/python2.6/threading.py', 504, '__bootstrap', None, None)] They all point to the __bootstrap method in threading. I could be on the wrong track here, but the context of some of these frames are nowhere near where I'm calling the method I posted.
python memory leak, leaking frames
I have this code to get the caller of my function's file name, line number, and function. It seems to be leaking frames though and I don't understand why. Is this just throwing me off and my leak must be elsewhere? rv = "(unknown file)", 0, "(unknown function)" for f in inspect.stack()[1:]: if __file__ in f: continue else: rv = f[1:4] break return rv I'm not saving a reference to the frame anywhere. But it's definitely frames that are leaking: > objcallgraph.show_most_common_types() >tuple 24798 >frame 9601 >... Update: My frames are definitely being leaked. I did the suggestion about gc.set_debug() and frames are very slowly going into the gc.garbage list. Not even close to how many are being created though as show in show_most_common_types(). I have a question about scope though, in the above, doesn't f go out of scope after the for loop? Because I just tried this: for f in range(20): l = 1 print f and it printed 19. So could it be my f in the for loop leaking? This is a reference graph of a frame reference that was in my gc.garbage list: Update2: It looks like the inspect module itself is holding references to the frames. This is an objectgraph of a backreference from a live frame, not one on the garbage list. Link here because it's too wide. Is there a way to clear the inspect module? Where the hell are these frames being saved =\
[ "EDIT I just realized that's wrong, the f reference and f_back both point the same way. I'll leave it in case it inspires someone else:\nEach frame has an f_back pointer, so when you set f = inspect.stack()[1] then inspect.stack()[0][0].f_locals (which contains f) now has a reference to ...stack()[1] and ...stack(...
[ 1, 1 ]
[]
[]
[ "memory_leaks", "python" ]
stackoverflow_0004093139_memory_leaks_python.txt
Q: PyGTK: Controlling interface from within joined thread I have a thread in PyGTK, inside my mainloop. It's a Timer, so it needed to be joined with .join(). The problem is, I now cannot edit my UI from in that thread - change text and so on - because of the .join(). Is there a way I can change things from outside (well, you know what I mean) the mainloop? Thanks. A: instead of using a Timer thread, use glib.timeout_add to do your thing. It works together with gtk's mainloop and runs in the same thread, so you don't have to do anything special.
PyGTK: Controlling interface from within joined thread
I have a thread in PyGTK, inside my mainloop. It's a Timer, so it needed to be joined with .join(). The problem is, I now cannot edit my UI from in that thread - change text and so on - because of the .join(). Is there a way I can change things from outside (well, you know what I mean) the mainloop? Thanks.
[ "instead of using a Timer thread, use glib.timeout_add to do your thing.\nIt works together with gtk's mainloop and runs in the same thread, so you don't have to do anything special.\n" ]
[ 2 ]
[]
[]
[ "gtk", "join", "multithreading", "python" ]
stackoverflow_0004101861_gtk_join_multithreading_python.txt
Q: Is this a Python or SQL server bug? I am running the following: Windows 7, Python 2.5, and SQL server 2005, with SQLNCLI as provider. I have one table, its name is TABLE and its fields are FIELD0, FIELD1, FIELD2. You can find SQLNCLI.msi here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&displaylang=en I'm attemting to use a store procedure. Its purpose is to update a row, or insert it if it doesn't exist. All goes wrong when it reaches the insert statment, but the insertion succeeds. Here is the code: set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go create procedure [dbo].[TEST0] @FIELD0 varchar(200) as begin declare @exist varchar(MAX) set @exist = (select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0) if @exist is null begin insert into [TABLE] ([FIELD0],[FIELD1],[FIELD2]) values (@FIELD0,'FIELD1','FIELD2') select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0 return 10 end else select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0 end To see the bug run this Python code twice; the first time it fails, but the second time it succeeds: from win32com.client import Dispatch dbConn = Dispatch( "ADODB.Connection" ) dbConn.Open( "server=xx.xx.xx.xx; initial catalog=MYDB; user=myuser; password=mypass; provider=SQLNCLI" ) command = Dispatch( 'ADODB.Command' ) command.ActiveConnection = s.dbConn command.CommandText = "[TEST0]" command.CommandType = 4 param0 = command.CreateParameter ('@FIELD0',200,1,200,'VALUE') command.Parameters.Append( param0 ) print param0 (rs, result) = command.Execute() while not rs.EOF: dic = {} for field in rs.Fields : dic[str( field.name )] = str( field.value ) print dic rs.MoveNext() A: I fix it: set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go alter procedure [dbo].[TEST0] @FIELD0 varchar(200) as begin set nocount on <=============================add this declare @exist varchar(MAX) set @exist = (select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0) if @exist is null begin insert into [TABLE] ([FIELD0],[FIELD1],[FIELD2]) values (@FIELD0,'FIELD1','FIELD2') select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0 end else select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0 set nocount off <=============================add this end
Is this a Python or SQL server bug?
I am running the following: Windows 7, Python 2.5, and SQL server 2005, with SQLNCLI as provider. I have one table, its name is TABLE and its fields are FIELD0, FIELD1, FIELD2. You can find SQLNCLI.msi here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&displaylang=en I'm attemting to use a store procedure. Its purpose is to update a row, or insert it if it doesn't exist. All goes wrong when it reaches the insert statment, but the insertion succeeds. Here is the code: set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go create procedure [dbo].[TEST0] @FIELD0 varchar(200) as begin declare @exist varchar(MAX) set @exist = (select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0) if @exist is null begin insert into [TABLE] ([FIELD0],[FIELD1],[FIELD2]) values (@FIELD0,'FIELD1','FIELD2') select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0 return 10 end else select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0 end To see the bug run this Python code twice; the first time it fails, but the second time it succeeds: from win32com.client import Dispatch dbConn = Dispatch( "ADODB.Connection" ) dbConn.Open( "server=xx.xx.xx.xx; initial catalog=MYDB; user=myuser; password=mypass; provider=SQLNCLI" ) command = Dispatch( 'ADODB.Command' ) command.ActiveConnection = s.dbConn command.CommandText = "[TEST0]" command.CommandType = 4 param0 = command.CreateParameter ('@FIELD0',200,1,200,'VALUE') command.Parameters.Append( param0 ) print param0 (rs, result) = command.Execute() while not rs.EOF: dic = {} for field in rs.Fields : dic[str( field.name )] = str( field.value ) print dic rs.MoveNext()
[ "I fix it:\nset ANSI_NULLS ON\nset QUOTED_IDENTIFIER ON\ngo\n\nalter procedure [dbo].[TEST0]\n @FIELD0 varchar(200) \nas\nbegin\n set nocount on <=============================add this\n declare @exist varchar(MAX)\n\n set @exist = (select top 1 [FIELD0] from [TABLE] where [FIELD0] = @FIELD0)...
[ 0 ]
[]
[]
[ "python", "sql_server" ]
stackoverflow_0004102323_python_sql_server.txt
Q: Where can you download an installer file for PyQT? Where can you download an installer file for PyQT? I am unable to figure out how to build it with the source code. Is there a prepackaged version? A: Here (http://www.riverbankcomputing.co.uk/software/pyqt/download, found by doing a google search for pyqt installer :-) )
Where can you download an installer file for PyQT?
Where can you download an installer file for PyQT? I am unable to figure out how to build it with the source code. Is there a prepackaged version?
[ "Here (http://www.riverbankcomputing.co.uk/software/pyqt/download, found by doing a google search for pyqt installer :-) )\n" ]
[ 2 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0004102509_pyqt_python.txt
Q: Find "string" in Text File - Add it to Excel File Using Python I ran a grep command and found several hundred instances of a string in a large directory of data. This file is 2 MB and has strings that I would like to extract out and put into an Excel file for easy access later. The part that I'm extracting is a path to a data file I need to work on later. I have been reading about Python lately and thought I could somehow do this extraction automatically. But I'm a bit stumped how to start. I have this so far: data = open("C:\python27\text.txt").read() if "string" in data: But then I'm not sure what to use to get out of the file what I want. Anything for a beginner to chew on? EDIT Here is some more info on what I was looking for. I have several hundred lines in a text file. Each line has a path and some strings like this: /path/to/file:STRING=SOME_STRING, ANOTHER_STRING What I would like from these lines are the paths of those lines with a specific "STRING=SOME_STRING". For example if the line looks like this, I want the path (/path/to/file) to be extracted to another file: /path/to/file:STRING=SOME_STRING A: All this is quite easily done with standard Python, but for "excel" (xls,or xlsx) files -- you'd have to install a third party library for that. However, if you need just a 2D table that cna open up on a spreadsheed you can use Comma Separated Values (CSV) files - these are comaptible with Excel and other spreadsheet software, and comes integrated in Python. As for searching a string inside a file, it is straightforward. You may not even need regular expressions for most things. What information do you want along with the string? Also, the "os" module onthse standardlib has some functions to list all files in a directory, or in a directory tree. The most straightforward is os.listdir(path) String methods like "count" and "find" can be used beyond "in" to locate the string in a file, or count the number of ocurrences. And finally, the "CSV" module can write a properly formated file to read in ay spreadsheet. Along the away, you may abuse python's buit-in list objects as an easy way to manipulate data sets around. Here is a sample programa that counts strings given in the command line found in files in a given directory,, and assembles a .CSV table with them: # -*- coding: utf-8 -*- import csv import sys, os output_name = "count.csv" def find_in_file(path, string_list): count = [] file_ = open(path) data = file_.read() file_.close() for string in string_list: count.append(data.count(string)) return count def main(): if len(sys.argv) < 3: print "Use %s directory_path <string1>[ string2 [...]])\n" % __package__ sys.exit(1) target_dir = sys.argv[1] string_list = sys.argv[2:] csv_file = open(output_name, "wt") writer = csv.writer(csv_file) header = ["Filename"] + string_list writer.writerow(header) for filename in os.listdir(target_dir): path = os.path.join(target_dir, filename) if not os.path.isfile(path): continue line = [filename] + find_in_file(path, string_list) writer.writerow(line) csv_file.close() if __name__=="__main__": main() A: The steps to do this are as follows: Make a list of all files in the directory (This isn't necessary if you're only interested in a single file) Extract the names of those files that you're interested in In a loop, read in those files line by line See if the line matches your pattern Extract the part of the line before the first : character So, the code would look something like this, provided your text files are formatted the way you've shown in the question and that this format is reliably correct: import sys, os, glob dir_path = sys.argv[1] if dir_path[-1] != os.sep: dir_path+=os.sep file_list = glob.glob(dir_path+'*.txt') #use standard *NIX wildcards to get your file names, in this case, all the files with a .txt extension with open('out_file.csv', 'w') as out_file: for filename in file_list: with open(filename, 'r') as in_file: for line in in_file: if 'STRING=SOME_STRING' in line: out_file.write(line.split(':')[0]+'\n') This program would be run as python extract_paths.py path/to/directory and would give you a file called out_file.csv in your current directory. This file can then be imported into Excel as a CSV file. If your input is less reliable than you've suggested, regular expressions might be a better choice.
Find "string" in Text File - Add it to Excel File Using Python
I ran a grep command and found several hundred instances of a string in a large directory of data. This file is 2 MB and has strings that I would like to extract out and put into an Excel file for easy access later. The part that I'm extracting is a path to a data file I need to work on later. I have been reading about Python lately and thought I could somehow do this extraction automatically. But I'm a bit stumped how to start. I have this so far: data = open("C:\python27\text.txt").read() if "string" in data: But then I'm not sure what to use to get out of the file what I want. Anything for a beginner to chew on? EDIT Here is some more info on what I was looking for. I have several hundred lines in a text file. Each line has a path and some strings like this: /path/to/file:STRING=SOME_STRING, ANOTHER_STRING What I would like from these lines are the paths of those lines with a specific "STRING=SOME_STRING". For example if the line looks like this, I want the path (/path/to/file) to be extracted to another file: /path/to/file:STRING=SOME_STRING
[ "All this is quite easily done with standard Python, but for \"excel\" (xls,or xlsx) files -- you'd have to install a third party library for that. However, if you need just a 2D table that cna open up on a spreadsheed you can use Comma Separated Values (CSV) files - these are comaptible with Excel and other spread...
[ 3, 1 ]
[]
[]
[ "excel", "grep", "python", "string" ]
stackoverflow_0004099792_excel_grep_python_string.txt
Q: python config parser cache to reduce I/O on an embedded system In my project we use a config file that's parsed with the configparser module. Is there any way to cache the entire config file, and then use configparser methods to read it from memory? I'm hoping to not have to just store the config variables in a dictionary and look them up that way since using the configparser is really tightly coupled with a lot of our app and I'm hoping I can just change where the config is located to point to memory instead of a file name. Is this possible? A: Yep. If you use the StringIO module, you can create a file-like object that is in memory. Then you can use the method (ConfigParser inherits from RawConfigParser): RawConfigParser.readfp(fp[, filename]) Read and parse configuration data from the file or file-like object in fp (only the readline() method is used). If filename is omitted and fp has a name attribute, that is used for filename; the default is .
python config parser cache to reduce I/O on an embedded system
In my project we use a config file that's parsed with the configparser module. Is there any way to cache the entire config file, and then use configparser methods to read it from memory? I'm hoping to not have to just store the config variables in a dictionary and look them up that way since using the configparser is really tightly coupled with a lot of our app and I'm hoping I can just change where the config is located to point to memory instead of a file name. Is this possible?
[ "Yep. If you use the StringIO module, you can create a file-like object that is in memory. \nThen you can use the method (ConfigParser inherits from RawConfigParser): \n\nRawConfigParser.readfp(fp[, filename])\n Read and parse configuration data from the file or file-like object in fp (only the readline() m...
[ 4 ]
[]
[]
[ "configparser", "configuration_files", "file_io", "python" ]
stackoverflow_0004102761_configparser_configuration_files_file_io_python.txt
Q: Odd python search-path behavior, what's going wrong here? We have an application based on Excel 2003 and Python 2.4 on Windows XP 32bit. The application consists of a large collection of Python functions which can be called from a number of excel worksheets. We've notcied an anomolous behavior which is that sometimes in the middle of one of these calls the python interpreter will start hunting around for modules which almost certainly are already loaded and in memory. We know this because we were able to hook-up Sysinternal's Process Monitor to the process and observe that from time to time the process (when called) starts hunting around a bunch of directories and eggs for certain .py files. The obvious thing to try is to see if the python search-path had become modified, however we found this not to be the case. It's exactly what we'd expect. The odd thing is that: The occasions on which this searching behavior was triggered appears to be random, i.e. it did not happen every time or with any noticable pattern. The behavior did not affect the result of the function. It returned the same value irrespective of whether this file searching behavior was triggered. The folders that were being scanned were non-existant (e.g. J:/python-eggs ) on a machine where J-drive contained no-such folder. Naturally procmon reports that this generated a file-not found error. It's all very mysterious so I dont expect anybody to be able to provide a definitive answer as to what might be going wrong. I would appreciate any suggestions about how this problem might be debugged. Thanks! Answers to comments All the things that are being searched for are actual, known python files which exist in the main project .egg file. The odd thing is that at the time they are being searched-for those particuar modules have already been imported. They must be in memory in order for the process to work. Yes, this affects performance because sometimes this searching behavior tries to hit network drives. Also by searching eggs which couldnt possibly contain certain modules it the process gets interrupted by the corporate mandated virus-scanner. That slows down what would normally be a harmless and instant interruption. This is stock python 2.4.4. No modifications. A: Python programs can import modules at any time, not just during program load. Try searching the modules you are using for import. If this doesn't work, you can write an import hook to catch and report all attempted imports before they occur. For example, if you run this before everything else, you will get a dump of every attempted import and its source: import sys, traceback class ImportDebugger: def find_module(self, fullname, path=None): print "Attempting to import %s:" % fullname traceback.print_stack() sys.meta_path.insert(0, ImportDebugger()) A: "Python functions which can be called from a number of excel worksheets" And you're not blaming Excel for randomly running Python modules? Why not? How have you proven that Excel is behaving properly?
Odd python search-path behavior, what's going wrong here?
We have an application based on Excel 2003 and Python 2.4 on Windows XP 32bit. The application consists of a large collection of Python functions which can be called from a number of excel worksheets. We've notcied an anomolous behavior which is that sometimes in the middle of one of these calls the python interpreter will start hunting around for modules which almost certainly are already loaded and in memory. We know this because we were able to hook-up Sysinternal's Process Monitor to the process and observe that from time to time the process (when called) starts hunting around a bunch of directories and eggs for certain .py files. The obvious thing to try is to see if the python search-path had become modified, however we found this not to be the case. It's exactly what we'd expect. The odd thing is that: The occasions on which this searching behavior was triggered appears to be random, i.e. it did not happen every time or with any noticable pattern. The behavior did not affect the result of the function. It returned the same value irrespective of whether this file searching behavior was triggered. The folders that were being scanned were non-existant (e.g. J:/python-eggs ) on a machine where J-drive contained no-such folder. Naturally procmon reports that this generated a file-not found error. It's all very mysterious so I dont expect anybody to be able to provide a definitive answer as to what might be going wrong. I would appreciate any suggestions about how this problem might be debugged. Thanks! Answers to comments All the things that are being searched for are actual, known python files which exist in the main project .egg file. The odd thing is that at the time they are being searched-for those particuar modules have already been imported. They must be in memory in order for the process to work. Yes, this affects performance because sometimes this searching behavior tries to hit network drives. Also by searching eggs which couldnt possibly contain certain modules it the process gets interrupted by the corporate mandated virus-scanner. That slows down what would normally be a harmless and instant interruption. This is stock python 2.4.4. No modifications.
[ "Python programs can import modules at any time, not just during program load. Try searching the modules you are using for import.\nIf this doesn't work, you can write an import hook to catch and report all attempted imports before they occur. For example, if you run this before everything else, you will get a dump...
[ 2, 1 ]
[]
[]
[ "excel", "python", "windows" ]
stackoverflow_0004099817_excel_python_windows.txt
Q: python: avoiding bug with variable use before assignment in a loop for element in container: # some code here temp_variable = f1(element) # more code # much later in the code for element in container: # some code another_variable = g(temp_variable) # more code temp_variable = f2(element) # more code In the second for loop, I accidentally used variable temp_variable before it's assigned. Normally, I'd get NameError exception, but here unfortunately it survived, valid and initialized, from the previous loop. Are there any coding practices, IDE tools, etc., that would help prevent such bugs? Btw, I was thinking it might be better if variables inside the loop stayed didn't survive past the end of the loop. EDIT @Ignacio Vazquez-Abrams: If I understood correctly, you suggest not to use the same variable name as a local variable in multiple loops. I have two problems with that: Often the most descriptive variable name to use happens to be the same in multiple loops. Say, I used something like unique_visitor_count. I wouldn't want to ban this variable from being used further down in the code, in another loop. When working on existing code, it would be quite onerous to check if any new variable name I want to use has already been used before. A: If it's 'much later' in the code, then you should probably break the code up into multiple functions. It sounds like the function is too long. Another tip is to use meaningful names. temp_variable, tmp, temp, etc. are not good names. Use a name that describes the value that it points to. This will eliminate a large class of potential occurrences of this problem. Also, list comprehensions don't leak their variables so if you can use them, than that's just one more reason that they're generally better. They are not applicable to all situations though. A: If you want the variables to go away after the loop ends, refactor the loop into a function. That way, after the function is called, the variables will go out of scope and will be garbage collected. As for coding practices that would prevent such bugs, I'd recommend that you a.) put these types of functions that require temporary variables in functions, and b.) unit test (since the second for loop would not execute by itself, a unit test for just that for loop would catch your error). A: Others have suggested putting code in functions if you don't want it to leak local variables. I would like to suggest that you put these functions inside a function. This way they have access to the variables defined in the outer function, so you don't have to pass them in. Just define inner functions as you need them and invoke them right away, unless of course they can be reused. def myfunc(a): i = 10 def infunc(): for i in range(a): print i, infunc() print i myfunc(5) >>> 0 1 2 3 4 10 This isn't particularly pretty, but it does work, and you shouldn't need it very often. A: Try adding del temp_variable when you no longer want it. A: Try running pylint. It won't catch errors like this directly, but it will tell you when you aren't using a variable's value. A: Are there any coding practices, IDE tools, etc., that would help prevent such bugs? Design first. Code second.
python: avoiding bug with variable use before assignment in a loop
for element in container: # some code here temp_variable = f1(element) # more code # much later in the code for element in container: # some code another_variable = g(temp_variable) # more code temp_variable = f2(element) # more code In the second for loop, I accidentally used variable temp_variable before it's assigned. Normally, I'd get NameError exception, but here unfortunately it survived, valid and initialized, from the previous loop. Are there any coding practices, IDE tools, etc., that would help prevent such bugs? Btw, I was thinking it might be better if variables inside the loop stayed didn't survive past the end of the loop. EDIT @Ignacio Vazquez-Abrams: If I understood correctly, you suggest not to use the same variable name as a local variable in multiple loops. I have two problems with that: Often the most descriptive variable name to use happens to be the same in multiple loops. Say, I used something like unique_visitor_count. I wouldn't want to ban this variable from being used further down in the code, in another loop. When working on existing code, it would be quite onerous to check if any new variable name I want to use has already been used before.
[ "If it's 'much later' in the code, then you should probably break the code up into multiple functions. It sounds like the function is too long.\nAnother tip is to use meaningful names. temp_variable, tmp, temp, etc. are not good names. Use a name that describes the value that it points to. This will eliminate a lar...
[ 8, 4, 4, 3, 0, 0 ]
[]
[]
[ "coding_style", "namespaces", "python" ]
stackoverflow_0004103031_coding_style_namespaces_python.txt
Q: Using Nose to test txmongo dependent code I want to use nose to test an application that I am writing using twisted and txmongo. I can't even get simple use cases like the following working: from nose.twistedtools import reactor, deferred, threaded_reactor import logging from twisted.internet import defer import txmongo log = logging.getLogger("common.test.test_db") conn = txmongo.lazyMongoConnectionPool('localhost', 27017, 4) @deferred() def test_mongo(): tdb = conn.test @defer.inlineCallbacks def cb(oid): assert oid obj = yield tdb.test.find({"_id":oid}) log.error("In callback") assert obj d = tdb.test.save({"s":1, "b":2}) d.addCallback(cb) return d However, this always return the following: E ====================================================================== ERROR: common.test.test_db.test_mongo ---------------------------------------------------------------------- Traceback (most recent call last): File "/Volumes/Users/jce/.pyenv/celery/lib/python2.6/site-packages/nose/case.py", line 186, in runTest self.test(*self.arg) File "/Volumes/Users/jce/.pyenv/celery/lib/python2.6/site-packages/nose/twistedtools.py", line 138, in errback failure.raiseException() File "/Volumes/Users/jce/.pyenv/celery/lib/python2.6/site-packages/twisted/python/failure.py", line 326, in raiseException raise self.type, self.value, self.tb RuntimeWarning: not connected ---------------------------------------------------------------------- Ran 1 test in 0.006s FAILED (errors=1) I tried manually adding a threaded_reactor() call, but it didn't help. edit I removed the "lazy" connections, and modified the code, and now it works... I'm still curious as to why the "lazy" didn't work. The working code is as follows: dbconn = txmongo.MongoConnectionPool('localhost', 27017, 4) @deferred() def test_mongo(): @defer.inlineCallbacks def cb(conn): tdb = conn.test oid = yield tdb.test.save({"s":1, "b":2}) assert oid log.error(str(oid)) obj = yield tdb.test.find({"_id":oid}) assert obj log.error(str(obj)) dbconn.addCallback(cb) return dbconn A: MongoConnectionPool will return a deferred, which is fired when the connection is established passing the connection handler as argument to the callback. You should conn = yield MongoConnectionPool(). lazyMongoConnectionPool will return the connection handler directly, without waiting for the connection to be established. Lazy is usually used by web servers and other services that doesn't require immediate connection when your service starts. If you want to do so, don't use the lazy method.
Using Nose to test txmongo dependent code
I want to use nose to test an application that I am writing using twisted and txmongo. I can't even get simple use cases like the following working: from nose.twistedtools import reactor, deferred, threaded_reactor import logging from twisted.internet import defer import txmongo log = logging.getLogger("common.test.test_db") conn = txmongo.lazyMongoConnectionPool('localhost', 27017, 4) @deferred() def test_mongo(): tdb = conn.test @defer.inlineCallbacks def cb(oid): assert oid obj = yield tdb.test.find({"_id":oid}) log.error("In callback") assert obj d = tdb.test.save({"s":1, "b":2}) d.addCallback(cb) return d However, this always return the following: E ====================================================================== ERROR: common.test.test_db.test_mongo ---------------------------------------------------------------------- Traceback (most recent call last): File "/Volumes/Users/jce/.pyenv/celery/lib/python2.6/site-packages/nose/case.py", line 186, in runTest self.test(*self.arg) File "/Volumes/Users/jce/.pyenv/celery/lib/python2.6/site-packages/nose/twistedtools.py", line 138, in errback failure.raiseException() File "/Volumes/Users/jce/.pyenv/celery/lib/python2.6/site-packages/twisted/python/failure.py", line 326, in raiseException raise self.type, self.value, self.tb RuntimeWarning: not connected ---------------------------------------------------------------------- Ran 1 test in 0.006s FAILED (errors=1) I tried manually adding a threaded_reactor() call, but it didn't help. edit I removed the "lazy" connections, and modified the code, and now it works... I'm still curious as to why the "lazy" didn't work. The working code is as follows: dbconn = txmongo.MongoConnectionPool('localhost', 27017, 4) @deferred() def test_mongo(): @defer.inlineCallbacks def cb(conn): tdb = conn.test oid = yield tdb.test.save({"s":1, "b":2}) assert oid log.error(str(oid)) obj = yield tdb.test.find({"_id":oid}) assert obj log.error(str(obj)) dbconn.addCallback(cb) return dbconn
[ "MongoConnectionPool will return a deferred, which is fired when the connection is established passing the connection handler as argument to the callback. You should conn = yield MongoConnectionPool().\nlazyMongoConnectionPool will return the connection handler directly, without waiting for the connection to be est...
[ 1 ]
[]
[]
[ "nose", "python", "twisted" ]
stackoverflow_0004100455_nose_python_twisted.txt
Q: Integer to Unique String There's probably someone else who asked a similar question, but I didn't take much time to search for this, so just point me to it if someone's already answered this. I'm trying to take an integer (or long) and turn it into a string, in a very specific way. The goal is essentially to split the integer into 8-bit segments, then take each of those segments and get the corresponding ASCII character for that chunk, then glue the chunks together. This is easy to implement, but I'm not sure I'm going about it in the most efficient way. >>> def stringify(integer): output = "" part = integer & 255 while integer != 0: output += chr(part) integer = integer >> 8 return output >>> stringify(10) '\n' >>> stringify(10 << 8 | 10) '\n\n' >>> stringify(32) ' ' Is there a more efficient way to do this? Is this built into Python? EDIT: Also, as this will be run sequentially in a tight loop, is there some way to streamline it for such use? >>> for n in xrange(1000): ## EXAMPLE! print stringify(n) ... A: struct can easily do this for integers up to 64 bits in size. Any larger will require you to carve the number up first. >>> struct.pack('>Q', 12345678901234567890) '\xabT\xa9\x8c\xeb\x1f\n\xd2'
Integer to Unique String
There's probably someone else who asked a similar question, but I didn't take much time to search for this, so just point me to it if someone's already answered this. I'm trying to take an integer (or long) and turn it into a string, in a very specific way. The goal is essentially to split the integer into 8-bit segments, then take each of those segments and get the corresponding ASCII character for that chunk, then glue the chunks together. This is easy to implement, but I'm not sure I'm going about it in the most efficient way. >>> def stringify(integer): output = "" part = integer & 255 while integer != 0: output += chr(part) integer = integer >> 8 return output >>> stringify(10) '\n' >>> stringify(10 << 8 | 10) '\n\n' >>> stringify(32) ' ' Is there a more efficient way to do this? Is this built into Python? EDIT: Also, as this will be run sequentially in a tight loop, is there some way to streamline it for such use? >>> for n in xrange(1000): ## EXAMPLE! print stringify(n) ...
[ "struct can easily do this for integers up to 64 bits in size. Any larger will require you to carve the number up first.\n>>> struct.pack('>Q', 12345678901234567890)\n'\\xabT\\xa9\\x8c\\xeb\\x1f\\n\\xd2'\n\n" ]
[ 3 ]
[]
[]
[ "ascii", "python" ]
stackoverflow_0004103631_ascii_python.txt
Q: Need a regex :( I'm using Python and I need to be able to take a string of the form abc | pqr | [1,2,3,4,5] and get the actual array of integers [1,2,3,4,5] from it. Any suggestions? A: Assuming the abc | pqr | part is literal characters, you want: import re import ast m = re.match(r"abc \| pqr \| (\[[-0-9,]*\])", inString) if m is not None: theList = ast.literal_eval(m.group(1)) Use search instead of match if you want to skip over leading non-matching characters. A: The following regex will match the array of numbers, probably not perfect but that's my stab. Then you should be able to reference it with $1, not too familiar with pythons matcher though. (\[.*\]) A: import re import ast s = "abc | pqr | [1,2,3,4,5]" r = re.compile('\| (\[.*\])') m = r.search(s) if m: print ast.literal_eval(m.group(1)) A: Another variant without using literal_eval. import re matched = re.search(r'\[([0-9,]+)\]', "abc | pqr | [1,2,3,4,5]") if matched: print map(int, matched.group(1).split(',')) # or if your into list comprehensions print [int(i) for i in matched.group(1).split(',')] A: The regex \[([^\]]+)\] will match the numbers inside the braces. Then split the result: import re str="abc | pqr | [1,2,3,4,5]" reg=re.compile('\[([^\]]+)\]') match=reg.search(s) list=match.group(1).split() list=['1,2,3,4,5']
Need a regex :(
I'm using Python and I need to be able to take a string of the form abc | pqr | [1,2,3,4,5] and get the actual array of integers [1,2,3,4,5] from it. Any suggestions?
[ "Assuming the abc | pqr | part is literal characters, you want:\nimport re\nimport ast\n\nm = re.match(r\"abc \\| pqr \\| (\\[[-0-9,]*\\])\", inString)\nif m is not None:\n theList = ast.literal_eval(m.group(1))\n\nUse search instead of match if you want to skip over leading non-matching characters.\n", "The f...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004103544_python_regex.txt
Q: When instancing an imported "class" from a package, how can i avoid using the package.class() declaration? I'm kinda new to Python, so i'm still lost in the whole namespace thing. I've created a package, with the init file in it and also a classname.py file, with the class, obviously. For instance: from parachute import container, emitter I tried to instance the class Container directly, but it gave me an error, so i had to instance it as container.Container(). How can i avoid doing this? Basically, what i want to do is to import a class from a package and avoid typing the package name and/or the file name. Thanks in advance, and please let me know if the question isn't clear enough. UPDATE The structure i have is: - parachute -- init.py -- container.py Serves as a controller, i'd say, instancing, calling and glueing all the other parts together. -- sparkles.py Has two classes: Sparkle and Sparkles. Sparkle is a single element, with only one property so far, and Sparkles serves as a collection. Sparkles() belongs to the Emitter, and Sparkle() belongs to Sparkles(). -- emitter.py Emitter could be seen as the user entity. It has a name and an uid, it belongs to a Container and the Container belongs to it. Now, from outside the package i'm calling Container and passing some arguments, and the Container instances and distributes the arguments as it needs. I have the impression that this isn't the best way to do what i need to do, which is: Create a collection of sparkles, owned by the emitter. A: from module import Class classInst = Class() This will work if your class is in module.py A: Don't put the class in it's own file. Put Container and Emitter directly in parachute.py. You can then do from parachute import Container, Emitter or import parachute container = parachute.Container() This essentially boils down to "Python isn't Java so for best results, don't treat it like it is" ;)
When instancing an imported "class" from a package, how can i avoid using the package.class() declaration?
I'm kinda new to Python, so i'm still lost in the whole namespace thing. I've created a package, with the init file in it and also a classname.py file, with the class, obviously. For instance: from parachute import container, emitter I tried to instance the class Container directly, but it gave me an error, so i had to instance it as container.Container(). How can i avoid doing this? Basically, what i want to do is to import a class from a package and avoid typing the package name and/or the file name. Thanks in advance, and please let me know if the question isn't clear enough. UPDATE The structure i have is: - parachute -- init.py -- container.py Serves as a controller, i'd say, instancing, calling and glueing all the other parts together. -- sparkles.py Has two classes: Sparkle and Sparkles. Sparkle is a single element, with only one property so far, and Sparkles serves as a collection. Sparkles() belongs to the Emitter, and Sparkle() belongs to Sparkles(). -- emitter.py Emitter could be seen as the user entity. It has a name and an uid, it belongs to a Container and the Container belongs to it. Now, from outside the package i'm calling Container and passing some arguments, and the Container instances and distributes the arguments as it needs. I have the impression that this isn't the best way to do what i need to do, which is: Create a collection of sparkles, owned by the emitter.
[ "from module import Class\nclassInst = Class()\n\nThis will work if your class is in module.py\n", "Don't put the class in it's own file. Put Container and Emitter directly in parachute.py. \nYou can then do\nfrom parachute import Container, Emitter\n\nor \nimport parachute\n\ncontainer = parachute.Container()\n\...
[ 2, 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0004103763_class_python.txt
Q: Sending an Email with python using the SMTP Library import smtplib def prompt(prompt): return raw_input(prompt).strip() fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() print "Enter message, end with ^D (Unix) or ^Z (Windows):" msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) while 1: try: line = raw_input() except EOFError: break if not line: break msg = msg + line print "Message length is " + repr(len(msg)) server = smtplib.SMTP('smtp.live.com:25') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() I'm trying to send an Email using that example, but it doesnt work, I dont get any error it just doesn't send anything, I'm trying to send it to a hotmail email. Any help will be appreciated, Thanks. A: Your call to smtplib.SMTP() uses invalid arguments. According to the smtplib docs: SMTP([host[, port[, local_hostname[, timeout]]]]) So, the SMTP constructor takes the optional arguments for hostname, port etc. But you've passed port and hostname as one argument (server = smtplib.SMTP('smtp.live.com:25')). Provided you have everything else right, if you change that line to read server = smtplib.SMTP('smtp.live.com', 25). If your server requires authentication (and I suspect it does), before you actually send the email you'll want to call server.login(user, password) to login so you can actually send the message.
Sending an Email with python using the SMTP Library
import smtplib def prompt(prompt): return raw_input(prompt).strip() fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() print "Enter message, end with ^D (Unix) or ^Z (Windows):" msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) while 1: try: line = raw_input() except EOFError: break if not line: break msg = msg + line print "Message length is " + repr(len(msg)) server = smtplib.SMTP('smtp.live.com:25') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() I'm trying to send an Email using that example, but it doesnt work, I dont get any error it just doesn't send anything, I'm trying to send it to a hotmail email. Any help will be appreciated, Thanks.
[ "Your call to smtplib.SMTP() uses invalid arguments. According to the smtplib docs:\n\nSMTP([host[, port[, local_hostname[,\n timeout]]]])\n\nSo, the SMTP constructor takes the optional arguments for hostname, port etc. But you've passed port and hostname as one argument (server = smtplib.SMTP('smtp.live.com:25'))...
[ 2 ]
[]
[]
[ "email", "python", "smtp" ]
stackoverflow_0004103317_email_python_smtp.txt
Q: Help with Tkinter in py2exe I'm trying to convert a basic tkinter GUI program to an .exe using py2exe. However I've run into an error using the following conversion script. # C:\Python26\test_hello_con.py py2exe from distutils.core import setup import py2exe setup(windows=[r'C:\Python26\py2exe_test_tk.py']) C:\Python26\py2exe_test_tk.py is the following code import Tkinter as tk root = tk.Tk() root.title("Test") label1 = tk.Label(root,text="Hello!",font=('arial', 10, 'bold'), bg='lightblue') label1.pack(ipadx=100, ipady=100) root.mainloop() This is the error I get when I try to run the newly created .exe Traceback (most recent call last): File "py2exe_test_tk.py", line 4, in <module> File "Tkinter.pyc", line 1643, in __init__ _tkinter.TclError: Can't find a usable init.tcl in the following directories: {C:/Users/My_Name/lib/tcl8.5} {C:/Users/My_Name/lib/tcl8.5} C:/Users/lib/tcl8.5 {C:/Users/My_Name/library} C:/Users/library C:/Users/tcl8.5.8/library C:/tcl8.5.8/library This probably means that Tcl wasn't installed properly. I'm pretty sure it's something in my conversion script thats giving me problems. What did I omit? Or does someone have an example of what the conversion script would look like for a tkinter GUI program? Also is it possible to divert the output .exe files to my desktop? EDIT: The error report said that I was missing init.tcl from {C:/Users/My_name/lib/tcl8.5}. So i made that directory and put a copy of init.tcl there. Now when I try to run the .exe it states that MSVCR90.dll is missing from my computer and is needed to run my program. Also this is python 2.6.5 on Windows 7. A: Such errors in Unix world are usually due to incorrect PATH settings or/and incorrectly installed third party modules (the GUI ones you're using). Have you seen this post: py2exe fails to generate an executable ?
Help with Tkinter in py2exe
I'm trying to convert a basic tkinter GUI program to an .exe using py2exe. However I've run into an error using the following conversion script. # C:\Python26\test_hello_con.py py2exe from distutils.core import setup import py2exe setup(windows=[r'C:\Python26\py2exe_test_tk.py']) C:\Python26\py2exe_test_tk.py is the following code import Tkinter as tk root = tk.Tk() root.title("Test") label1 = tk.Label(root,text="Hello!",font=('arial', 10, 'bold'), bg='lightblue') label1.pack(ipadx=100, ipady=100) root.mainloop() This is the error I get when I try to run the newly created .exe Traceback (most recent call last): File "py2exe_test_tk.py", line 4, in <module> File "Tkinter.pyc", line 1643, in __init__ _tkinter.TclError: Can't find a usable init.tcl in the following directories: {C:/Users/My_Name/lib/tcl8.5} {C:/Users/My_Name/lib/tcl8.5} C:/Users/lib/tcl8.5 {C:/Users/My_Name/library} C:/Users/library C:/Users/tcl8.5.8/library C:/tcl8.5.8/library This probably means that Tcl wasn't installed properly. I'm pretty sure it's something in my conversion script thats giving me problems. What did I omit? Or does someone have an example of what the conversion script would look like for a tkinter GUI program? Also is it possible to divert the output .exe files to my desktop? EDIT: The error report said that I was missing init.tcl from {C:/Users/My_name/lib/tcl8.5}. So i made that directory and put a copy of init.tcl there. Now when I try to run the .exe it states that MSVCR90.dll is missing from my computer and is needed to run my program. Also this is python 2.6.5 on Windows 7.
[ "Such errors in Unix world are usually due to incorrect PATH settings or/and incorrectly installed third party modules (the GUI ones you're using). Have you seen this post: py2exe fails to generate an executable ?\n" ]
[ 0 ]
[]
[]
[ "py2exe", "python", "tkinter", "user_interface" ]
stackoverflow_0004104074_py2exe_python_tkinter_user_interface.txt
Q: What is the vim feature: --enable-pythoninterp I am going to build vim and see that it supports the pythoninterp feature by --enable-pythoninterp. What is it? Since I am a big Python fan, I'd like to know more about it. And also, what's the --with-python-config-dir=PATH for? A: vim supports scripting in various languages, Python being one of them. See :h python for more details.
What is the vim feature: --enable-pythoninterp
I am going to build vim and see that it supports the pythoninterp feature by --enable-pythoninterp. What is it? Since I am a big Python fan, I'd like to know more about it. And also, what's the --with-python-config-dir=PATH for?
[ "vim supports scripting in various languages, Python being one of them. See :h python for more details.\n" ]
[ 8 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0004104202_python_vim.txt
Q: Thread locals in Python - negatives, with regards to scalability? I'm wondering if there are some serious implications I might be creating for myself by using thread locals. I noticed that in the case of Flask, they use thread locals, and mention that it can cause issues with servers that aren't built with threads in mind. Is this an outdated concern? I'm using thread locals with Django for a few things, deploying with NGINX in front of UWSGI, or Gunicorn, on Ubuntu 10.04 with Postgres (not that the OS or DB probably matter, but just for clarity). Do I need to be worried? A: Threadlocals aren't the most robust or secure way to do things - check out this note, for instance. [ Though also see Glenn's comment, below ] I suppose if you have coded cleanly, with the idea that you're putting stuff into a big global pot of info, accepting unguaranteed data consistency in those threaded locals and taking care to avoid race conditions, etc, etc, you might well be ok. But, even with that in mind, there's still the 'magic'ness of threaded local vars, so documenting clearly what the heck is going on and any time a threadedlocal var is used might help you/future developers of the codebase down the line.
Thread locals in Python - negatives, with regards to scalability?
I'm wondering if there are some serious implications I might be creating for myself by using thread locals. I noticed that in the case of Flask, they use thread locals, and mention that it can cause issues with servers that aren't built with threads in mind. Is this an outdated concern? I'm using thread locals with Django for a few things, deploying with NGINX in front of UWSGI, or Gunicorn, on Ubuntu 10.04 with Postgres (not that the OS or DB probably matter, but just for clarity). Do I need to be worried?
[ "Threadlocals aren't the most robust or secure way to do things - check out this note, for instance. [ Though also see Glenn's comment, below ]\nI suppose if you have coded cleanly, with the idea that you're putting stuff into a big global pot of info, accepting unguaranteed data consistency in those threaded local...
[ 0 ]
[]
[]
[ "django", "multithreading", "python", "thread_local" ]
stackoverflow_0004103741_django_multithreading_python_thread_local.txt