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: Exposing a "dumbed-down", read-only instance of a Model in GAE Does anyone know a clever way, in Google App Engine, to return a wrapped Model instance that only exposes a few of the original properties, and does not allow saving the instance back to the datastore? I'm not looking for ways of actually enforcing these rules, obviously it'll still be possible to change the instance by digging through its __dict__ etc. I just want a way to avoid accidental exposure/changing of data. My initial thought was to do this (I want to do this for a public version of a User model): class PublicUser(db.Model): display_name = db.StringProperty() @classmethod def kind(cls): return 'User' def put(self): raise SomeError() Unfortunately, GAE maps the kind to a class early on, so if I do PublicUser.get_by_id(1) I will actually get a User instance back, not a PublicUser instance. Also, the idea is that it should at least appear to be a Model instance so that I can pass it around to code that does not know about the fact that it is a "dumbed-down" version. Ultimately I want to do this so that I can use my generic data exposure functions on the read-only version, so that they only expose public information about the user. Update I went with icio's solution. Here's the code I wrote for copying the properties from the User instance over to a PublicUser instance: class User(db.Model): # ... # code # ... def as_public(self): """Returns a PublicUser version of this object. """ props = self.properties() pu = PublicUser() for prop in pu.properties().values(): # Only copy properties that exist for both the PublicUser model and # the User model. if prop.name in props: # This line of code sets the property of the PublicUser # instance to the value of the same property on the User # instance. prop.__set__(pu, props[prop.name].__get__(self, type(self))) return pu Please comment if this isn't a good way of doing it. A: Could you not create a method within your User class which instantiates a ReadOnlyUser object and copies the values of member variables over as appropriate? Your call would be something like User.get_by_id(1).readonly() with the readonly method defined in the following form: class User(db.Model): def readonly(self): return ReadOnlyUser(self.name, self.id); Or you could perhaps have your User class extend another class with methods to do this automatically based on some static vars listing properties to copy over, or something. P.S. I don't code in Python
Exposing a "dumbed-down", read-only instance of a Model in GAE
Does anyone know a clever way, in Google App Engine, to return a wrapped Model instance that only exposes a few of the original properties, and does not allow saving the instance back to the datastore? I'm not looking for ways of actually enforcing these rules, obviously it'll still be possible to change the instance by digging through its __dict__ etc. I just want a way to avoid accidental exposure/changing of data. My initial thought was to do this (I want to do this for a public version of a User model): class PublicUser(db.Model): display_name = db.StringProperty() @classmethod def kind(cls): return 'User' def put(self): raise SomeError() Unfortunately, GAE maps the kind to a class early on, so if I do PublicUser.get_by_id(1) I will actually get a User instance back, not a PublicUser instance. Also, the idea is that it should at least appear to be a Model instance so that I can pass it around to code that does not know about the fact that it is a "dumbed-down" version. Ultimately I want to do this so that I can use my generic data exposure functions on the read-only version, so that they only expose public information about the user. Update I went with icio's solution. Here's the code I wrote for copying the properties from the User instance over to a PublicUser instance: class User(db.Model): # ... # code # ... def as_public(self): """Returns a PublicUser version of this object. """ props = self.properties() pu = PublicUser() for prop in pu.properties().values(): # Only copy properties that exist for both the PublicUser model and # the User model. if prop.name in props: # This line of code sets the property of the PublicUser # instance to the value of the same property on the User # instance. prop.__set__(pu, props[prop.name].__get__(self, type(self))) return pu Please comment if this isn't a good way of doing it.
[ "Could you not create a method within your User class which instantiates a ReadOnlyUser object and copies the values of member variables over as appropriate? Your call would be something like User.get_by_id(1).readonly() with the readonly method defined in the following form:\nclass User(db.Model):\n def readonly(self):\n return ReadOnlyUser(self.name, self.id);\n\nOr you could perhaps have your User class extend another class with methods to do this automatically based on some static vars listing properties to copy over, or something.\nP.S. I don't code in Python\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "model", "python" ]
stackoverflow_0002754721_google_app_engine_model_python.txt
Q: Until when will Python 2.5 be supported? Apparently Python only supports 2 minor versions (like 2.X), so that would mean Python 2.5 would get phased out when Python 2.7 comes out (in June 2010?) Is this correct? PEP 356 -- Python 2.5 Release Schedule doesn't give much answers to this question. A: Python 2.5 will continue to get security updates until September 2011. See this message by Martin v. Löwis, the Python 2.5 release manager.
Until when will Python 2.5 be supported?
Apparently Python only supports 2 minor versions (like 2.X), so that would mean Python 2.5 would get phased out when Python 2.7 comes out (in June 2010?) Is this correct? PEP 356 -- Python 2.5 Release Schedule doesn't give much answers to this question.
[ "Python 2.5 will continue to get security updates until September 2011. See this message by Martin v. Löwis, the Python 2.5 release manager.\n" ]
[ 6 ]
[]
[]
[ "python", "python_2.5" ]
stackoverflow_0002754755_python_python_2.5.txt
Q: python: subclass a metaclass For putting methods of various classes into a global registry I'm using a decorator with a metaclass. The decorator tags, the metaclass puts the function in the registry: class ExposedMethod (object): def __init__(self, decoratedFunction): self._decoratedFunction = decoratedFunction def __call__(__self,*__args,**__kw): return __self._decoratedFunction(*__args,**__kw) class ExposedMethodDecoratorMetaclass(type): def __new__(mcs, name, bases, dct): for obj_name, obj in dct.iteritems(): if isinstance(obj, ExposedMethod): WorkerFunctionRegistry.addWorkerToWorkerFunction(obj_name, name) return type.__new__(mcs, name, bases, dct) class MyClass (object): __metaclass__ = DiscoveryExposedMethodDecoratorMetaclass @ExposeDiscoveryMethod def myCoolExposedMethod (self): pass I've now came to the point where two function registries are needed. The first thought was to subclass the metaclass and put the other registry in. For that the new method has simply to be rewritten. Since rewriting means redundant code this is not what I really want. So, it would be nice if anyone could name a way how to put an attribute inside of the metaclass which is able to be read when new is executed. With that the right registry could be put in without having to rewrite new. A: Your ExposedMethod instances do not behave as normal instance methods but rather like static methods -- the fact that you're giving one of them a self argument hints that you're not aware of that. You may need to add a __get__ method to the ExposedMethod class to make it a descriptor, just like function objects are -- see here for more on descriptors. But there is a much simpler way, since functions can have attributes...: def ExposedMethod(registry=None): def decorate(f): f.registry = registry return f return decorate and in a class decorator (simpler than a metaclass! requires Python 2.6 or better -- in 2.5 or earlier you'll need to stick w/the metaclass or explicitly call this after the class statement, though the first part of the answer and the functionality of the code below are still perfectly fine): def RegisterExposedMethods(cls): for name, f in vars(cls).iteritems(): if not hasattr(f, 'registry'): continue registry = f.registry if registry is None: registry = cls.registry registry.register(name, cls.__name__) return cls So you can do: @RegisterExposedMethods class MyClass (object): @ExposeMethod(WorkerFunctionRegistry) def myCoolExposedMethod (self): pass and the like. This is easily extended to allowing an exposed method to have several registries, get the default registry elsewhere than from the class (it could be in the class decorator, for example, if that works better for you) and avoids getting enmeshed with metaclasses without losing any functionality. Indeed that's exactly why class decorators were introduced in Python 2.6: they can take the place of 90% or so of practical uses of metaclasses and are much simpler than custom metaclasses. A: You can use a class attribute to point to the registry you want to use in the specialized metaclasses, e.g. : class ExposedMethodDecoratorMetaclassBase(type): registry = None def __new__(mcs, name, bases, dct): for obj_name, obj in dct.items(): if isinstance(obj, ExposedMethod): mcs.registry.register(obj_name, name) return type.__new__(mcs, name, bases, dct) class WorkerExposedMethodDecoratorMetaclass(ExposedMethodDecoratorMetaclassBase): registry = WorkerFunctionRegistry class RetiredExposedMethodDecoratorMetaclass(ExposedMethodDecoratorMetaclassBase): registry = RetiredFunctionRegistry A: Thank you both for your answers. Both helped alot to find a proper way for my request. My final solution to the problem is the following: def ExposedMethod(decoratedFunction): decoratedFunction.isExposed = True return decoratedFunction class RegisterExposedMethods (object): def __init__(self, decoratedClass, registry): self._decoratedClass = decoratedClass for name, f in vars(self._decoratedClass).iteritems(): if hasattr(f, "isExposed"): registry.addComponentClassToComponentFunction(name, self._decoratedClass.__name__) # cloak us as the original class self.__class__.__name__ = decoratedClass.__name__ def __call__(self,*__args,**__kw): return self._decoratedClass(*__args,**__kw) def __getattr__(self, name): return getattr(self._decoratedClass, name) On a Class I wish to expose methods from I do the following: @RegisterExposedMethods class MyClass (object): @ExposedMethod def myCoolExposedMethod (self): pass The class decorator is now very easy to be subclassed. Here is an example: class DiscoveryRegisterExposedMethods (RegisterExposedMethods): def __init__(self, decoratedClass): RegisterExposedMethods.__init__(self, decoratedClass, DiscoveryFunctionRegistry()) With that the comment of Alex Your ExposedMethod instances do not behave as normal instance methods ... is no longer true, since the method is simply tagged and not wrapped.
python: subclass a metaclass
For putting methods of various classes into a global registry I'm using a decorator with a metaclass. The decorator tags, the metaclass puts the function in the registry: class ExposedMethod (object): def __init__(self, decoratedFunction): self._decoratedFunction = decoratedFunction def __call__(__self,*__args,**__kw): return __self._decoratedFunction(*__args,**__kw) class ExposedMethodDecoratorMetaclass(type): def __new__(mcs, name, bases, dct): for obj_name, obj in dct.iteritems(): if isinstance(obj, ExposedMethod): WorkerFunctionRegistry.addWorkerToWorkerFunction(obj_name, name) return type.__new__(mcs, name, bases, dct) class MyClass (object): __metaclass__ = DiscoveryExposedMethodDecoratorMetaclass @ExposeDiscoveryMethod def myCoolExposedMethod (self): pass I've now came to the point where two function registries are needed. The first thought was to subclass the metaclass and put the other registry in. For that the new method has simply to be rewritten. Since rewriting means redundant code this is not what I really want. So, it would be nice if anyone could name a way how to put an attribute inside of the metaclass which is able to be read when new is executed. With that the right registry could be put in without having to rewrite new.
[ "Your ExposedMethod instances do not behave as normal instance methods but rather like static methods -- the fact that you're giving one of them a self argument hints that you're not aware of that. You may need to add a __get__ method to the ExposedMethod class to make it a descriptor, just like function objects are -- see here for more on descriptors.\nBut there is a much simpler way, since functions can have attributes...:\ndef ExposedMethod(registry=None):\n def decorate(f):\n f.registry = registry\n return f\n return decorate\n\nand in a class decorator (simpler than a metaclass! requires Python 2.6 or better -- in 2.5 or earlier you'll need to stick w/the metaclass or explicitly call this after the class statement, though the first part of the answer and the functionality of the code below are still perfectly fine):\ndef RegisterExposedMethods(cls):\n for name, f in vars(cls).iteritems():\n if not hasattr(f, 'registry'): continue\n registry = f.registry\n if registry is None:\n registry = cls.registry\n registry.register(name, cls.__name__)\n return cls\n\nSo you can do:\n@RegisterExposedMethods\nclass MyClass (object):\n\n @ExposeMethod(WorkerFunctionRegistry)\n def myCoolExposedMethod (self):\n pass\n\nand the like. This is easily extended to allowing an exposed method to have several registries, get the default registry elsewhere than from the class (it could be in the class decorator, for example, if that works better for you) and avoids getting enmeshed with metaclasses without losing any functionality. Indeed that's exactly why class decorators were introduced in Python 2.6: they can take the place of 90% or so of practical uses of metaclasses and are much simpler than custom metaclasses.\n", "You can use a class attribute to point to the registry you want to use in the specialized metaclasses, e.g. :\nclass ExposedMethodDecoratorMetaclassBase(type):\n\n registry = None\n\n def __new__(mcs, name, bases, dct):\n for obj_name, obj in dct.items():\n if isinstance(obj, ExposedMethod):\n mcs.registry.register(obj_name, name)\n return type.__new__(mcs, name, bases, dct)\n\n\nclass WorkerExposedMethodDecoratorMetaclass(ExposedMethodDecoratorMetaclassBase):\n\n registry = WorkerFunctionRegistry\n\n\nclass RetiredExposedMethodDecoratorMetaclass(ExposedMethodDecoratorMetaclassBase):\n\n registry = RetiredFunctionRegistry\n\n", "Thank you both for your answers. Both helped alot to find a proper way for my request.\nMy final solution to the problem is the following:\ndef ExposedMethod(decoratedFunction):\n decoratedFunction.isExposed = True\n return decoratedFunction\n\nclass RegisterExposedMethods (object):\n def __init__(self, decoratedClass, registry):\n self._decoratedClass = decoratedClass\n for name, f in vars(self._decoratedClass).iteritems():\n if hasattr(f, \"isExposed\"):\n registry.addComponentClassToComponentFunction(name, self._decoratedClass.__name__)\n\n # cloak us as the original class\n self.__class__.__name__ = decoratedClass.__name__\n\n def __call__(self,*__args,**__kw):\n return self._decoratedClass(*__args,**__kw)\n\n def __getattr__(self, name):\n return getattr(self._decoratedClass, name)\n\nOn a Class I wish to expose methods from I do the following:\n@RegisterExposedMethods\nclass MyClass (object):\n @ExposedMethod\n def myCoolExposedMethod (self):\n pass\n\nThe class decorator is now very easy to be subclassed. Here is an example:\nclass DiscoveryRegisterExposedMethods (RegisterExposedMethods):\n def __init__(self, decoratedClass):\n RegisterExposedMethods.__init__(self,\n decoratedClass,\n DiscoveryFunctionRegistry())\n\nWith that the comment of Alex \n\nYour ExposedMethod instances do not behave as normal instance methods ...\n\nis no longer true, since the method is simply tagged and not wrapped.\n" ]
[ 5, 0, 0 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0002744687_metaclass_python.txt
Q: Merge decorator function as class Need to create a class that will do all things as the "merge" function. In class i will change, process and add new arguments. def merge(*arg, **kwarg): # get decorator args & kwargs def func(f): def tmp(*args, **kwargs): # get function args & kwargs kwargs.update(kwarg) # merge two dictionaries return f(*args, **kwargs) # return merged data return tmp return func Usage: @other_decorator # return *args and **kwarg @merge(list=['one','two','three']) # need to merge with @other_decorator def test(*a, **k): # get merged args and kwargs print 'args:', a print 'kwargs:', k A: I'm not sure I quite get what you're asking. Your implementation works fine, and you won't get around having two levels of indirection if you want to create a parametrized decorator of any kind. To make merge a class you could do this class Merge(object): def __init__(self, **extra_kws): self.extra_kws = extra_kws def __call__(self, function): def _wrapper(*args, **kws): kws.update(self.extra_kws) return function(*args, **kws) return _wrapper Then you can do this: @Merge(foo='bar') def test(*args, **kws): print *args print **kws But you said you want to add change and process new arguments. So presumably you want the decorator itself to be live so you can do: test.extra_kws['sun'] = 'dock' After the decorator has been applied. In that case you probably don't want merge to be a class, but you want it to generate a class, so that test is replaced by the modifiable instance: def merge(**extra_kws): class _Merge(object): def __init__(self, function): self.extra_kws = extra_kws self.function = function def __call__(self, *args, **kws): kws.update(self.extra_kws) return self.function(*args, **kws) return _Merge @merge(foo='bar') def test(*args, **kws): print 'args:', args print 'kws:', kws test(sun='dock') test.extra_kws['trog'] = 'cube' test(sun='dock') This then allows you to change the keywords on a particular decorated function later. You could also do the same thing with function arguments without classes: def merge(**extra_kws): def _decorator(function): def _wrapper(*args, **kws): kws.update(_wrapper.extra_kws) return function(*args, **kws) _wrapper.extra_kws = extra_kws return _wrapper return _decorator @merge(foo='bar') def test(*args, **kws): print 'kws:', kws test(sun='dock') test.extra_kws['trog'] = 'cube' test(sun='dock')
Merge decorator function as class
Need to create a class that will do all things as the "merge" function. In class i will change, process and add new arguments. def merge(*arg, **kwarg): # get decorator args & kwargs def func(f): def tmp(*args, **kwargs): # get function args & kwargs kwargs.update(kwarg) # merge two dictionaries return f(*args, **kwargs) # return merged data return tmp return func Usage: @other_decorator # return *args and **kwarg @merge(list=['one','two','three']) # need to merge with @other_decorator def test(*a, **k): # get merged args and kwargs print 'args:', a print 'kwargs:', k
[ "I'm not sure I quite get what you're asking. Your implementation works fine, and you won't get around having two levels of indirection if you want to create a parametrized decorator of any kind.\nTo make merge a class you could do this\nclass Merge(object):\n def __init__(self, **extra_kws):\n self.extra_kws = extra_kws\n def __call__(self, function):\n def _wrapper(*args, **kws):\n kws.update(self.extra_kws)\n return function(*args, **kws)\n return _wrapper\n\nThen you can do this:\n@Merge(foo='bar')\ndef test(*args, **kws):\n print *args\n print **kws\n\nBut you said you want to add change and process new arguments. So presumably you want the decorator itself to be live so you can do:\ntest.extra_kws['sun'] = 'dock'\n\nAfter the decorator has been applied. In that case you probably don't want merge to be a class, but you want it to generate a class, so that test is replaced by the modifiable instance:\ndef merge(**extra_kws):\n class _Merge(object):\n def __init__(self, function):\n self.extra_kws = extra_kws\n self.function = function\n def __call__(self, *args, **kws):\n kws.update(self.extra_kws)\n return self.function(*args, **kws)\n return _Merge\n\n@merge(foo='bar')\ndef test(*args, **kws):\n print 'args:', args\n print 'kws:', kws\n\ntest(sun='dock')\ntest.extra_kws['trog'] = 'cube'\ntest(sun='dock')\n\nThis then allows you to change the keywords on a particular decorated function later. \nYou could also do the same thing with function arguments without classes:\ndef merge(**extra_kws):\n def _decorator(function):\n def _wrapper(*args, **kws):\n kws.update(_wrapper.extra_kws)\n return function(*args, **kws)\n _wrapper.extra_kws = extra_kws\n return _wrapper\n return _decorator\n\n@merge(foo='bar')\ndef test(*args, **kws):\n print 'kws:', kws\n\ntest(sun='dock')\ntest.extra_kws['trog'] = 'cube'\ntest(sun='dock')\n\n" ]
[ 2 ]
[]
[]
[ "arguments", "class", "decorator", "keyword_argument", "python" ]
stackoverflow_0002754363_arguments_class_decorator_keyword_argument_python.txt
Q: str.format() raises KeyError The following code raises a KeyError exception: addr_list_formatted = [] addr_list_idx = 0 for addr in addr_list: # addr_list is a list addr_list_idx = addr_list_idx + 1 addr_list_formatted.append(""" "{0}" { "gamedir" "str" "address" "{1}" } """.format(addr_list_idx, addr)) Why? I am using Python 3.1. A: The problem is that those { and } characters you have there don't specify a key for formatting. You need to double them up, so change your code to: addr_list_formatted.append(""" "{0}" {{ "gamedir" "str" "address" "{1}" }} """.format(addr_list_idx, addr))
str.format() raises KeyError
The following code raises a KeyError exception: addr_list_formatted = [] addr_list_idx = 0 for addr in addr_list: # addr_list is a list addr_list_idx = addr_list_idx + 1 addr_list_formatted.append(""" "{0}" { "gamedir" "str" "address" "{1}" } """.format(addr_list_idx, addr)) Why? I am using Python 3.1.
[ "The problem is that those { and } characters you have there don't specify a key for formatting. You need to double them up, so change your code to:\naddr_list_formatted.append(\"\"\"\n \"{0}\"\n {{\n \"gamedir\" \"str\"\n \"address\" \"{1}\"\n }}\n\"\"\".format(addr_list_idx, addr))\n\n" ]
[ 164 ]
[]
[]
[ "delimiter", "missing_data", "python", "string_formatting", "syntax" ]
stackoverflow_0002755201_delimiter_missing_data_python_string_formatting_syntax.txt
Q: Reduce function calls I profiled my python program and found that the following function was taking too long to run. Perhaps, I can use a different algorithm and make it run faster. However, I have read that I can also possibly increase the speed by reducing function calls, especially when it gets called repeatedly within a loop. I am a python newbie and would like to learn how to do this and see how much faster it can get. Currently, the function is: def potentialActualBuyers(setOfPeople,theCar,price): count=0 for person in setOfPeople: if person.getUtility(theCar) >= price and person.periodCarPurchased==None: count += 1 return count where setOfPeople is a list of person objects. I tried the following: def potentialActualBuyers(setOfPeople,theCar,price): count=0 Utility=person.getUtility for person in setOfPeople: if Utility(theCar) >= price and person.periodCarPurchased==None: count += 1 return count This, however, gives me an error saying local variable 'person' referenced before assignment Any suggestions, how I can reduce function calls or any other changes that can make the code faster. Again, I am a python newbie and even though I may possibly be able to use a better algorithm, it is still worthwhile learning the answer to the above question. Thanks very much. ***** EDIT ***** Adding the getUtility method: def getUtility(self,theCar): if theCar in self.utility.keys(): return self.utility[theCar] else: self.utility[theCar]=self.A*(math.pow(theCar.mpg,self.alpha))*(math.pow(theCar.hp,self.beta))*(math.pow(theCar.pc,self.gamma)) return self.utility[theCar] ***** EDIT: asking for new ideas ***** Any ideas how to speed this up further. I used the method suggested by Alex to cut the time in half. Can I speed this further? Thanks. A: I doubt you can get much speedup in this case by hoisting the lookup of person.getUtility (by class, not by instances, as other instances have pointed out). Maybe...: return sum(1 for p in setOfPeople if p.periodCarPurchased is None and p.getUtility(theCar) >= price) but I suspect most of the time is actually spent in the execution of getUtility (and possibly in the lookup of p.periodCarPurchased if that's some fancy property as opposed to a plain old attribute -- I moved the latter before the and just in case it is a plain attribute and can save a number of the getUtility calls). What does your profiling say wrt the fraction of time spent in this function (net of its calls to others) vs the method (and possibly property) in question? A: Try instead (that's assuming all persons are of the same type Person): Utility = Person.getUtility for person in setOfPeople: if Utility (person, theCar) >= ... Also, instead of == None using is None should be marginally faster. Try if swapping and terms helps. A: Methods are just functions bound to an object: Utility = Person.getUtility for person in setOfPeople: if Utility(person, theCar) ... This doesn't eliminate a function call though, it eliminates an attribute lookup. A: This one line made my eyes bleed: self.utility[theCar]=self.A*(math.pow(theCar.mpg,self.alpha))*(math.pow(theCar.hp,self.beta))*(math.pow(theCar.pc,self.gamma)) Let's make it legible and PEP8able and then see if it can be faster. First some spaces: self.utility[theCar] = self.A * (math.pow(theCar.mpg, self.alpha)) * (math.pow(theCar.hp, self.beta)) * (math.pow(theCar.pc, self.gamma)) Now we can see there are very redundant parentheses; remove them: self.utility[theCar] = self.A * math.pow(theCar.mpg, self.alpha) * math.pow(theCar.hp, self.beta) * math.pow(theCar.pc, self.gamma) Hmmm: 3 lookups of math.pow and 3 function calls. You have three choices for powers: x ** y, the built-in pow(x, y[, z]), and math.pow(x, y). Unless you have good reason for using one of the others, it's best (IMHO) to choose x ** y; you save both the attribute lookup and the function call. self.utility[theCar] = self.A * theCar.mpg ** self.alpha * theCar.hp ** self.beta * theCar.pc ** self.gamma annnnnnd while we're here, let's get rid of the horizontal scroll-bar: self.utility[theCar] = (self.A * theCar.mpg ** self.alpha * theCar.hp ** self.beta * theCar.pc ** self.gamma) A possibility that would require quite a rewrite of your existing code and may not help anyway (in Python) would be to avoid most of the power calculations by taking logs everywhere and working with log_utility = log_A + log_mpg * alpha ...
Reduce function calls
I profiled my python program and found that the following function was taking too long to run. Perhaps, I can use a different algorithm and make it run faster. However, I have read that I can also possibly increase the speed by reducing function calls, especially when it gets called repeatedly within a loop. I am a python newbie and would like to learn how to do this and see how much faster it can get. Currently, the function is: def potentialActualBuyers(setOfPeople,theCar,price): count=0 for person in setOfPeople: if person.getUtility(theCar) >= price and person.periodCarPurchased==None: count += 1 return count where setOfPeople is a list of person objects. I tried the following: def potentialActualBuyers(setOfPeople,theCar,price): count=0 Utility=person.getUtility for person in setOfPeople: if Utility(theCar) >= price and person.periodCarPurchased==None: count += 1 return count This, however, gives me an error saying local variable 'person' referenced before assignment Any suggestions, how I can reduce function calls or any other changes that can make the code faster. Again, I am a python newbie and even though I may possibly be able to use a better algorithm, it is still worthwhile learning the answer to the above question. Thanks very much. ***** EDIT ***** Adding the getUtility method: def getUtility(self,theCar): if theCar in self.utility.keys(): return self.utility[theCar] else: self.utility[theCar]=self.A*(math.pow(theCar.mpg,self.alpha))*(math.pow(theCar.hp,self.beta))*(math.pow(theCar.pc,self.gamma)) return self.utility[theCar] ***** EDIT: asking for new ideas ***** Any ideas how to speed this up further. I used the method suggested by Alex to cut the time in half. Can I speed this further? Thanks.
[ "I doubt you can get much speedup in this case by hoisting the lookup of person.getUtility (by class, not by instances, as other instances have pointed out). Maybe...:\nreturn sum(1 for p in setOfPeople\n if p.periodCarPurchased is None\n and p.getUtility(theCar) >= price)\n\nbut I suspect most of the time is actually spent in the execution of getUtility (and possibly in the lookup of p.periodCarPurchased if that's some fancy property as opposed to a plain old attribute -- I moved the latter before the and just in case it is a plain attribute and can save a number of the getUtility calls). What does your profiling say wrt the fraction of time spent in this function (net of its calls to others) vs the method (and possibly property) in question?\n", "Try instead (that's assuming all persons are of the same type Person):\nUtility = Person.getUtility\nfor person in setOfPeople:\n if Utility (person, theCar) >= ...\n\nAlso, instead of == None using is None should be marginally faster. Try if swapping and terms helps.\n", "Methods are just functions bound to an object:\n Utility = Person.getUtility\n for person in setOfPeople:\n if Utility(person, theCar) ...\n\nThis doesn't eliminate a function call though, it eliminates an attribute lookup.\n", "This one line made my eyes bleed: \n self.utility[theCar]=self.A*(math.pow(theCar.mpg,self.alpha))*(math.pow(theCar.hp,self.beta))*(math.pow(theCar.pc,self.gamma))\n\nLet's make it legible and PEP8able and then see if it can be faster. First some spaces:\nself.utility[theCar] = self.A * (math.pow(theCar.mpg, self.alpha)) * (math.pow(theCar.hp, self.beta)) * (math.pow(theCar.pc, self.gamma))\n\nNow we can see there are very redundant parentheses; remove them:\nself.utility[theCar] = self.A * math.pow(theCar.mpg, self.alpha) * math.pow(theCar.hp, self.beta) * math.pow(theCar.pc, self.gamma)\n\nHmmm: 3 lookups of math.pow and 3 function calls. You have three choices for powers: x ** y, the built-in pow(x, y[, z]), and math.pow(x, y). Unless you have good reason for using one of the others, it's best (IMHO) to choose x ** y; you save both the attribute lookup and the function call.\nself.utility[theCar] = self.A * theCar.mpg ** self.alpha * theCar.hp ** self.beta * theCar.pc ** self.gamma\n\nannnnnnd while we're here, let's get rid of the horizontal scroll-bar:\nself.utility[theCar] = (self.A\n * theCar.mpg ** self.alpha\n * theCar.hp ** self.beta\n * theCar.pc ** self.gamma)\n\nA possibility that would require quite a rewrite of your existing code and may not help anyway (in Python) would be to avoid most of the power calculations by taking logs everywhere and working with log_utility = log_A + log_mpg * alpha ...\n" ]
[ 2, 1, 1, 1 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0002751861_performance_python.txt
Q: Converting html entities into their values in python I use this regex on some input, [^a-zA-Z0-9@#] However this ends up removing lots of html special characters within the input, such as #227;, #1606;, #1588; (i had to remove the & prefix so that it wouldn't show up as the actual value..) is there a way that I can convert them to their values so that it will satisfy the regexp expression? I also have no idea why the text decided to be so big. A: Given that your text appears to have numeric-coded, not named, entities, you can first convert your byte string that includes xml entity defs (ampersand, hash, digits, semicolon) to unicode: import re xed_re = re.compile(r'&#(\d+);') def usub(m): return unichr(int(m.group(1))) s = 'ã, ن, ش' u = xed_re.sub(usub, s) if your terminal emulator can display arbitrary unicode glyphs, a print u will then show ã, ن, ش In any case, you can now, if you wish, use your original RE and you won't accidentally "catch" the entities, only ascii letters, digits, and the couple of punctuation characters you listed. (I'm not sure that's what you really want -- why not accented letters but just ascii ones, for example? -- but, if it is what you want, it will work). If you do have named entities in addition to the numeric-coded ones, you can also apply the htmlentitydefs standard library module recommended in another answer (it only deals with named entities which map to Latin-1 code points, however). A: You can adapt the following script: import htmlentitydefs import re def substitute_entity (match): name = match.group (1) if name in htmlentitydefs.name2codepoint: return unichr (htmlentitydefs.name2codepoint[name]) elif name.startswith ('#'): try: return unichr (int (name[1:])) except: pass return '?' print re.sub ('&(#?\\w+);', substitute_entity, 'x « y &wat; z {') Produces the following answer here: x « y ? z { EDIT: I understood the question as "how to get rid of HTML entities before further processing", hope I haven't wasted time on answering a wrong question ;) A: Without knowing what the expression is being used for I can't tell exactly what you need. This will match special characters or strings of characters excluding letters, digits, @, and #: [^a-zA-Z0-9@#]*|#[0-9A-Za-z]+;
Converting html entities into their values in python
I use this regex on some input, [^a-zA-Z0-9@#] However this ends up removing lots of html special characters within the input, such as #227;, #1606;, #1588; (i had to remove the & prefix so that it wouldn't show up as the actual value..) is there a way that I can convert them to their values so that it will satisfy the regexp expression? I also have no idea why the text decided to be so big.
[ "Given that your text appears to have numeric-coded, not named, entities, you can first convert your byte string that includes xml entity defs (ampersand, hash, digits, semicolon) to unicode:\nimport re\nxed_re = re.compile(r'&#(\\d+);')\ndef usub(m): return unichr(int(m.group(1)))\n\ns = 'ã, ن, ش'\nu = xed_re.sub(usub, s)\n\nif your terminal emulator can display arbitrary unicode glyphs, a print u will then show\nã, ن, ش\n\nIn any case, you can now, if you wish, use your original RE and you won't accidentally \"catch\" the entities, only ascii letters, digits, and the couple of punctuation characters you listed. (I'm not sure that's what you really want -- why not accented letters but just ascii ones, for example? -- but, if it is what you want, it will work).\nIf you do have named entities in addition to the numeric-coded ones, you can also apply the htmlentitydefs standard library module recommended in another answer (it only deals with named entities which map to Latin-1 code points, however).\n", "You can adapt the following script:\nimport htmlentitydefs\nimport re\n\ndef substitute_entity (match):\n name = match.group (1)\n if name in htmlentitydefs.name2codepoint:\n return unichr (htmlentitydefs.name2codepoint[name])\n elif name.startswith ('#'):\n try:\n return unichr (int (name[1:]))\n except:\n pass\n\n return '?'\n\nprint re.sub ('&(#?\\\\w+);', substitute_entity, 'x « y &wat; z {')\n\nProduces the following answer here:\nx « y ? z {\n\nEDIT: I understood the question as \"how to get rid of HTML entities before further processing\", hope I haven't wasted time on answering a wrong question ;)\n", "Without knowing what the expression is being used for I can't tell exactly what you need.\nThis will match special characters or strings of characters excluding letters, digits, @, and #:\n[^a-zA-Z0-9@#]*|#[0-9A-Za-z]+;\n\n" ]
[ 4, 1, 0 ]
[]
[]
[ "html_entities", "python", "special_characters" ]
stackoverflow_0002755432_html_entities_python_special_characters.txt
Q: Python Mechanize unable to avoid redirect when Post I am trying to crawl a site using mechanize. The site provides search results in different pages. When posting to get the next set of results, something is wrong and the server redirects me to the first page, asking mechanize to update the SearchSession Cookie. I have been debugging the requests using Firefox and they look quite the same, and I am unable to find the problem. Any suggestion? Below the requests: ----------- FIRST THE RIGHT SEQUENCE, USING TAMPER IN FIREFOX ------------------------- POST XXX/JobSearch/Results.aspx?Keywords=Python&LTxt=London%2c+South+East&Radius=0&LIds2=ZV&clid=1621&cltypeid=2&clName=London Load Flags[LOAD_DOCUMENT_URI LOAD_INITIAL_DOCUMENT_URI ] Content Size[-1] Mime Type[text/html] Request Headers: Host[www.cwjobs.co.uk] User-Agent[Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.9) Gecko/20100401 Ubuntu/9.10 (karmic) Firefox/3.5.9] Accept[text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8] Accept-Language[en-us,en;q=0.5] Accept-Encoding[gzip,deflate] Accept-Charset[ISO-8859-1,utf-8;q=0.7,*;q=0.7] Keep-Alive[300] Connection[keep-alive] Referer[XXX/JobSearch/Results.aspx?Keywords=Python&LTxt=London%2c+South+East&Radius=0&LIds2=ZV&clid=1621&cltypeid=2&clName=London] Cookie[ecos=774803468-0; AnonymousUser=MemberId=acc079dd-66b6-4081-9b07-60d6955ee8bf&IsAnonymous=True; PJBIPPOPUP=; WT_FPC=id=86.181.183.106-2262469600.30073025:lv=1272812851736:ss=1272812789362; SearchSession=SessionGuid=71de63de-3bd0-4787-895d-b6b9e7c93801&LogSource=NAT] Post Data: __EVENTTARGET[srpPager%24btnForward] __EVENTARGUMENT[] hdnSearchResults[BV%2CA%2CC0P5x%2COou-%2CB4S-%2CBuC-%2CDzx-%2CHwn-%2CKPP-%2CIVA-%2CC9D-%2CH6X-%2CH7x-%2CJ0x-%2CCvX-%2CCra-%2COHa-%2CHhP-%2CCoj-%2CBlM-%2CE9W-%2CIm8-%2CBqG-%2CPFy-%2CN%2Fm-%2Ceaa%2CCvj-%2CCtJ-%2CCr7-%2CBpu-%2Cmh%2CMb6-%2CJ%2Fk-%2CHY8-%2COJ7-%2CNtF-%2CEya-%2CErT-%2CEo4-%2CEKU-%2CDnL-%2CC5M-%2CCyB-%2CBsD-%2CBrc-%2CBpU-%2Col%2C30%2CC1%2Cd4N%2COo8-%2COi0-%2CLz%2F-%2CLxP-%2CFyp-%2CFVR-%2CEHL-%2CPrP-%2CLmE-%2CK3H-%2CKXJ-%2CFyn%2CIcq-%2CIco-%2CIK4-%2CIIg-%2CH2k-%2CH0N-%2CHwp-%2CHvF-%2CFij-%2CFhl-%2CCwj-%2CCb5-%2CCQj-%2CCQh-%2CB%2B2-%2CBc6-%2ChFo%2CNLq-%2CNI%2F-%2CFzM-%2Cdu-%2CHg2-%2CBug-%2CBse-%2CB9Q-] __VIEWSTATE[%2FwEPDwUKLTkyMzI2ODA4Ng9kFgYCBA8WBB4EaHJlZgWJAWh0dHA6Ly93d3cuY3dqb2JzLmNvLnVrL0pvYlNlYXJjaC9SU1MuYXNweD9LZXl3b3Jkcz1QeXRob24mTFR4dD1Mb25kb24lMmMrU291dGgrRWFzdCZSYWRpdXM9MCZMSWRzMj1aViZjbGlkPTE2MjEmY2x0eXBlaWQ9MiZjbE5hbWU9TG9uZG9uHgV0aXRsZQUkTGF0ZXN0IFB5dGhvbiBqb2JzIGZyb20gQ1dKb2JzLmNvLnVrZAIGDxYCHgRUZXh0BV48bGluayByZWw9ImNhbm9uaWNhbCIgaHJlZj0iaHR0cDovL3d3dy5jd2pvYnMuY28udWsvSm9iU2Vla2luZy9QeXRob25fTG9uZG9uX2wxNjIxX3QyLmh0bWwiIC8%2BZAIIEGRkFg4CBw8WAh8CBV9Zb3VyIHNlYXJjaCBvbiA8Yj5LZXl3b3JkczogUHl0aG9uOyBMb2NhdGlvbjogTG9uZG9uLCBTb3V0aCBFYXN0OyA8L2I%2BIHJldHVybmVkIDxiPjg1PC9iPiBqb2JzLmQCCQ8WAh4HVmlzaWJsZWhkAgsPFgIfAgUoVGhlIG1vc3QgcmVsZXZhbnQgam9icyBhcmUgbGlzdGVkIGZpcnN0LmQCEw8PFgIeC05hdmlnYXRlVXJsBQF%2BZGQCFQ9kFgYCBQ8PFgYfAgUGUHl0aG9uHgtEZWZhdWx0VGV4dAUMZS5nLiBhbmFseXN0HhNEZWZhdWx0VGV4dENzc0NsYXNzZWRkAgsPDxYGHwIFEkxvbmRvbiwgU291dGggRWFzdB8FBQllLmcuIEJhdGgfBmVkZAIRDxAPFgYeDURhdGFUZXh0RmllbGQFClJhZGl1c05hbWUeDkRhdGFWYWx1ZUZpZWxkBQZSYWRpdXMeC18hRGF0YUJvdW5kZ2QQFREHMCBtaWxlcwcyIG1pbGVzBzUgbWlsZXMIMTAgbWlsZXMIMTUgbWlsZXMIMjAgbWlsZXMIMjUgbWlsZXMIMzAgbWlsZXMIMzUgbWlsZXMINDAgbWlsZXMINDUgbWlsZXMINTAgbWlsZXMINjAgbWlsZXMINzAgbWlsZXMIODAgbWlsZXMIOTAgbWlsZXMJMTAwIG1pbGVzFREBMAEyATUCMTACMTUCMjACMjUCMzACMzUCNDACNDUCNTACNjACNzACODACOTADMTAwFCsDEWdnZ2dnZ2dnZ2dnZ2dnZ2dnZGQCFw9kFgQCAQ9kFgQCBA8QZA8WA2YCAQICFgMQBQhBbGwgam9icwUBMGcQBRlEaXJlY3QgZW1wbG95ZXIgam9icyBvbmx5BQEyZxAFEEFnZW5jeSBqb2JzIG9ubHkFATFnZGQCBg8QZA8WA2YCAQICFgMQBQlSZWxldmFuY2UFATFnEAUERGF0ZQUBMmcQBQZTYWxhcnkFATNnZGQCBQ8PFgYeClBhZ2VOdW1iZXICAh4PTnVtYmVyT2ZSZXN1bHRzAlUeDlJlc3VsdHNQZXJQYWdlAhRkZAIZDxYCHwNoZGQ%3D] Refinesearch%24txtKeywords[Python] Refinesearch%24txtLocation[London%2C+South+East] Refinesearch%24ddlRadius[0] ddlCompanyType[0] ddlSort[1] Response Headers: Cache-Control[private] Date[Sun, 02 May 2010 16:09:27 GMT] Content-Type[text/html; charset=utf-8] Expires[Sat, 02 May 2009 16:09:27 GMT] Server[Microsoft-IIS/6.0] X-SiteConHost[P310] X-Powered-By[ASP.NET] X-AspNet-Version[2.0.50727] Set-Cookie[SearchSession=SessionGuid=71de63de-3bd0-4787-895d-b6b9e7c93801&LogSource=NAT; path=/] Content-Encoding[gzip] Vary[Accept-Encoding] Transfer-Encoding[chunked] -------- NOW WHAT I'AM SENDING USING MECHANIZE, SOME HEADERS ADDED, ETC ----------- POST /JobSearch/Results.aspx?Keywords=Python&LTxt=London%2c+South+East&Radius=0&LIds2=ZV&clid=1621&cltypeid=2&clName=London HTTP/1.1\r\nContent-Length: 2424\r\n Accept-Language: en-us,en;q=0.5\r\n Accept-Encoding: gzip\r\n Host: www.cwjobs.co.uk\r\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8\r\n Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n Connection: keep-alive\r\n Cookie: AnonymousUser=MemberId=8fa5ddd7-17ed-425e-b189-82693bfbaa0c&IsAnonymous=True; SearchSession=SessionGuid=33e4e439-c2d6-423f-900f-574099310d5a&LogSource=NAT\r\n Referer: XXX/JobSearch/Results.aspx?Keywords=Python&LTxt=London%2c+South+East&Radius=0&LIds2=ZV&clid=1621&cltypeid=2&clName=London\r\n Content-Type: application/x-www-form-urlencoded\r\n\r\n' '__EVENTTARGET=srpPager%24btnForward& __EVENTARGUMENT=& hdnSearchResults=BV%2CA%2CC0eif%2CMwc%2CM6s%2COou%2CK09%2CG4H%2CEZf%2CGTu%2CLrr%2CGuX%2CGs9%2CEz9%2CL5X%2CL9U%2ChU%2CHHf%2CMAL%2CNDi%2CJrY%2CGBy%2CM%2Bo%2CdE-%2CpI%2CtDI%2CL5L%2CL7l%2CL8z%2CM%2FA%2CPPP%2CCM0%2CEpK%2CHPy%2Cez%2C7p%2CJ2U%2CJ9b%2CJ%2F2%2CKea%2CLBj%2CLvi%2CL2t%2CM8r%2CM9S%2CM%2Fa%2CPRT%2CPgi%2Csg7%2CF6%2CI2F%2CJTd%2CO-%2CC0v%2CC3f%2CDCq%2CDxn%2CERl%2CUbV%2CGME%2CGMG%2CGd2%2CGgO%2CGyK%2CG0h%2CG4F%2CG5p%2CJGL%2CJHJ%2CKhj%2CL4L%2CMM1%2CMYL%2CMYN%2CMp4%2CNL0%2COrj%2CvuW%2CBdE%2CBfv%2CI1i%2CBCh-%2COLA%2CHH4%2CM6O%2CM8Q%2CMre& __VIEWSTATE=%2FwEPDwUKLTkyMzI2ODA4Ng9kFgYCBA8WBB4EaHJlZgWJAWh0dHA6Ly93d3cuY3dqb2JzLmNvLnVrL0pvYlNlYXJjaC9SU1MuYXNweD9LZXl3b3Jkcz1QeXRob24mTFR4dD1Mb25kb24lMmMrU291dGgrRWFzdCZSYWRpdXM9MCZMSWRzMj1aViZjbGlkPTE2MjEmY2x0eXBlaWQ9MiZjbE5hbWU9TG9uZG9uHgV0aXRsZQUkTGF0ZXN0IFB5dGhvbiBqb2JzIGZyb20gQ1dKb2JzLmNvLnVrZAIGDxYCHgRUZXh0BV48bGluayByZWw9ImNhbm9uaWNhbCIgaHJlZj0iaHR0cDovL3d3dy5jd2pvYnMuY28udWsvSm9iU2Vla2luZy9QeXRob25fTG9uZG9uX2wxNjIxX3QyLmh0bWwiIC8%2BZAIIEGRkFg4CBw8WAh8CBV9Zb3VyIHNlYXJjaCBvbiA8Yj5LZXl3b3JkczogUHl0aG9uOyBMb2NhdGlvbjogTG9uZG9uLCBTb3V0aCBFYXN0OyA8L2I%2BIHJldHVybmVkIDxiPjg1PC9iPiBqb2JzLmQCCQ8WAh4HVmlzaWJsZWhkAgsPFgIfAgUoVGhlIG1vc3QgcmVsZXZhbnQgam9icyBhcmUgbGlzdGVkIGZpcnN0LmQCEw8PFgIeC05hdmlnYXRlVXJsBQF%2BZGQCFQ9kFgYCBQ8PFgYfAgUGUHl0aG9uHgtEZWZhdWx0VGV4dAUMZS5nLiBhbmFseXN0HhNEZWZhdWx0VGV4dENzc0NsYXNzZWRkAgsPDxYGHwIFEkxvbmRvbiwgU291dGggRWFzdB8FBQllLmcuIEJhdGgfBmVkZAIRDxAPFgYeDURhdGFUZXh0RmllbGQFClJhZGl1c05hbWUeDkRhdGFWYWx1ZUZpZWxkBQZSYWRpdXMeC18hRGF0YUJvdW5kZ2QQFREHMCBtaWxlcwcyIG1pbGVzBzUgbWlsZXMIMTAgbWlsZXMIMTUgbWlsZXMIMjAgbWlsZXMIMjUgbWlsZXMIMzAgbWlsZXMIMzUgbWlsZXMINDAgbWlsZXMINDUgbWlsZXMINTAgbWlsZXMINjAgbWlsZXMINzAgbWlsZXMIODAgbWlsZXMIOTAgbWlsZXMJMTAwIG1pbGVzFREBMAEyATUCMTACMTUCMjACMjUCMzACMzUCNDACNDUCNTACNjACNzACODACOTADMTAwFCsDEWdnZ2dnZ2dnZ2dnZ2dnZ2dnZGQCFw9kFgQCAQ9kFgQCBA8QZA8WA2YCAQICFgMQBQhBbGwgam9icwUBMGcQBRlEaXJlY3QgZW1wbG95ZXIgam9icyBvbmx5BQEyZxAFEEFnZW5jeSBqb2JzIG9ubHkFATFnZGQCBg8QZA8WA2YCAQICFgMQBQlSZWxldmFuY2UFATFnEAUERGF0ZQUBMmcQBQZTYWxhcnkFATNnZGQCBQ8PFgYeClBhZ2VOdW1iZXICAR4PTnVtYmVyT2ZSZXN1bHRzAlUeDlJlc3VsdHNQZXJQYWdlAhRkZAIZDxYCHwNoZGQ%3D& Refinesearch%24txtKeywords=Python& Refinesearch%24txtLocation=London%2CSouth+East& Refinesearch%24ddlRadius=0& Refinesearch%24btnSearch=Search& ddlCompanyType=0& ddlSort=1' A: The SearchSession cookies are quite different: the working one has SearchSession=SessionGuid=71de63de-3bd0-4787-895d-b6b9e7c93801 and the non-working one has SearchSession=SessionGuid=33e4e439-c2d6-423f-900f-574099310d5a Do you have any way to independently validate why the second one might not be acceptable for the server? (This may not be the case, but since the server's complaining exactly about your SearchSession cookie, it seems it should be the first line of inquiry).
Python Mechanize unable to avoid redirect when Post
I am trying to crawl a site using mechanize. The site provides search results in different pages. When posting to get the next set of results, something is wrong and the server redirects me to the first page, asking mechanize to update the SearchSession Cookie. I have been debugging the requests using Firefox and they look quite the same, and I am unable to find the problem. Any suggestion? Below the requests: ----------- FIRST THE RIGHT SEQUENCE, USING TAMPER IN FIREFOX ------------------------- POST XXX/JobSearch/Results.aspx?Keywords=Python&LTxt=London%2c+South+East&Radius=0&LIds2=ZV&clid=1621&cltypeid=2&clName=London Load Flags[LOAD_DOCUMENT_URI LOAD_INITIAL_DOCUMENT_URI ] Content Size[-1] Mime Type[text/html] Request Headers: Host[www.cwjobs.co.uk] User-Agent[Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.9) Gecko/20100401 Ubuntu/9.10 (karmic) Firefox/3.5.9] Accept[text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8] Accept-Language[en-us,en;q=0.5] Accept-Encoding[gzip,deflate] Accept-Charset[ISO-8859-1,utf-8;q=0.7,*;q=0.7] Keep-Alive[300] Connection[keep-alive] Referer[XXX/JobSearch/Results.aspx?Keywords=Python&LTxt=London%2c+South+East&Radius=0&LIds2=ZV&clid=1621&cltypeid=2&clName=London] Cookie[ecos=774803468-0; AnonymousUser=MemberId=acc079dd-66b6-4081-9b07-60d6955ee8bf&IsAnonymous=True; PJBIPPOPUP=; WT_FPC=id=86.181.183.106-2262469600.30073025:lv=1272812851736:ss=1272812789362; SearchSession=SessionGuid=71de63de-3bd0-4787-895d-b6b9e7c93801&LogSource=NAT] Post Data: __EVENTTARGET[srpPager%24btnForward] __EVENTARGUMENT[] hdnSearchResults[BV%2CA%2CC0P5x%2COou-%2CB4S-%2CBuC-%2CDzx-%2CHwn-%2CKPP-%2CIVA-%2CC9D-%2CH6X-%2CH7x-%2CJ0x-%2CCvX-%2CCra-%2COHa-%2CHhP-%2CCoj-%2CBlM-%2CE9W-%2CIm8-%2CBqG-%2CPFy-%2CN%2Fm-%2Ceaa%2CCvj-%2CCtJ-%2CCr7-%2CBpu-%2Cmh%2CMb6-%2CJ%2Fk-%2CHY8-%2COJ7-%2CNtF-%2CEya-%2CErT-%2CEo4-%2CEKU-%2CDnL-%2CC5M-%2CCyB-%2CBsD-%2CBrc-%2CBpU-%2Col%2C30%2CC1%2Cd4N%2COo8-%2COi0-%2CLz%2F-%2CLxP-%2CFyp-%2CFVR-%2CEHL-%2CPrP-%2CLmE-%2CK3H-%2CKXJ-%2CFyn%2CIcq-%2CIco-%2CIK4-%2CIIg-%2CH2k-%2CH0N-%2CHwp-%2CHvF-%2CFij-%2CFhl-%2CCwj-%2CCb5-%2CCQj-%2CCQh-%2CB%2B2-%2CBc6-%2ChFo%2CNLq-%2CNI%2F-%2CFzM-%2Cdu-%2CHg2-%2CBug-%2CBse-%2CB9Q-] __VIEWSTATE[%2FwEPDwUKLTkyMzI2ODA4Ng9kFgYCBA8WBB4EaHJlZgWJAWh0dHA6Ly93d3cuY3dqb2JzLmNvLnVrL0pvYlNlYXJjaC9SU1MuYXNweD9LZXl3b3Jkcz1QeXRob24mTFR4dD1Mb25kb24lMmMrU291dGgrRWFzdCZSYWRpdXM9MCZMSWRzMj1aViZjbGlkPTE2MjEmY2x0eXBlaWQ9MiZjbE5hbWU9TG9uZG9uHgV0aXRsZQUkTGF0ZXN0IFB5dGhvbiBqb2JzIGZyb20gQ1dKb2JzLmNvLnVrZAIGDxYCHgRUZXh0BV48bGluayByZWw9ImNhbm9uaWNhbCIgaHJlZj0iaHR0cDovL3d3dy5jd2pvYnMuY28udWsvSm9iU2Vla2luZy9QeXRob25fTG9uZG9uX2wxNjIxX3QyLmh0bWwiIC8%2BZAIIEGRkFg4CBw8WAh8CBV9Zb3VyIHNlYXJjaCBvbiA8Yj5LZXl3b3JkczogUHl0aG9uOyBMb2NhdGlvbjogTG9uZG9uLCBTb3V0aCBFYXN0OyA8L2I%2BIHJldHVybmVkIDxiPjg1PC9iPiBqb2JzLmQCCQ8WAh4HVmlzaWJsZWhkAgsPFgIfAgUoVGhlIG1vc3QgcmVsZXZhbnQgam9icyBhcmUgbGlzdGVkIGZpcnN0LmQCEw8PFgIeC05hdmlnYXRlVXJsBQF%2BZGQCFQ9kFgYCBQ8PFgYfAgUGUHl0aG9uHgtEZWZhdWx0VGV4dAUMZS5nLiBhbmFseXN0HhNEZWZhdWx0VGV4dENzc0NsYXNzZWRkAgsPDxYGHwIFEkxvbmRvbiwgU291dGggRWFzdB8FBQllLmcuIEJhdGgfBmVkZAIRDxAPFgYeDURhdGFUZXh0RmllbGQFClJhZGl1c05hbWUeDkRhdGFWYWx1ZUZpZWxkBQZSYWRpdXMeC18hRGF0YUJvdW5kZ2QQFREHMCBtaWxlcwcyIG1pbGVzBzUgbWlsZXMIMTAgbWlsZXMIMTUgbWlsZXMIMjAgbWlsZXMIMjUgbWlsZXMIMzAgbWlsZXMIMzUgbWlsZXMINDAgbWlsZXMINDUgbWlsZXMINTAgbWlsZXMINjAgbWlsZXMINzAgbWlsZXMIODAgbWlsZXMIOTAgbWlsZXMJMTAwIG1pbGVzFREBMAEyATUCMTACMTUCMjACMjUCMzACMzUCNDACNDUCNTACNjACNzACODACOTADMTAwFCsDEWdnZ2dnZ2dnZ2dnZ2dnZ2dnZGQCFw9kFgQCAQ9kFgQCBA8QZA8WA2YCAQICFgMQBQhBbGwgam9icwUBMGcQBRlEaXJlY3QgZW1wbG95ZXIgam9icyBvbmx5BQEyZxAFEEFnZW5jeSBqb2JzIG9ubHkFATFnZGQCBg8QZA8WA2YCAQICFgMQBQlSZWxldmFuY2UFATFnEAUERGF0ZQUBMmcQBQZTYWxhcnkFATNnZGQCBQ8PFgYeClBhZ2VOdW1iZXICAh4PTnVtYmVyT2ZSZXN1bHRzAlUeDlJlc3VsdHNQZXJQYWdlAhRkZAIZDxYCHwNoZGQ%3D] Refinesearch%24txtKeywords[Python] Refinesearch%24txtLocation[London%2C+South+East] Refinesearch%24ddlRadius[0] ddlCompanyType[0] ddlSort[1] Response Headers: Cache-Control[private] Date[Sun, 02 May 2010 16:09:27 GMT] Content-Type[text/html; charset=utf-8] Expires[Sat, 02 May 2009 16:09:27 GMT] Server[Microsoft-IIS/6.0] X-SiteConHost[P310] X-Powered-By[ASP.NET] X-AspNet-Version[2.0.50727] Set-Cookie[SearchSession=SessionGuid=71de63de-3bd0-4787-895d-b6b9e7c93801&LogSource=NAT; path=/] Content-Encoding[gzip] Vary[Accept-Encoding] Transfer-Encoding[chunked] -------- NOW WHAT I'AM SENDING USING MECHANIZE, SOME HEADERS ADDED, ETC ----------- POST /JobSearch/Results.aspx?Keywords=Python&LTxt=London%2c+South+East&Radius=0&LIds2=ZV&clid=1621&cltypeid=2&clName=London HTTP/1.1\r\nContent-Length: 2424\r\n Accept-Language: en-us,en;q=0.5\r\n Accept-Encoding: gzip\r\n Host: www.cwjobs.co.uk\r\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8\r\n Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n Connection: keep-alive\r\n Cookie: AnonymousUser=MemberId=8fa5ddd7-17ed-425e-b189-82693bfbaa0c&IsAnonymous=True; SearchSession=SessionGuid=33e4e439-c2d6-423f-900f-574099310d5a&LogSource=NAT\r\n Referer: XXX/JobSearch/Results.aspx?Keywords=Python&LTxt=London%2c+South+East&Radius=0&LIds2=ZV&clid=1621&cltypeid=2&clName=London\r\n Content-Type: application/x-www-form-urlencoded\r\n\r\n' '__EVENTTARGET=srpPager%24btnForward& __EVENTARGUMENT=& hdnSearchResults=BV%2CA%2CC0eif%2CMwc%2CM6s%2COou%2CK09%2CG4H%2CEZf%2CGTu%2CLrr%2CGuX%2CGs9%2CEz9%2CL5X%2CL9U%2ChU%2CHHf%2CMAL%2CNDi%2CJrY%2CGBy%2CM%2Bo%2CdE-%2CpI%2CtDI%2CL5L%2CL7l%2CL8z%2CM%2FA%2CPPP%2CCM0%2CEpK%2CHPy%2Cez%2C7p%2CJ2U%2CJ9b%2CJ%2F2%2CKea%2CLBj%2CLvi%2CL2t%2CM8r%2CM9S%2CM%2Fa%2CPRT%2CPgi%2Csg7%2CF6%2CI2F%2CJTd%2CO-%2CC0v%2CC3f%2CDCq%2CDxn%2CERl%2CUbV%2CGME%2CGMG%2CGd2%2CGgO%2CGyK%2CG0h%2CG4F%2CG5p%2CJGL%2CJHJ%2CKhj%2CL4L%2CMM1%2CMYL%2CMYN%2CMp4%2CNL0%2COrj%2CvuW%2CBdE%2CBfv%2CI1i%2CBCh-%2COLA%2CHH4%2CM6O%2CM8Q%2CMre& __VIEWSTATE=%2FwEPDwUKLTkyMzI2ODA4Ng9kFgYCBA8WBB4EaHJlZgWJAWh0dHA6Ly93d3cuY3dqb2JzLmNvLnVrL0pvYlNlYXJjaC9SU1MuYXNweD9LZXl3b3Jkcz1QeXRob24mTFR4dD1Mb25kb24lMmMrU291dGgrRWFzdCZSYWRpdXM9MCZMSWRzMj1aViZjbGlkPTE2MjEmY2x0eXBlaWQ9MiZjbE5hbWU9TG9uZG9uHgV0aXRsZQUkTGF0ZXN0IFB5dGhvbiBqb2JzIGZyb20gQ1dKb2JzLmNvLnVrZAIGDxYCHgRUZXh0BV48bGluayByZWw9ImNhbm9uaWNhbCIgaHJlZj0iaHR0cDovL3d3dy5jd2pvYnMuY28udWsvSm9iU2Vla2luZy9QeXRob25fTG9uZG9uX2wxNjIxX3QyLmh0bWwiIC8%2BZAIIEGRkFg4CBw8WAh8CBV9Zb3VyIHNlYXJjaCBvbiA8Yj5LZXl3b3JkczogUHl0aG9uOyBMb2NhdGlvbjogTG9uZG9uLCBTb3V0aCBFYXN0OyA8L2I%2BIHJldHVybmVkIDxiPjg1PC9iPiBqb2JzLmQCCQ8WAh4HVmlzaWJsZWhkAgsPFgIfAgUoVGhlIG1vc3QgcmVsZXZhbnQgam9icyBhcmUgbGlzdGVkIGZpcnN0LmQCEw8PFgIeC05hdmlnYXRlVXJsBQF%2BZGQCFQ9kFgYCBQ8PFgYfAgUGUHl0aG9uHgtEZWZhdWx0VGV4dAUMZS5nLiBhbmFseXN0HhNEZWZhdWx0VGV4dENzc0NsYXNzZWRkAgsPDxYGHwIFEkxvbmRvbiwgU291dGggRWFzdB8FBQllLmcuIEJhdGgfBmVkZAIRDxAPFgYeDURhdGFUZXh0RmllbGQFClJhZGl1c05hbWUeDkRhdGFWYWx1ZUZpZWxkBQZSYWRpdXMeC18hRGF0YUJvdW5kZ2QQFREHMCBtaWxlcwcyIG1pbGVzBzUgbWlsZXMIMTAgbWlsZXMIMTUgbWlsZXMIMjAgbWlsZXMIMjUgbWlsZXMIMzAgbWlsZXMIMzUgbWlsZXMINDAgbWlsZXMINDUgbWlsZXMINTAgbWlsZXMINjAgbWlsZXMINzAgbWlsZXMIODAgbWlsZXMIOTAgbWlsZXMJMTAwIG1pbGVzFREBMAEyATUCMTACMTUCMjACMjUCMzACMzUCNDACNDUCNTACNjACNzACODACOTADMTAwFCsDEWdnZ2dnZ2dnZ2dnZ2dnZ2dnZGQCFw9kFgQCAQ9kFgQCBA8QZA8WA2YCAQICFgMQBQhBbGwgam9icwUBMGcQBRlEaXJlY3QgZW1wbG95ZXIgam9icyBvbmx5BQEyZxAFEEFnZW5jeSBqb2JzIG9ubHkFATFnZGQCBg8QZA8WA2YCAQICFgMQBQlSZWxldmFuY2UFATFnEAUERGF0ZQUBMmcQBQZTYWxhcnkFATNnZGQCBQ8PFgYeClBhZ2VOdW1iZXICAR4PTnVtYmVyT2ZSZXN1bHRzAlUeDlJlc3VsdHNQZXJQYWdlAhRkZAIZDxYCHwNoZGQ%3D& Refinesearch%24txtKeywords=Python& Refinesearch%24txtLocation=London%2CSouth+East& Refinesearch%24ddlRadius=0& Refinesearch%24btnSearch=Search& ddlCompanyType=0& ddlSort=1'
[ "The SearchSession cookies are quite different: the working one has\nSearchSession=SessionGuid=71de63de-3bd0-4787-895d-b6b9e7c93801\n\nand the non-working one has\nSearchSession=SessionGuid=33e4e439-c2d6-423f-900f-574099310d5a\n\nDo you have any way to independently validate why the second one might not be acceptable for the server? (This may not be the case, but since the server's complaining exactly about your SearchSession cookie, it seems it should be the first line of inquiry).\n" ]
[ 1 ]
[]
[]
[ "mechanize", "post", "python", "redirect" ]
stackoverflow_0002754922_mechanize_post_python_redirect.txt
Q: Algorithm detect repeating/similiar strings in a corpus of data -- say email subjects, in Python I'm downloading a long list of my email subject lines , with the intent of finding email lists that I was a member of years ago, and would want to purge them from my Gmail account (which is getting pretty slow.) I'm specifically thinking of newsletters that often come from the same address, and repeat the product/service/group's name in the subject. I'm aware that I could search/sort by the common occurrence of items from a particular email address (and I intend to), but I'd like to correlate that data with repeating subject lines.... Now, many subject lines would fail a string match, but "Google Friends : Our latest news" "Google Friends : What we're doing today" are more similar to each other than a random subject line, as is: "Virgin Airlines has a great sale today" "Take a flight with Virgin Airlines" So -- how can I start to automagically extract trends/examples of strings that may be more similar. Approaches I've considered and discarded ('because there must be some better way'): Extracting all the possible substrings and ordering them by how often they show up, and manually selecting relevant ones Stripping off the first word or two and then count the occurrence of each sub string Comparing Levenshtein distance between entries Some sort of string similarity index ... Most of these were rejected for massive inefficiency or likelyhood of a vast amount of manual intervention required. I guess I need some sort of fuzzy string matching..? In the end, I can think of kludgy ways of doing this, but I'm looking for something more generic so I've added to my set of tools rather than special casing for this data set. After this, I'd be matching the occurring of particular subject strings with 'From' addresses - I'm not sure if there's a good way of building a data structure that represents how likely/not two messages are part of the 'same email list' or by filtering all my email subjects/from addresses into pools of likely 'related' emails and not -- but that's a problem to solve after this one. Any guidance would be appreciated. A: I would first turn each string of characters into a set or multiset of words (ignoring punctuation and differences in lower/upper case). (If that's not powerful enough, in a second pass I could try pairs or even triples of adjacent words, known as bigrams and trigrams). The key measure of similarity between strings thus reduced is, what words that are not high frequency overall (not the, and, etc;-) are common to both strings, so a simple set intersection (or multiset intersection, but for your simple use case I think just sets would work fine, esp. sets of bigrams) should suffice to measure the "commonality". A word that's common to the two strings should be worth more the rarer it is, so negative log of frequency of the word across the whole corpus is an excellent starting point for this heuristics. A: Smooth BLEU You might be able to make use of the smooth-BLEU score between the subjects. BLEU is an evaluation metric that is used to score how similar the translations produced by a machine translation system are to translations produced by humans. Smooth BLEU is calculated like the normal BLEU score, except that you add one to the n-gram match counts so that you avoid multiplying anything by zero when evaluating short segments of text. Smooth-BLEU should be much faster to compute than the Levenshtein distance, while still capturing word order information, since it looks at n-gram matches rather than just matches between single words. Unfortunately, I don't have a pointer to a Python BLEU implementation, but you'll find a Perl implementation from NIST here.
Algorithm detect repeating/similiar strings in a corpus of data -- say email subjects, in Python
I'm downloading a long list of my email subject lines , with the intent of finding email lists that I was a member of years ago, and would want to purge them from my Gmail account (which is getting pretty slow.) I'm specifically thinking of newsletters that often come from the same address, and repeat the product/service/group's name in the subject. I'm aware that I could search/sort by the common occurrence of items from a particular email address (and I intend to), but I'd like to correlate that data with repeating subject lines.... Now, many subject lines would fail a string match, but "Google Friends : Our latest news" "Google Friends : What we're doing today" are more similar to each other than a random subject line, as is: "Virgin Airlines has a great sale today" "Take a flight with Virgin Airlines" So -- how can I start to automagically extract trends/examples of strings that may be more similar. Approaches I've considered and discarded ('because there must be some better way'): Extracting all the possible substrings and ordering them by how often they show up, and manually selecting relevant ones Stripping off the first word or two and then count the occurrence of each sub string Comparing Levenshtein distance between entries Some sort of string similarity index ... Most of these were rejected for massive inefficiency or likelyhood of a vast amount of manual intervention required. I guess I need some sort of fuzzy string matching..? In the end, I can think of kludgy ways of doing this, but I'm looking for something more generic so I've added to my set of tools rather than special casing for this data set. After this, I'd be matching the occurring of particular subject strings with 'From' addresses - I'm not sure if there's a good way of building a data structure that represents how likely/not two messages are part of the 'same email list' or by filtering all my email subjects/from addresses into pools of likely 'related' emails and not -- but that's a problem to solve after this one. Any guidance would be appreciated.
[ "I would first turn each string of characters into a set or multiset of words (ignoring punctuation and differences in lower/upper case). (If that's not powerful enough, in a second pass I could try pairs or even triples of adjacent words, known as bigrams and trigrams). The key measure of similarity between strings thus reduced is, what words that are not high frequency overall (not the, and, etc;-) are common to both strings, so a simple set intersection (or multiset intersection, but for your simple use case I think just sets would work fine, esp. sets of bigrams) should suffice to measure the \"commonality\". A word that's common to the two strings should be worth more the rarer it is, so negative log of frequency of the word across the whole corpus is an excellent starting point for this heuristics.\n", "Smooth BLEU\nYou might be able to make use of the smooth-BLEU score between the subjects. BLEU is an evaluation metric that is used to score how similar the translations produced by a machine translation system are to translations produced by humans. Smooth BLEU is calculated like the normal BLEU score, except that you add one to the n-gram match counts so that you avoid multiplying anything by zero when evaluating short segments of text.\nSmooth-BLEU should be much faster to compute than the Levenshtein distance, while still capturing word order information, since it looks at n-gram matches rather than just matches between single words.\nUnfortunately, I don't have a pointer to a Python BLEU implementation, but you'll find a Perl implementation from NIST here. \n" ]
[ 4, 1 ]
[]
[]
[ "data_mining", "email", "fuzzy_search", "python", "string" ]
stackoverflow_0002752022_data_mining_email_fuzzy_search_python_string.txt
Q: Python invalid syntax with "with" statement I am working on writing a simple python application for linux (maemo). However I am getting SyntaxError: invalid syntax on line 23: with open(file,'w') as fileh: The code can be seen here: http://pastebin.com/MPxfrsAp I can not figure out what is wrong with my code, I am new to python and the "with" statement. So, what is causing this code to error, and how can I fix it? Is it something wrong with the "with" statement? Thanks! A: Most likely, you are using an earlier version of Python that doesn't support the with statement. Here's how to do the same thing without using with: fileh = open(file, 'w') try: # Do things with fileh here finally: fileh.close()
Python invalid syntax with "with" statement
I am working on writing a simple python application for linux (maemo). However I am getting SyntaxError: invalid syntax on line 23: with open(file,'w') as fileh: The code can be seen here: http://pastebin.com/MPxfrsAp I can not figure out what is wrong with my code, I am new to python and the "with" statement. So, what is causing this code to error, and how can I fix it? Is it something wrong with the "with" statement? Thanks!
[ "Most likely, you are using an earlier version of Python that doesn't support the with statement. Here's how to do the same thing without using with:\nfileh = open(file, 'w')\ntry:\n # Do things with fileh here\nfinally:\n fileh.close()\n\n" ]
[ 26 ]
[]
[]
[ "python", "syntax", "syntax_error" ]
stackoverflow_0002755849_python_syntax_syntax_error.txt
Q: Python questions from beginner I'm thinking about rewriting an MS Access db I wrote years ago into a stand-alone Python app. Other than a college class called "Intro to C++" (console only, with OOP concepts) and the Access db itself, I have no experience, so I need to ask if the basis for my decision to go with Python is correct. Is it true that: 1) Python is relatively easy to pick up? 2) Python apps can run as "portable" (ie from one directory, no registry needs, nothing needs to be pre-installed on a Windows PC) as long as I use an embedded db? A: Python is widely considered an easy language to learn, being simple and readable. For easy running of Python on any Windows PC I recommend Portable Python (other platforms such as Macs and Linux distros typically come with Python, so there's usually no need for such measures there). For running a pre-made, pre-package app with its own sqlite database, I recommend pyInstaller, which is also cross-platform. A: Python is like the game Go, the rules are easy, but it's hard to master. You'll get started easily, but if you wind up using it as an interpreted version of VB, or C, you'll be missing much of the point. More to the point, if your Access application is UI-centric, Python is not necessarily the natural platform to port it to. Python does not specialize, or particularly excel, in building UIs and there's no "visual"-style application builder (that I know of) as in Access. If your application is more oriented towards reading, manipulating, and writing data, however, Python is ideal. A: 1) Yes, if you grasped the material in your intro to C++ class you should be able to pick up the basics of Python without too much trouble 2) It can be. There's Py2Exe which can include the necessary python files to run standalone. Otherwise Python will need to be installed. A: to answer your questions: 1) yes, it is relatively easy to pick up. however, as @Larry mentions, it still takes time and experience to master. i've been using it for 14 straight years, and i still feel like i know less than half of everything out there. of course, the Python universe continues to expand every day, so that may be the cause. :-) 2) Python is indeed portable, but as @Alex mentions, only POSIX systems (i.e., Mac OS X, Linux, *BSD, etc.) come with Python installed while PCs require a download, thus making PortablePython an option for moving around a directory tree which can be used for development. More specifically, you can use PyInstaller (multi-platform) or py2exe (PCs only; py2app is a Mac equivalent) to generate standalone executables that can be distributed to computers that don't require Python to already be installed. To develop apps for MS Access, you will likely need to download the Python Extensions for Windows package (win32all) and use a COM interface. (Although I do not have an example of an Access app in my Python book, I do have COM client Python examples interacting with Word, Excel, PowerPoint, and Outlook in Chapter 23 of Core Python Programming.) A more modern alternative is to use IronPython on the .NET or Mono platforms. As far as UI stuff goes, win32all also gives you access to creating MFC apps. A: Python is easy to pick up, yes. That doesn't mean you master it as easily :) You can use Portable Python if on Windows (or even py2exe) for the portability part, and perhaps Dabo will be close enough to Access for the database+GUI part.
Python questions from beginner
I'm thinking about rewriting an MS Access db I wrote years ago into a stand-alone Python app. Other than a college class called "Intro to C++" (console only, with OOP concepts) and the Access db itself, I have no experience, so I need to ask if the basis for my decision to go with Python is correct. Is it true that: 1) Python is relatively easy to pick up? 2) Python apps can run as "portable" (ie from one directory, no registry needs, nothing needs to be pre-installed on a Windows PC) as long as I use an embedded db?
[ "Python is widely considered an easy language to learn, being simple and readable. For easy running of Python on any Windows PC I recommend Portable Python (other platforms such as Macs and Linux distros typically come with Python, so there's usually no need for such measures there). For running a pre-made, pre-package app with its own sqlite database, I recommend pyInstaller, which is also cross-platform.\n", "Python is like the game Go, the rules are easy, but it's hard to master. You'll get started easily, but if you wind up using it as an interpreted version of VB, or C, you'll be missing much of the point.\nMore to the point, if your Access application is UI-centric, Python is not necessarily the natural platform to port it to. Python does not specialize, or particularly excel, in building UIs and there's no \"visual\"-style application builder (that I know of) as in Access.\nIf your application is more oriented towards reading, manipulating, and writing data, however, Python is ideal.\n", "1) Yes, if you grasped the material in your intro to C++ class you should be able to pick up the basics of Python without too much trouble\n2) It can be. There's Py2Exe which can include the necessary python files to run standalone. Otherwise Python will need to be installed. \n", "to answer your questions:\n1) yes, it is relatively easy to pick up. however, as @Larry mentions, it still takes time and experience to master. i've been using it for 14 straight years, and i still feel like i know less than half of everything out there. of course, the Python universe continues to expand every day, so that may be the cause. :-)\n2) Python is indeed portable, but as @Alex mentions, only POSIX systems (i.e., Mac OS X, Linux, *BSD, etc.) come with Python installed while PCs require a download, thus making PortablePython an option for moving around a directory tree which can be used for development. More specifically, you can use PyInstaller (multi-platform) or py2exe (PCs only; py2app is a Mac equivalent) to generate standalone executables that can be distributed to computers that don't require Python to already be installed.\nTo develop apps for MS Access, you will likely need to download the Python Extensions for Windows package (win32all) and use a COM interface. (Although I do not have an example of an Access app in my Python book, I do have COM client Python examples interacting with Word, Excel, PowerPoint, and Outlook in Chapter 23 of Core Python Programming.) A more modern alternative is to use IronPython on the .NET or Mono platforms. As far as UI stuff goes, win32all also gives you access to creating MFC apps.\n", "Python is easy to pick up, yes. That doesn't mean you master it as easily :)\nYou can use Portable Python if on Windows (or even py2exe) for the portability part, and perhaps Dabo will be close enough to Access for the database+GUI part.\n" ]
[ 5, 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002752055_python.txt
Q: How to pass elements of a list as arguments to a function? I'm building a simple interpreter in python and I'm having trouble handling differing numbers of arguments to my functions. My current method is to get a list of the commands/arguments as follows. args = str(raw_input('>> ')).split() com = args.pop(0) Then to execute com, I check to see if it is in my dictionary of command-> code mappings and if it is I call the function I have stored there. For a command with no arguments, this would look like: commands[com]() However, if a command had multiple arguments, I would want this: commands[com](args[0],args[1]) Is there some trick where I could pass some (or all) of the elements of my arg list to the function that I'm trying to call? Or is there a better way of implementing this without having to use Python's Cmd class? A: Try unpacking your list into positional arguments: commands[com](*args)
How to pass elements of a list as arguments to a function?
I'm building a simple interpreter in python and I'm having trouble handling differing numbers of arguments to my functions. My current method is to get a list of the commands/arguments as follows. args = str(raw_input('>> ')).split() com = args.pop(0) Then to execute com, I check to see if it is in my dictionary of command-> code mappings and if it is I call the function I have stored there. For a command with no arguments, this would look like: commands[com]() However, if a command had multiple arguments, I would want this: commands[com](args[0],args[1]) Is there some trick where I could pass some (or all) of the elements of my arg list to the function that I'm trying to call? Or is there a better way of implementing this without having to use Python's Cmd class?
[ "Try unpacking your list into positional arguments:\ncommands[com](*args)\n\n" ]
[ 14 ]
[]
[]
[ "arguments", "list", "python" ]
stackoverflow_0002756116_arguments_list_python.txt
Q: How do I generate coverage xml report for a single package? I'm using nose and coverage to generate coverage reports. I only have one package right now, ae, so I specify to only cover that: nosetests -w tests/unit --with-xunit --with-coverage --cover-package=ae And here are the results, which look good: Name Stmts Exec Cover Missing ---------------------------------------------- ae 1 1 100% ae.util 253 224 88% 39, 63-65, 284, 287, 362, 406 ---------------------------------------------- TOTAL 263 234 88% ---------------------------------------------------------------------- Ran 68 tests in 5.292s However when I run coverage xml, coverage pulls in more packages than necessary, including python email and logging packages which have nothing to do with my code. If I run coverage xml ae, I get this error: No source for code: '/home/wraith/dev/projects/trimurti/src/ae': [Errno 21] Is a directory: '/home/wraith/dev/projects/trimurti/src/ae' Is there a way to generate the XML for just the ae package? A: I had a similar problem and solved it with the --omit option. This made it run much faster and reduced the size of coverage.xml from 2MB to 70kB. --omit=PRE1,PRE2,... Omit files when their filename path starts with one of these prefixes. I'm on Mac OS X, so I omitted the /Library/ and /Applications/ folders: $ coverage xml --omit=/Library/,/Applications/ On other systems, you may find --omit=/usr/ more helpful. A: Did you try: coverage xml ae A: I wasn't able to find the answer to this, so I'm stripping the unwanted package elements out after processing. This function takes the original XML file, the element name to check, its attribute to check, the pattern (or list of words) you'd like to KEEP, and a destination filepath for the new file. from lxml import etree def keep(self, xmlfile, elem_name, attr_name, pattern, dst): try: rep = re.compile(pattern) except TypeError: # Create regex pattern if a list is given. # TypeError: unhashable type: 'list' rep = re.compile("|".join(pattern)) dom = etree.parse(xmlfile) for node in dom.findall('//%s' % elem_name): if not rep.search(node.get(attr_name)): node.getparent().remove(node) dom.write(dst) To solve my problem, I'm calling it like this: keep('coverage.xml', 'package', 'name', 'ae|tests', 'wanted-coverage.xml')
How do I generate coverage xml report for a single package?
I'm using nose and coverage to generate coverage reports. I only have one package right now, ae, so I specify to only cover that: nosetests -w tests/unit --with-xunit --with-coverage --cover-package=ae And here are the results, which look good: Name Stmts Exec Cover Missing ---------------------------------------------- ae 1 1 100% ae.util 253 224 88% 39, 63-65, 284, 287, 362, 406 ---------------------------------------------- TOTAL 263 234 88% ---------------------------------------------------------------------- Ran 68 tests in 5.292s However when I run coverage xml, coverage pulls in more packages than necessary, including python email and logging packages which have nothing to do with my code. If I run coverage xml ae, I get this error: No source for code: '/home/wraith/dev/projects/trimurti/src/ae': [Errno 21] Is a directory: '/home/wraith/dev/projects/trimurti/src/ae' Is there a way to generate the XML for just the ae package?
[ "I had a similar problem and solved it with the --omit option. This made it run much faster and reduced the size of coverage.xml from 2MB to 70kB.\n--omit=PRE1,PRE2,... Omit files when their filename path starts with one of\n these prefixes.\n\nI'm on Mac OS X, so I omitted the /Library/ and /Applications/ folders:\n$ coverage xml --omit=/Library/,/Applications/\n\nOn other systems, you may find --omit=/usr/ more helpful.\n", "Did you try:\ncoverage xml ae\n\n", "I wasn't able to find the answer to this, so I'm stripping the unwanted package elements out after processing. This function takes the original XML file, the element name to check, its attribute to check, the pattern (or list of words) you'd like to KEEP, and a destination filepath for the new file. \nfrom lxml import etree\n\ndef keep(self, xmlfile, elem_name, attr_name, pattern, dst):\n try: \n rep = re.compile(pattern)\n except TypeError:\n # Create regex pattern if a list is given. \n # TypeError: unhashable type: 'list'\n rep = re.compile(\"|\".join(pattern))\n\n dom = etree.parse(xmlfile)\n for node in dom.findall('//%s' % elem_name):\n if not rep.search(node.get(attr_name)):\n node.getparent().remove(node)\n\n dom.write(dst)\n\nTo solve my problem, I'm calling it like this: \nkeep('coverage.xml', 'package', 'name', 'ae|tests', 'wanted-coverage.xml')\n\n" ]
[ 3, 0, 0 ]
[]
[]
[ "code_coverage", "coverage.py", "nose", "python" ]
stackoverflow_0002293647_code_coverage_coverage.py_nose_python.txt
Q: defining information out of class is there a way to define a value within a class in the __init__ part, send it to some variable outside of the class without calling another function within the class? like class c: def __init__(self, a): self.a = a b = 4 # do something like this so that outside of class c, # b is set to 4 automatically for the entire program # when i use class c def function(self): ... # whatever. this doesnt matter i have multiple classes that have different values for b. i could just make a list that tells the computer to change b, but i would rather set b within each class A: I'm not sure I understood the question correctly, but try adding this line into the __init__: global b Before assignment to b I mean. Like the first line of the function. A: Since globals are bad, try a class variable. (Is there any reason you can't?) For example: class C(object): def __init__(self,a): self.a=a C.b=4 or, better yet: class C(object): b=4 def __init__(self,a): self.a=a global, as doublep suggests, will bind to a variable global to the module. Since it's limited to the module namespace, it's not that bad an option. A: Basically, the answer is no. You can make a parent class that does the callback for you, then you won't need to think about it beyond passing the b value to the parent class constructor. But unless you want to use global variables (which is not a good idea), there is no way to return a value from a constructor that is not the object.
defining information out of class
is there a way to define a value within a class in the __init__ part, send it to some variable outside of the class without calling another function within the class? like class c: def __init__(self, a): self.a = a b = 4 # do something like this so that outside of class c, # b is set to 4 automatically for the entire program # when i use class c def function(self): ... # whatever. this doesnt matter i have multiple classes that have different values for b. i could just make a list that tells the computer to change b, but i would rather set b within each class
[ "I'm not sure I understood the question correctly, but try adding this line into the __init__:\nglobal b\n\nBefore assignment to b I mean. Like the first line of the function.\n", "Since globals are bad, try a class variable. (Is there any reason you can't?) For example:\nclass C(object):\n def __init__(self,a):\n self.a=a\n C.b=4\n\nor, better yet:\nclass C(object):\n b=4\n def __init__(self,a):\n self.a=a\n\nglobal, as doublep suggests, will bind to a variable global to the module. Since it's limited to the module namespace, it's not that bad an option.\n", "Basically, the answer is no. You can make a parent class that does the callback for you, then you won't need to think about it beyond passing the b value to the parent class constructor. But unless you want to use global variables (which is not a good idea), there is no way to return a value from a constructor that is not the object.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "class_design", "python" ]
stackoverflow_0002755380_class_design_python.txt
Q: New at Python: GLPK not building properly / Python ImportError This is a beginner question, and a follow-up to this one, where I was pointed to GLPK. I'm trying to get PyGLPK, a Python binding for the GNU Linear Programming Kit up and running, but no matter what I do, I can't seem to build and install GLPK so that Python finds it correctly. This comes after running ./configure, make, and sudo make install on the GLPK libraries, and following the instructions for PyGLPK. Specifically, here is the error I get: >>> import glpk Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/glpk.so, 2): Symbol not found: __glp_lpx_print_ips Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/glpk.so Expected in: dynamic lookup I assume that something isn't linking to somewhere else, and that it probably has something to do with paths and environment variables. However, here's where my abilities in the shell fail, and I'm at a loss over what to do next. Edits I'm able to run the GLPK Solver (glpsol) from the command line, so I know that it works, at least in theory. At one point I tried using MacPorts to install a version of GLPK. I've since uninstalled this version, albeit using MacPorts. Here's the result of using otool -L, which apparently is the OS X answer to ldd: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/glpk.so: /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.11) Again, there is probably a simple answer to this, but I haven't had any luck with Google using the terminology I know. A: The problem isn't really specific to Python. The glpk module is an extension module, a C shared library that Python loads. That C shared library has a dependency on the GLPK C library that it wraps; loading the extension module should load the GLPK C library so that the extension module can reference symbols from the GLPK C library, like __glp_lpx_print_ips. Apparently, something there is failing. It could be one of several things: The glpk.so extension module may not be linked against the GLPK C library at all. That would mean it was built without the -l argument necessary to link against the GLPK library, which means the problem is in the build procedure for the glpk extension module. You can tell whether glpk.so depends on the C library by using the ldd tool. For example: % ldd /usr/lib/python2.6/lib-dynload/gdbm.so linux-gate.so.1 => (0xb77bb000) libgdbm.so.3 => /usr/lib/libgdbm.so.3 (0xb7799000) libpthread.so.0 => /lib/i686/cmov/libpthread.so.0 (0xb7780000) libc.so.6 => /lib/i686/cmov/libc.so.6 (0xb7639000) /lib/ld-linux.so.2 (0xb77bc000) That shows my gdbm extension module is linked against the libgdbm shared library (as well as those other shared libraries.) The glpk.so extension module may be linked against the GLPK C library correctly, but the dynamic linker may not be able to find the C library. Usually this produces a different warning (about not being able to find the C library) but this may not happen on MacOS. You can see this by again using the ldd tool: it'll list the dependency but not the actual file that is loaded (it'll say "not found" instead.) This is usually caused by not installing the C library, or by installing it somewhere the dynamic linker doesn't know to look. Unfortunately I don't know how MacOS X does its library lookup, and how you're supposed to modify the paths it scans. (On most UNIX systems you'd edit /etc/ld.so.conf or a file in /etc/ld.so.conf.d/, or run ldconfig -m.) The glpk.so extension module may be linked correctly, and the dynamic linker may find the module correctly, but the GLPK extension module may not define this symbol after all. That could be a bug in GLPK, or it could be because the dynamic linker is finding a different GLPK C library (a different version, or one that is built differently), or it could be because the GLPK C library was compiled differently than the glpk.so extension module was. That's a little hard to diagnose, though, as it means digging into the actual C library symbols and the header files used during compilation. I would guess, all things considered, the problem is #2. It's the most common problem, especially when installing in /usr/local, which is what ./configure without a --prefix argument usually does. A: Solved the problem! Thomas Wouter's first suggestion was closest to the mark: the glpk.so module wasn't linked to the C library at all. The reason was that make built the original GLPK libraries using gcc4.2 and specifying a 64-bit architecture , while Python's distutils module insisted on building PyGLPK's source code using gcc-4.0 with a 32-bit architecture. Since I couldn't figure out how to add compiler flags to distutils, I just rebuilt the GLPK libraries forcing distutils compiler flags. This was what finally worked. This seems to be an issue with OS X 10.6. ./configure scripts query the system architecture, which by default, I think, is x86_64, even though Python 2.6 plays best with 32-bit binaries.
New at Python: GLPK not building properly / Python ImportError
This is a beginner question, and a follow-up to this one, where I was pointed to GLPK. I'm trying to get PyGLPK, a Python binding for the GNU Linear Programming Kit up and running, but no matter what I do, I can't seem to build and install GLPK so that Python finds it correctly. This comes after running ./configure, make, and sudo make install on the GLPK libraries, and following the instructions for PyGLPK. Specifically, here is the error I get: >>> import glpk Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/glpk.so, 2): Symbol not found: __glp_lpx_print_ips Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/glpk.so Expected in: dynamic lookup I assume that something isn't linking to somewhere else, and that it probably has something to do with paths and environment variables. However, here's where my abilities in the shell fail, and I'm at a loss over what to do next. Edits I'm able to run the GLPK Solver (glpsol) from the command line, so I know that it works, at least in theory. At one point I tried using MacPorts to install a version of GLPK. I've since uninstalled this version, albeit using MacPorts. Here's the result of using otool -L, which apparently is the OS X answer to ldd: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/glpk.so: /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.11) Again, there is probably a simple answer to this, but I haven't had any luck with Google using the terminology I know.
[ "The problem isn't really specific to Python. The glpk module is an extension module, a C shared library that Python loads. That C shared library has a dependency on the GLPK C library that it wraps; loading the extension module should load the GLPK C library so that the extension module can reference symbols from the GLPK C library, like __glp_lpx_print_ips. Apparently, something there is failing. It could be one of several things:\n\nThe glpk.so extension module may not be linked against the GLPK C library at all. That would mean it was built without the -l argument necessary to link against the GLPK library, which means the problem is in the build procedure for the glpk extension module. You can tell whether glpk.so depends on the C library by using the ldd tool. For example:\n% ldd /usr/lib/python2.6/lib-dynload/gdbm.so \nlinux-gate.so.1 => (0xb77bb000)\nlibgdbm.so.3 => /usr/lib/libgdbm.so.3 (0xb7799000)\nlibpthread.so.0 => /lib/i686/cmov/libpthread.so.0 (0xb7780000)\nlibc.so.6 => /lib/i686/cmov/libc.so.6 (0xb7639000)\n/lib/ld-linux.so.2 (0xb77bc000)\n\nThat shows my gdbm extension module is linked against the libgdbm shared library (as well as those other shared libraries.)\nThe glpk.so extension module may be linked against the GLPK C library correctly, but the dynamic linker may not be able to find the C library. Usually this produces a different warning (about not being able to find the C library) but this may not happen on MacOS. You can see this by again using the ldd tool: it'll list the dependency but not the actual file that is loaded (it'll say \"not found\" instead.)\nThis is usually caused by not installing the C library, or by installing it somewhere the dynamic linker doesn't know to look. Unfortunately I don't know how MacOS X does its library lookup, and how you're supposed to modify the paths it scans. (On most UNIX systems you'd edit /etc/ld.so.conf or a file in /etc/ld.so.conf.d/, or run ldconfig -m.)\nThe glpk.so extension module may be linked correctly, and the dynamic linker may find the module correctly, but the GLPK extension module may not define this symbol after all. That could be a bug in GLPK, or it could be because the dynamic linker is finding a different GLPK C library (a different version, or one that is built differently), or it could be because the GLPK C library was compiled differently than the glpk.so extension module was. That's a little hard to diagnose, though, as it means digging into the actual C library symbols and the header files used during compilation.\n\nI would guess, all things considered, the problem is #2. It's the most common problem, especially when installing in /usr/local, which is what ./configure without a --prefix argument usually does.\n", "Solved the problem!\nThomas Wouter's first suggestion was closest to the mark: the glpk.so module wasn't linked to the C library at all. The reason was that make built the original GLPK libraries using gcc4.2 and specifying a 64-bit architecture , while Python's distutils module insisted on building PyGLPK's source code using gcc-4.0 with a 32-bit architecture. \nSince I couldn't figure out how to add compiler flags to distutils, I just rebuilt the GLPK libraries forcing distutils compiler flags. This was what finally worked. \nThis seems to be an issue with OS X 10.6. ./configure scripts query the system architecture, which by default, I think, is x86_64, even though Python 2.6 plays best with 32-bit binaries. \n" ]
[ 1, 1 ]
[]
[]
[ "importerror", "installation", "module", "python", "unix" ]
stackoverflow_0002728385_importerror_installation_module_python_unix.txt
Q: Outputing json with well formed accents I have an anoying problem that is giving me a hard time these days... I would like to develop a few webservices for my own usage and currently i am fighting with my damn french accents to be rendered correctly in my json outputs. Here is my scenario: I retrieve a number of lines from my database that i put in a dict. What i want to do next is pass this dict to json.dumps and output the result. The problem is: strings containing accents are rendered as utf8 so for example it gives me the following ouput \u00e9milie (it should be émilie). What is frustrating is that if i print each returned line, accents will be correctly rendered in my browser. Questions: Is it normal to give this kind of json output ? How can I 'simply' transform a dict containing accents to json ? (whis is vital for me since other websites will work with my output) Here is the test i am running. # -*- coding: utf-8 -* from json import dumps as json_dumps import json machaine = "une personne émérite" print(machaine) output = {} output[1] = machaine output[2] = machaine output[3] = machaine jsonoutput = json_dumps(output) print jsonoutput A: Just like the docs say, pass ensure_ascii=False and encode manually.
Outputing json with well formed accents
I have an anoying problem that is giving me a hard time these days... I would like to develop a few webservices for my own usage and currently i am fighting with my damn french accents to be rendered correctly in my json outputs. Here is my scenario: I retrieve a number of lines from my database that i put in a dict. What i want to do next is pass this dict to json.dumps and output the result. The problem is: strings containing accents are rendered as utf8 so for example it gives me the following ouput \u00e9milie (it should be émilie). What is frustrating is that if i print each returned line, accents will be correctly rendered in my browser. Questions: Is it normal to give this kind of json output ? How can I 'simply' transform a dict containing accents to json ? (whis is vital for me since other websites will work with my output) Here is the test i am running. # -*- coding: utf-8 -* from json import dumps as json_dumps import json machaine = "une personne émérite" print(machaine) output = {} output[1] = machaine output[2] = machaine output[3] = machaine jsonoutput = json_dumps(output) print jsonoutput
[ "Just like the docs say, pass ensure_ascii=False and encode manually.\n" ]
[ 5 ]
[]
[]
[ "diacritics", "json", "python", "utf_8" ]
stackoverflow_0002757237_diacritics_json_python_utf_8.txt
Q: Cache the result of a MySQLdb database query in memory Our application fetches the correct database server from a pool of database servers. So each query is really 2 queries, and they look like this: Fetch the correct DB server Execute the query We do this so we can take DB servers online and offline as necessary, as well as for load-balancing. But the first query seems like it could be cached to memory, so it only actually queries the database every 5 or 10 minutes or so. What's the best way to do this? Thanks. EDIT this is for a Pylons web application A: Just make a cache(python dict) which stores the first query and return it everytime, clear the cache every N mins, for this you make a decorator or cache class e.g. import time cache = {} lastTime = time.time() def timedCacheDecorator(func): def wrap(*args, **kwargs): key = str(args)+str(kwargs) # cache for 5 seconds global lastTime if key not in cache or time.time() - lastTime > 5: lastTime = time.time() cache[key] = func(*args, **kwargs) return cache[key] return wrap # lets test it @timedCacheDecorator def myquery(): return time.time() print myquery() time.sleep(1) print myquery() time.sleep(5) print myquery() time.sleep(1) print myquery() Output: 1270441034.58 1270441034.58 1270441040.58 1270441040.58 Now this decorator can be used on any function whose results are to be cached upto a time or may be upto a event, I would make this decorator a class , so that it can take how many seconds to wait before cache refresh, and also you can see how best to generate key. A: The easiest way would be to use the beaker cache, which is a library built into the pylons framework. In your model class import the beaker decorator: from pylons.decorators.cache import beaker_cache Then on your function header, where you make the database call, add the following decorator: @beaker_cache(expire = 300, type='memory') Change the expire value to the amount of seconds you want (currently set to 5 minutes).
Cache the result of a MySQLdb database query in memory
Our application fetches the correct database server from a pool of database servers. So each query is really 2 queries, and they look like this: Fetch the correct DB server Execute the query We do this so we can take DB servers online and offline as necessary, as well as for load-balancing. But the first query seems like it could be cached to memory, so it only actually queries the database every 5 or 10 minutes or so. What's the best way to do this? Thanks. EDIT this is for a Pylons web application
[ "Just make a cache(python dict) which stores the first query and return it everytime, clear the cache every N mins, for this you make a decorator or cache class e.g.\nimport time\n\ncache = {}\nlastTime = time.time()\n\ndef timedCacheDecorator(func):\n\n def wrap(*args, **kwargs):\n\n key = str(args)+str(kwargs)\n\n # cache for 5 seconds\n global lastTime\n if key not in cache or time.time() - lastTime > 5:\n lastTime = time.time()\n cache[key] = func(*args, **kwargs)\n\n return cache[key]\n\n return wrap\n\n\n# lets test it\n\n@timedCacheDecorator\ndef myquery():\n return time.time()\n\nprint myquery()\ntime.sleep(1)\nprint myquery()\ntime.sleep(5)\nprint myquery()\ntime.sleep(1)\nprint myquery()\n\nOutput:\n1270441034.58\n1270441034.58\n1270441040.58\n1270441040.58\n\nNow this decorator can be used on any function whose results are to be cached upto a time or may be upto a event, I would make this decorator a class , so that it can take how many seconds to wait before cache refresh, and also you can see how best to generate key. \n", "The easiest way would be to use the beaker cache, which is a library built into the pylons framework.\nIn your model class import the beaker decorator:\nfrom pylons.decorators.cache import beaker_cache\n\nThen on your function header, where you make the database call, add the following decorator:\n@beaker_cache(expire = 300, type='memory')\n\nChange the expire value to the amount of seconds you want (currently set to 5 minutes).\n" ]
[ 5, 1 ]
[]
[]
[ "caching", "mysql", "pylons", "python" ]
stackoverflow_0002576867_caching_mysql_pylons_python.txt
Q: Django db encoding I have a little problem with encoding. The data in db is ok, when I select the data in php its ok. Problem comes when I get the data and try to print it in the template, I get - Å port instead of Šport, etc. Everything is set to utf-8 - in settings.py, meta tags in template, db table and I even have unicode method specified for the model, but nothing seems to work. I am getting pretty hopeless here... Here is some code: class Category_info(models.Model): objtree_label_id = models.AutoField(primary_key = True) node_id = models.IntegerField(unique = True) language_id = models.IntegerField() label = models.CharField(max_length = 255) type_id = models.IntegerField() class Meta: db_table = 'objtree_labels' def __unicode__(self): return self.label I have even tried with return u"%s" % self.label. Here is the view: def categories_list(request): categories_list = Category.objects.filter(parent_id = 1, status = 1) paginator = Paginator(categories_list, 10) try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 try: categories = paginator.page(page) except (EmptyPage, InvalidPage): categories = paginator.page(paginator.num_pages) return render_to_response('categories_list.html', {'categories': categories}) Maybe I am just blind and/or stupid, but it just doesnt work. So any help is appreciated, thanks in advance. Regards A: It's definitely not Django issue. As far as I understood you try to introspect existing DB (I suppose it's MySQL because it looks like common problem after incorrect upgrade from 4.x to 5.x). You should find out necessary connect options and provide them via DATABASE_OPTIONS setting. Try something like this: DATABASE_OPTIONS = { 'use_unicode': True, 'charset': 'utf8' }
Django db encoding
I have a little problem with encoding. The data in db is ok, when I select the data in php its ok. Problem comes when I get the data and try to print it in the template, I get - Å port instead of Šport, etc. Everything is set to utf-8 - in settings.py, meta tags in template, db table and I even have unicode method specified for the model, but nothing seems to work. I am getting pretty hopeless here... Here is some code: class Category_info(models.Model): objtree_label_id = models.AutoField(primary_key = True) node_id = models.IntegerField(unique = True) language_id = models.IntegerField() label = models.CharField(max_length = 255) type_id = models.IntegerField() class Meta: db_table = 'objtree_labels' def __unicode__(self): return self.label I have even tried with return u"%s" % self.label. Here is the view: def categories_list(request): categories_list = Category.objects.filter(parent_id = 1, status = 1) paginator = Paginator(categories_list, 10) try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 try: categories = paginator.page(page) except (EmptyPage, InvalidPage): categories = paginator.page(paginator.num_pages) return render_to_response('categories_list.html', {'categories': categories}) Maybe I am just blind and/or stupid, but it just doesnt work. So any help is appreciated, thanks in advance. Regards
[ "It's definitely not Django issue. As far as I understood you try to introspect existing DB (I suppose it's MySQL because it looks like common problem after incorrect upgrade from 4.x to 5.x). You should find out necessary connect options and provide them via DATABASE_OPTIONS setting. Try something like this:\nDATABASE_OPTIONS = {\n 'use_unicode': True,\n 'charset': 'utf8'\n}\n\n" ]
[ 0 ]
[]
[]
[ "django", "encoding", "python" ]
stackoverflow_0002757118_django_encoding_python.txt
Q: Load JSON in Python as header character set I've always found character sets and encodings complicated to understand and here I'm faced with another problem. My apologies for any inaccuracies. I'll do my best. I'm requesting data from a server which returns JSON. In the HTTP headers it also returns the character set like so: Content-Type: text/html; charset=UTF-8 I'm using the JSON library in Python to load the JSON using the json.loads method. When I pass it the returned JSON, it gives me a dictionary in Unicode. I've Googled around and I know that JSON should return Unicode as JavaScript strings are Unicode objects. How can I load the JSON as UTF-8? I would like to use the same encoding as specified in the response header. I've read this post but it didn't help. Thank you. A: json.loads automatically handles strs that are passed to it in UTF-8, so, in this specific case, you shouldn't have to worry about charsets yourself. loads is already converting from UTF-8 to Python's UCS-2 Unicode representation for you. Unless you have some other reason why you really need to operate on the original UTF-8, you should feel fine, even though you're passing in a str and getting back unicodes. You can also specify the input encoding as the second parameter to loads if you want to be sure or if you're dealing with varying charsets. A: From application/json rfc: JSON text SHALL be encoded in Unicode. The default encoding is UTF-8. Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets. 00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8 So given json text as a bytestring it is always possible to convert it to unicode string. Given unicode string you can convert it if desired to another bytestring using any encoding you like. json.loads() uses specified encoding (default is 'utf-8'). if input encoding is not ASCII-based then the text should be manually converted to unicode before passing it to json.loads().
Load JSON in Python as header character set
I've always found character sets and encodings complicated to understand and here I'm faced with another problem. My apologies for any inaccuracies. I'll do my best. I'm requesting data from a server which returns JSON. In the HTTP headers it also returns the character set like so: Content-Type: text/html; charset=UTF-8 I'm using the JSON library in Python to load the JSON using the json.loads method. When I pass it the returned JSON, it gives me a dictionary in Unicode. I've Googled around and I know that JSON should return Unicode as JavaScript strings are Unicode objects. How can I load the JSON as UTF-8? I would like to use the same encoding as specified in the response header. I've read this post but it didn't help. Thank you.
[ "json.loads automatically handles strs that are passed to it in UTF-8, so, in this specific case, you shouldn't have to worry about charsets yourself. loads is already converting from UTF-8 to Python's UCS-2 Unicode representation for you.\nUnless you have some other reason why you really need to operate on the original UTF-8, you should feel fine, even though you're passing in a str and getting back unicodes. You can also specify the input encoding as the second parameter to loads if you want to be sure or if you're dealing with varying charsets.\n", "From application/json rfc:\n\nJSON text SHALL be encoded in Unicode. The default encoding is UTF-8.\nSince the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.\n 00 00 00 xx UTF-32BE\n 00 xx 00 xx UTF-16BE\n xx 00 00 00 UTF-32LE\n xx 00 xx 00 UTF-16LE\n xx xx xx xx UTF-8\n\n\nSo given json text as a bytestring it is always possible to convert it to unicode string. Given unicode string you can convert it if desired to another bytestring using any encoding you like.\njson.loads() uses specified encoding (default is 'utf-8'). if input encoding is not ASCII-based then the text should be manually converted to unicode before passing it to json.loads().\n" ]
[ 2, 2 ]
[]
[]
[ "character_encoding", "json", "python", "unicode", "utf_8" ]
stackoverflow_0002756847_character_encoding_json_python_unicode_utf_8.txt
Q: Renaming TurboGears 2's Repoze Fields with TGAdmin I've been working on renaming TurboGears 2's Repoze 'groups' field to 'roles' to free the namespace and db tables for other purposes. Also roles makes much more sense to me then groups because I have a strong Drupal background. Now I have found some of the docs to do this such as these: http://www.turbogears.org/2.1/docs/main/Auth/Customization.html#customizing-the-model-structure-assumed-by-the-quickstart http://code.gustavonarea.net/repoze.what-quickstart/#customizing-the-model-definition However these only go part of the way. I have made (I'm pretty sure at least, I've double checked a few times.) all the changes required as you can see in this diff. This seems to work fine however I've ran into a rather major issue with the TurboGears Admin system. I've tried http://turbogears.org/2.0/docs/main/Extensions/Admin/index.html and it didn't seem to make any difference, however I'm not 100% sure I did it correctly. The problem occurs when I attempt to go to localhost/admin/permissions/. It causes a Internal Server Error and outputs the following error. http://pastebin.com/YWMH3SiU This error does not happen on the Roles/Users pages and the permissions /edit/1 also works. I'm running kubuntu 10.04 with TG 2.1b2. (I'm running the beta mostly for easier mako support which is really important.) Any help would be very appreciated. A: Why cross post with the TurboGears mailing list? http://groups.google.com/group/turbogears/browse_thread/thread/e6040eb194880fc6/ This just duplicates efforts for people trying to help you and is annoying for those who follow both the mailing list and Python related questions on StackOverflow.
Renaming TurboGears 2's Repoze Fields with TGAdmin
I've been working on renaming TurboGears 2's Repoze 'groups' field to 'roles' to free the namespace and db tables for other purposes. Also roles makes much more sense to me then groups because I have a strong Drupal background. Now I have found some of the docs to do this such as these: http://www.turbogears.org/2.1/docs/main/Auth/Customization.html#customizing-the-model-structure-assumed-by-the-quickstart http://code.gustavonarea.net/repoze.what-quickstart/#customizing-the-model-definition However these only go part of the way. I have made (I'm pretty sure at least, I've double checked a few times.) all the changes required as you can see in this diff. This seems to work fine however I've ran into a rather major issue with the TurboGears Admin system. I've tried http://turbogears.org/2.0/docs/main/Extensions/Admin/index.html and it didn't seem to make any difference, however I'm not 100% sure I did it correctly. The problem occurs when I attempt to go to localhost/admin/permissions/. It causes a Internal Server Error and outputs the following error. http://pastebin.com/YWMH3SiU This error does not happen on the Roles/Users pages and the permissions /edit/1 also works. I'm running kubuntu 10.04 with TG 2.1b2. (I'm running the beta mostly for easier mako support which is really important.) Any help would be very appreciated.
[ "Why cross post with the TurboGears mailing list?\nhttp://groups.google.com/group/turbogears/browse_thread/thread/e6040eb194880fc6/\nThis just duplicates efforts for people trying to help you and is annoying for those who follow both the mailing list and Python related questions on StackOverflow.\n" ]
[ 0 ]
[]
[]
[ "pylons", "python", "repoze.who", "turbogears2" ]
stackoverflow_0002755833_pylons_python_repoze.who_turbogears2.txt
Q: File mode for creating+reading+appending+binary I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this? I tried 'r+ab' but that doesn't create the files if they are not found. Thanks A: The mode is ab+ the r is implied and 'a'ppend and ('w'rite '+' 'r'ead) are redundant. Since the CPython (i.e. regular python) file is based on the C stdio FILE type, here are the relevant lines from the fopen(3) man page: w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file. With the "b" tacked on to make DOS happy. Presumably you want to do something like this: >>> f = open('junk', 'ab+') >>> f <open file 'junk', mode 'ab+' at 0xb77e6288> >>> f.write('hello\n') >>> f.seek(0, os.SEEK_SET) >>> f.readline() 'hello\n' >>> f.write('there\n') >>> f.seek(0, os.SEEK_SET) >>> f.readline() 'hello\n' >>> f.readline() 'there\n' A: open("filename", "a+b") should work. It opens a binary file in append/update mode.
File mode for creating+reading+appending+binary
I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this? I tried 'r+ab' but that doesn't create the files if they are not found. Thanks
[ "The mode is ab+ the r is implied and 'a'ppend and ('w'rite '+' 'r'ead) are redundant. Since the CPython (i.e. regular python) file is based on the C stdio FILE type, here are the relevant lines from the fopen(3) man page:\n\nw+ Open for reading and writing. \nThe file is created if it does not\nexist, otherwise it is truncated. \nThe stream is positioned at the\nbeginning of the file.\na+ Open for reading and appending (writing at end of file). \nThe file is created if it does not \nexist. The initial file position\nfor reading is at the beginning of\nthe file, but output is always\nappended to the end of the file.\n\nWith the \"b\" tacked on to make DOS happy. Presumably you want to do something like this:\n>>> f = open('junk', 'ab+')\n>>> f\n<open file 'junk', mode 'ab+' at 0xb77e6288>\n>>> f.write('hello\\n')\n>>> f.seek(0, os.SEEK_SET)\n>>> f.readline()\n'hello\\n'\n>>> f.write('there\\n')\n>>> f.seek(0, os.SEEK_SET)\n>>> f.readline()\n'hello\\n'\n>>> f.readline()\n'there\\n'\n\n", "open(\"filename\", \"a+b\")\n\nshould work. It opens a binary file in append/update mode.\n" ]
[ 64, 8 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002757887_file_io_python.txt
Q: setfsuid() and python 2.5.4 I'm trying to use setfsuid() with python 2.5.4 and RHEL 5.4. Since it's not included in the os module, I wrapped it in a C module of my own and installed it as a python extension module using distutils. However when I try to use it I don't get the expected result. setfsuid() returns value indicating success (changing from a superuser), but I can't access files to which only the newly set user should have user access (using open()), indicating that fsuid was not truely changed. I tried to verify setfsuid() worked, by running it consecutively twice with the same user input The result was as if nothing had changed, and on every call the returned value was of old user id different from the new one. I also called getpid() from the module, and from the python script, both returned the same id. so this is not the problem. Just in case it's significant, I should note that I'm doing all of this from within an Apache daemon process (WSGI). Anyone can provide an explanation to that? Thank you A: The ability to change the FSUID is limited to either root or non-root processes with the CAP_SETFCAP capability. These days it's usually considered bad practice to run a webserver with root permissions so, most likely, you'll need to set the capability on the file server (see man capabilities for details). Please note that doing this could severly affect your overall system's security. I'd recommend considering spawning a small backend process that runs as root and converses with your WSGI app via a local UNIX socket prior to mucking with the security of a high-profile target like Apache.
setfsuid() and python 2.5.4
I'm trying to use setfsuid() with python 2.5.4 and RHEL 5.4. Since it's not included in the os module, I wrapped it in a C module of my own and installed it as a python extension module using distutils. However when I try to use it I don't get the expected result. setfsuid() returns value indicating success (changing from a superuser), but I can't access files to which only the newly set user should have user access (using open()), indicating that fsuid was not truely changed. I tried to verify setfsuid() worked, by running it consecutively twice with the same user input The result was as if nothing had changed, and on every call the returned value was of old user id different from the new one. I also called getpid() from the module, and from the python script, both returned the same id. so this is not the problem. Just in case it's significant, I should note that I'm doing all of this from within an Apache daemon process (WSGI). Anyone can provide an explanation to that? Thank you
[ "The ability to change the FSUID is limited to either root or non-root processes with the CAP_SETFCAP capability. These days it's usually considered bad practice to run a webserver with root permissions so, most likely, you'll need to set the capability on the file server (see man capabilities for details). Please note that doing this could severly affect your overall system's security. I'd recommend considering spawning a small backend process that runs as root and converses with your WSGI app via a local UNIX socket prior to mucking with the security of a high-profile target like Apache.\n" ]
[ 2 ]
[]
[]
[ "operating_system", "python" ]
stackoverflow_0002757991_operating_system_python.txt
Q: Not able to access parts of imported .PY in a .PSP I'm trying to load a weather plugin for a website I'm working on. The weather plugin is a separate weather.py file located at /var/www/piss/plugins/base/weather.py. In the PSP it seems to import correctly, but I am unable to access any variables or objects from the weather.py plugin in the PSP. Here's the code I have: ...HTML and CSS stuff... <% sys.path.append('/var/www/piss/plugins/base/') pwd = os.getcwd() import sys, os import string from weather import weather %> <%= pwd %> <%= html1 %> <%= currentWeather %> </div> </div> <div id="footer">Piss + INK Version 0.00001</div> <div id="bottom"></div> </div> </body> </html> Here's the weather.py code: from basePlugin import plugin import MySQLdb import pywapi class weather(plugin): """ weather.py Built-in weather plugin. """ def __init__(self,zipcode): self.zipcode = zipcode #Tested without DB access #db=_mysql.connect(host="localhost",user="things",passwd="things",db="things") #zip="SELECT zipcode FROM "+currentUser+"\;" #c = db.cursor() #dbResult = c.execute (zip) wResult=pywapi.get_weather_from_google('05401') html1=""" <div class="weather"> Weather:<br /> """ print html1 currently = wResult['current_conditions'] currentWeather = currently['condition'] print currentWeather print "<br />" if currentWeather == "Mostly Cloudy": print '<img src="themes/default/images/weather/cloudy.png" alt="cloudy">' if currentWeather == "Cloudy": print '<img src="themes/default/images/weather/cloudy.png" alt="cloudy">' if currentWeather == "Sunny": print '<img src="themes/default/images/weather/sunny.png" alt="sunny">' if currentWeather == "Showers": print '<img src="themes/default/images/weather/rain.png" alt="rain">' #More conditions will be added in actual plugin. print "</div>" A: PSP isn't particularly popular in the Python world, and for good reason. Pretty much any other templating system is a better choice. It's been a very long time since I looked at PSP, and I may be misremembering how it works, but I'm not sure you expect PSP to know that pwd, html1 and currentWeather come from the weather class you imported from the weather module. I'm also not sure the print statements in the class are doing what you think they're doing, considering they're in the class body, not a method. All in all I would suggest you pick a saner templating system. Django's templates, Mako, Jinja, anything but PSP.
Not able to access parts of imported .PY in a .PSP
I'm trying to load a weather plugin for a website I'm working on. The weather plugin is a separate weather.py file located at /var/www/piss/plugins/base/weather.py. In the PSP it seems to import correctly, but I am unable to access any variables or objects from the weather.py plugin in the PSP. Here's the code I have: ...HTML and CSS stuff... <% sys.path.append('/var/www/piss/plugins/base/') pwd = os.getcwd() import sys, os import string from weather import weather %> <%= pwd %> <%= html1 %> <%= currentWeather %> </div> </div> <div id="footer">Piss + INK Version 0.00001</div> <div id="bottom"></div> </div> </body> </html> Here's the weather.py code: from basePlugin import plugin import MySQLdb import pywapi class weather(plugin): """ weather.py Built-in weather plugin. """ def __init__(self,zipcode): self.zipcode = zipcode #Tested without DB access #db=_mysql.connect(host="localhost",user="things",passwd="things",db="things") #zip="SELECT zipcode FROM "+currentUser+"\;" #c = db.cursor() #dbResult = c.execute (zip) wResult=pywapi.get_weather_from_google('05401') html1=""" <div class="weather"> Weather:<br /> """ print html1 currently = wResult['current_conditions'] currentWeather = currently['condition'] print currentWeather print "<br />" if currentWeather == "Mostly Cloudy": print '<img src="themes/default/images/weather/cloudy.png" alt="cloudy">' if currentWeather == "Cloudy": print '<img src="themes/default/images/weather/cloudy.png" alt="cloudy">' if currentWeather == "Sunny": print '<img src="themes/default/images/weather/sunny.png" alt="sunny">' if currentWeather == "Showers": print '<img src="themes/default/images/weather/rain.png" alt="rain">' #More conditions will be added in actual plugin. print "</div>"
[ "PSP isn't particularly popular in the Python world, and for good reason. Pretty much any other templating system is a better choice. It's been a very long time since I looked at PSP, and I may be misremembering how it works, but I'm not sure you expect PSP to know that pwd, html1 and currentWeather come from the weather class you imported from the weather module. I'm also not sure the print statements in the class are doing what you think they're doing, considering they're in the class body, not a method.\nAll in all I would suggest you pick a saner templating system. Django's templates, Mako, Jinja, anything but PSP.\n" ]
[ 0 ]
[]
[]
[ "mod_python", "python", "python_server_pages" ]
stackoverflow_0002757673_mod_python_python_python_server_pages.txt
Q: Declaring models elsewhere than in "models.py" AND dynamically I have an application that splits models into different files. Actually the folder looks like : >myapp __init__.py models.py >hooks ... ... myapp don't care about what's in the hooks, folder, except that there are models, and that they have to be imported somehow, and installed by syncdb. So, I put this in myapp.__init__.py : from django.conf import settings for hook in settings.HOOKS : try : __import__(hook) except ImportError as e : print "Got import err !", e #where settings.HOOKS = ("myapp.hooks.a_super_hook1", ...) In order for this code to work, the models in hooks have class Meta: app_label="my_app" The problem is that it doesn't work when I run syncdb. So I tried successively : 1) for hook in settings.HOOKS : try : exec ("from %s import *" % hook) -> doesn't work either : syncdb doesn't install the models in hooks 2) from myapp.hooks.a_super_hook1 import * -> This works 3) exec("from myapp.hooks.a_super_hook1 import *") -> This works to So I checked that in the test 1), the statement executed is the same than in tests 2) and 3), and it is exactly the same ... Any idea ??? EDIT : The question could be summarized to : I declared models outside of "models.py", where to put MY import code, so that syncdb finds the models ? A: Django know of all models that are defined anywhere in your project, so you only need to make sure that the code where they are defined gets executed. This usually happens when you import the module in which the models are defined. The other thing which is important to know is that the app_label attribute of the Meta class inside your models needs to be set to the package name of your app (myapp in your example). This is necessary, because syncdb will only install models in the database from apps that are listed in your INSTALLED_APPS setting. Regarding to your setup described in your question, you need to: make sure that the module where the model is defined gets imported set the app_label attribute in the model's Meta class to myapp put myapp into your INSTALLED_APPS setting Additional information: Another requirement in django for making the syncdb work on your models is, that the app in which the models are defined (to which app_label is set to) needs a models.py file even if its empty. But as described in your question you already have this file. A: Ok ... I've got the damn thing. When importing models, syncdb tries to import what it finds. If the import fails, then it is post-poned to be tried later ! That's why : for hook in settings.HOOKS : try : __import__(hook) except ImportError as e : print "Got import err !", e doesn't work with syncdb : because the import error is caught, and not transmitted, then the models import will never be post-poned. So right code to do this is simply : for log_hook in settings.LOG_HOOKS : try : __import__(log_hook) except ImportError as e : raise e The try... except is probably useless in this case.
Declaring models elsewhere than in "models.py" AND dynamically
I have an application that splits models into different files. Actually the folder looks like : >myapp __init__.py models.py >hooks ... ... myapp don't care about what's in the hooks, folder, except that there are models, and that they have to be imported somehow, and installed by syncdb. So, I put this in myapp.__init__.py : from django.conf import settings for hook in settings.HOOKS : try : __import__(hook) except ImportError as e : print "Got import err !", e #where settings.HOOKS = ("myapp.hooks.a_super_hook1", ...) In order for this code to work, the models in hooks have class Meta: app_label="my_app" The problem is that it doesn't work when I run syncdb. So I tried successively : 1) for hook in settings.HOOKS : try : exec ("from %s import *" % hook) -> doesn't work either : syncdb doesn't install the models in hooks 2) from myapp.hooks.a_super_hook1 import * -> This works 3) exec("from myapp.hooks.a_super_hook1 import *") -> This works to So I checked that in the test 1), the statement executed is the same than in tests 2) and 3), and it is exactly the same ... Any idea ??? EDIT : The question could be summarized to : I declared models outside of "models.py", where to put MY import code, so that syncdb finds the models ?
[ "Django know of all models that are defined anywhere in your project, so you only need to make sure that the code where they are defined gets executed. This usually happens when you import the module in which the models are defined.\nThe other thing which is important to know is that the app_label attribute of the Meta class inside your models needs to be set to the package name of your app (myapp in your example). This is necessary, because syncdb will only install models in the database from apps that are listed in your INSTALLED_APPS setting.\nRegarding to your setup described in your question, you need to:\n\nmake sure that the module where the model is defined gets imported\nset the app_label attribute in the model's Meta class to myapp\nput myapp into your INSTALLED_APPS setting\n\nAdditional information:\nAnother requirement in django for making the syncdb work on your models is, that the app in which the models are defined (to which app_label is set to) needs a models.py file even if its empty. But as described in your question you already have this file.\n", "Ok ... I've got the damn thing.\nWhen importing models, syncdb tries to import what it finds. If the import fails, then it is post-poned to be tried later ! That's why :\nfor hook in settings.HOOKS :\n try :\n __import__(hook)\n except ImportError as e :\n print \"Got import err !\", e\n\ndoesn't work with syncdb : because the import error is caught, and not transmitted, then the models import will never be post-poned. So right code to do this is simply :\nfor log_hook in settings.LOG_HOOKS :\n try :\n __import__(log_hook)\n except ImportError as e :\n raise e\n\nThe try... except is probably useless in this case.\n" ]
[ 1, 0 ]
[ "Assuming you have a file called users_models.py in hooks folder:\nYou could say from hooks.users_models import * in myapp.__init__.py right ? That will be picked up by syncdb for sure.\n" ]
[ -1 ]
[ "django", "python" ]
stackoverflow_0002737275_django_python.txt
Q: What are the elegant ways to do MixIns in Python? I need to find an elegant way to do 2 kinds of MixIns. First: class A(object): def method1(self): do_something() Now, a MixInClass should make method1 do this: do_other() -> A.method1() -> do_smth_else() - i.e. basically "wrap" the older function. I'm pretty sure there must exist a good solution to this. Second: class B(object): def method1(self): do_something() do_more() In this case, I want MixInClass2 to be able to inject itself between do_something() and do_more(), i.e.: do_something() -> MixIn.method1 -> do_more(). I understand that probably this would require modifying class B - that's ok, just looking for simplest ways to achieve this. These are pretty trivial problems and I actually solved them, but my solution is tainted. Fisrt one by using self._old_method1 = self.method1(); self.method1() = self._new_method1(); and writing _new_method1() that calls to _old_method1(). Problem: multiple MixIns will all rename to _old_method1 and it is inelegant. Second MixIn one was solved by creating a dummy method call_mixin(self): pass and injecting it between calls and defining self.call_mixin(). Again inelegant and will break on multiple MixIns.. Any ideas? Thanks to Boldewyn, I've found elegant solution to first one (I've forgot you can create decorators on-the-fly, without modifying original code): class MixIn_for_1(object): def __init__(self): self.method1 = self.wrap1(self.method1) super(MixIn_for_1, self).__init__() def wrap1(self, old): def method1(): print "do_other()" old() print "do_smth_else()" return method1 Still searching for ideas for second one (this idea won't fit, since I need to inject inside of old method, not outside, like in this case). Solution for second is below, replacing "pass_func" with lambda:0. A: I think, that can be handled in quite a Pythonic way using decorators. (PEP 318, too) A: Here is another way to implement MixInClass1, MixinClass2: Decorators are useful when you need to wrap many functions. Since MixinClass1 needs to wrap only one function, I think it is clearer to monkey-patch: Using double underscores for __old_method1 and __method1 plays a useful role in MixInClass1. Because of Python's name-mangling convention, using the double underscores localizes these attributes to MixinClass1 and allows you to use the very same attribute names for other mix-in classes without causing unwanted name-collisions. class MixInClass1(object): def __init__(self): self.__old_method1,self.method1=self.method1,self.__method1 super(MixInClass1, self).__init__() def __method1(self): print "pre1()" self.__old_method1() print "post1()" class MixInClass2(object): def __init__(self): super(MixInClass2, self).__init__() def method1_hook(self): print('MixIn method1') class Foo(MixInClass2,MixInClass1): def method1(self): print "do_something()" getattr(self,'method1_hook',lambda *args,**kw: None)() print "do_more()" foo=Foo() foo.method1()
What are the elegant ways to do MixIns in Python?
I need to find an elegant way to do 2 kinds of MixIns. First: class A(object): def method1(self): do_something() Now, a MixInClass should make method1 do this: do_other() -> A.method1() -> do_smth_else() - i.e. basically "wrap" the older function. I'm pretty sure there must exist a good solution to this. Second: class B(object): def method1(self): do_something() do_more() In this case, I want MixInClass2 to be able to inject itself between do_something() and do_more(), i.e.: do_something() -> MixIn.method1 -> do_more(). I understand that probably this would require modifying class B - that's ok, just looking for simplest ways to achieve this. These are pretty trivial problems and I actually solved them, but my solution is tainted. Fisrt one by using self._old_method1 = self.method1(); self.method1() = self._new_method1(); and writing _new_method1() that calls to _old_method1(). Problem: multiple MixIns will all rename to _old_method1 and it is inelegant. Second MixIn one was solved by creating a dummy method call_mixin(self): pass and injecting it between calls and defining self.call_mixin(). Again inelegant and will break on multiple MixIns.. Any ideas? Thanks to Boldewyn, I've found elegant solution to first one (I've forgot you can create decorators on-the-fly, without modifying original code): class MixIn_for_1(object): def __init__(self): self.method1 = self.wrap1(self.method1) super(MixIn_for_1, self).__init__() def wrap1(self, old): def method1(): print "do_other()" old() print "do_smth_else()" return method1 Still searching for ideas for second one (this idea won't fit, since I need to inject inside of old method, not outside, like in this case). Solution for second is below, replacing "pass_func" with lambda:0.
[ "I think, that can be handled in quite a Pythonic way using decorators. (PEP 318, too)\n", "Here is another way to implement MixInClass1, MixinClass2:\nDecorators are useful when you need to wrap many functions. Since MixinClass1 needs to wrap only one function, I think it is clearer to monkey-patch:\nUsing double underscores for __old_method1 and __method1 plays a useful role in MixInClass1. Because of Python's name-mangling convention, using the double underscores localizes these attributes to MixinClass1 and allows you to use the very same attribute names for other mix-in classes without causing unwanted name-collisions.\nclass MixInClass1(object):\n def __init__(self):\n self.__old_method1,self.method1=self.method1,self.__method1\n super(MixInClass1, self).__init__() \n def __method1(self):\n print \"pre1()\"\n self.__old_method1()\n print \"post1()\"\n\nclass MixInClass2(object):\n def __init__(self):\n super(MixInClass2, self).__init__() \n def method1_hook(self):\n print('MixIn method1')\n\nclass Foo(MixInClass2,MixInClass1):\n def method1(self):\n print \"do_something()\"\n getattr(self,'method1_hook',lambda *args,**kw: None)()\n print \"do_more()\"\n\nfoo=Foo()\nfoo.method1()\n\n" ]
[ 5, 3 ]
[]
[]
[ "mixins", "python" ]
stackoverflow_0002757358_mixins_python.txt
Q: Linux distro name parsing I chose this way to get linux distro name: ls /etc/*release And now I have to parse it for name: /etc/<name>-release def checkDistro(): p = Popen('ls /etc/*release' , shell = True, stdout = PIPE) distroRelease = p.stdout.read() distroName = re.search( ur"\/etc\/(.*)\-release", distroRelease).group() print distroName But this prints the same string that is in distroRelease. A: An alternative is to use the builtin method platform.linux_distribution() (available in Python 2.6+): >>> import platform >>> platform.linux_distribution() ('Red Hat Enterprise Linux Server', '5.1', 'Tikanga') In older versions of Python, platform.dist() can be used: >>> import platform >>> platform.dist() ('redhat', '5.1', 'Tikanga') A: You need .group(1), because you want the first capture group - without arguments, it defaults to .group(0) which is the entire matched text. A: Parsing ls output is discouraged. Consider using a glob(): #!/usr/bin/env python import os import glob def check_distro(): print os.path.basename(glob.glob('/etc/*-release')[0]).replace('-release', '') if __name__ == '__main__': check_distro() A: Use .group(1). A: What's the point? /etc/*release is not a standard, it will only work on some distros.
Linux distro name parsing
I chose this way to get linux distro name: ls /etc/*release And now I have to parse it for name: /etc/<name>-release def checkDistro(): p = Popen('ls /etc/*release' , shell = True, stdout = PIPE) distroRelease = p.stdout.read() distroName = re.search( ur"\/etc\/(.*)\-release", distroRelease).group() print distroName But this prints the same string that is in distroRelease.
[ "An alternative is to use the builtin method platform.linux_distribution() (available in Python 2.6+):\n>>> import platform\n>>> platform.linux_distribution()\n('Red Hat Enterprise Linux Server', '5.1', 'Tikanga')\n\nIn older versions of Python, platform.dist() can be used:\n>>> import platform\n>>> platform.dist()\n('redhat', '5.1', 'Tikanga')\n\n", "You need .group(1), because you want the first capture group - without arguments, it defaults to .group(0) which is the entire matched text.\n", "Parsing ls output is discouraged. Consider using a glob():\n#!/usr/bin/env python\n\nimport os\nimport glob\n\ndef check_distro():\n print os.path.basename(glob.glob('/etc/*-release')[0]).replace('-release', '')\n\nif __name__ == '__main__':\n check_distro()\n\n", "Use .group(1).\n", "What's the point? /etc/*release is not a standard, it will only work on some distros.\n" ]
[ 7, 5, 3, 2, 1 ]
[]
[]
[ "linux", "python", "regex" ]
stackoverflow_0002756873_linux_python_regex.txt
Q: How do I read user input in python thread? I'm trying to read from a thread in python as follows import threading, time, random var = True class MyThread(threading.Thread): def set_name(self, name): self.name = name def run(self): global var while var == True: print "In mythread " + self.name time.sleep(random.randint(2,5)) class MyReader(threading.Thread): def run(self): global var while var == True: input = raw_input("Quit?") if input == "q": var = False t1 = MyThread() t1.set_name("One") t2 = MyReader() t1.start() t2.start() However, if I enter 'q', I see the following error. In mythread One Quit?q Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() File "test.py", line 20, in run input = raw_input("Quit?") EOFError In mythread One In mythread One How does on get user input from a thread? A: Your code is a bit strange. If you are using the reader strictly to quit the program, why not have it outside the threading code entirely? It doesn't need to be in the thread, for your purposes, and won't work in the thread. Regardless, I don't think you want to take this road. Consider this problem: multiple threads stop to ask for input simultaneously, and the user types input. To which thread should it go? I would advise restructuring the code to avoid this need. A: Also all read /writes to var should locked
How do I read user input in python thread?
I'm trying to read from a thread in python as follows import threading, time, random var = True class MyThread(threading.Thread): def set_name(self, name): self.name = name def run(self): global var while var == True: print "In mythread " + self.name time.sleep(random.randint(2,5)) class MyReader(threading.Thread): def run(self): global var while var == True: input = raw_input("Quit?") if input == "q": var = False t1 = MyThread() t1.set_name("One") t2 = MyReader() t1.start() t2.start() However, if I enter 'q', I see the following error. In mythread One Quit?q Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() File "test.py", line 20, in run input = raw_input("Quit?") EOFError In mythread One In mythread One How does on get user input from a thread?
[ "Your code is a bit strange. If you are using the reader strictly to quit the program, why not have it outside the threading code entirely? It doesn't need to be in the thread, for your purposes, and won't work in the thread.\nRegardless, I don't think you want to take this road. Consider this problem: multiple threads stop to ask for input simultaneously, and the user types input. To which thread should it go? I would advise restructuring the code to avoid this need.\n", "Also all read /writes to var should locked\n" ]
[ 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002757318_multithreading_python.txt
Q: Google App Engine - Document Editor Creation/Tap Into Google Docs? What is the best way to create a custom document editor in GAE? I'm making a website meant for a School Robotics Club (With support for any other organization - DRY). We currently use Google services for online collaboration, I'm wondering if there is a way to tap into Google Docs and allow users to edit a Google Document without using Google Accounts or the Google Docs [EDIT]interface website[/EDIT]. If that is not possible (I've researched and I don't think it is), what is the best way to make a document editor? I want it completely on the website I'm creating, so I'm assuming just some javascript editor like TinyMCE + Ajax + Datastore. Is their anything that replicates Google Doc's/Microsoft Offices's/OpenOffice.org's feature set as far as fonts, spacing, alignment, justification, etc.? A: That depends on what you mean by 'use' - if you don't want Google Accounts, or the editor, it's hard to see what's left. You can use the document list data API to upload, download, and convert docs. A: It sounds to me like you want to use the Google Docs editor like a widget within your application. To the best of my knowledge you can't do this.
Google App Engine - Document Editor Creation/Tap Into Google Docs?
What is the best way to create a custom document editor in GAE? I'm making a website meant for a School Robotics Club (With support for any other organization - DRY). We currently use Google services for online collaboration, I'm wondering if there is a way to tap into Google Docs and allow users to edit a Google Document without using Google Accounts or the Google Docs [EDIT]interface website[/EDIT]. If that is not possible (I've researched and I don't think it is), what is the best way to make a document editor? I want it completely on the website I'm creating, so I'm assuming just some javascript editor like TinyMCE + Ajax + Datastore. Is their anything that replicates Google Doc's/Microsoft Offices's/OpenOffice.org's feature set as far as fonts, spacing, alignment, justification, etc.?
[ "That depends on what you mean by 'use' - if you don't want Google Accounts, or the editor, it's hard to see what's left. You can use the document list data API to upload, download, and convert docs.\n", "It sounds to me like you want to use the Google Docs editor like a widget within your application. To the best of my knowledge you can't do this.\n" ]
[ 3, 2 ]
[]
[]
[ "ajax", "google_app_engine", "python", "text_editor", "tinymce" ]
stackoverflow_0002755069_ajax_google_app_engine_python_text_editor_tinymce.txt
Q: Calling methods in super class constructor or subclass constructor? 1. Passing configuration to the __init__ method which calls register implicitely: class Base: def __init__(self, *verbs): if not verbs: verbs = "get", "post" self._register(verbs) def _register(self, *verbs): pass class Sub(Base): def __init__(self): super().__init__("get", "post", "put") 2. Calling register explicitely in the subclass' __init__ method: class Base: def __init__(self): self._register("get", "post") def _register(self, *verbs): pass class Sub(Base): def __init__(self): self._register("get", "post", "put") I use Python 3. What is better or more pythonic? Or is it only a matter of taste? A: I think none of these options is good. The closest solution would probably be: class Base(object): def __init__(self): self._register("get", "post") class Sub(Base): def __init__(self): super(Sub, self).__init__() self._register("put") I'm also wondering if it wouldn't be better to register the verbs at the class level. They are probably identical for all instances, so why are they registered for each instance individually? A: If everything extending the base class will behave like this, I would personally call from the base class's constructor. If not, and the behaviour varies, I would call from the sub class... As for what is more Pythonic - don't subscribe to a cult - write code that works... Martin A: IMHO, the second way is better. The 'more pythonic' way is to make things as explicit as practical. You won't have to go track down the parent class constructor to see what it's doing with those arguments... A: I would definitely use the first form. The question I would ask myself is: "What if the initialization for the base class is modified, one day? do I want subclasses to benefit from the update or not?". In almost all of my code, the answer is a resounding yes… :)
Calling methods in super class constructor or subclass constructor?
1. Passing configuration to the __init__ method which calls register implicitely: class Base: def __init__(self, *verbs): if not verbs: verbs = "get", "post" self._register(verbs) def _register(self, *verbs): pass class Sub(Base): def __init__(self): super().__init__("get", "post", "put") 2. Calling register explicitely in the subclass' __init__ method: class Base: def __init__(self): self._register("get", "post") def _register(self, *verbs): pass class Sub(Base): def __init__(self): self._register("get", "post", "put") I use Python 3. What is better or more pythonic? Or is it only a matter of taste?
[ "I think none of these options is good. The closest solution would probably be:\nclass Base(object):\n\n def __init__(self):\n self._register(\"get\", \"post\")\n\n\nclass Sub(Base):\n\n def __init__(self):\n super(Sub, self).__init__()\n self._register(\"put\")\n\nI'm also wondering if it wouldn't be better to register the verbs at the class level. They are probably identical for all instances, so why are they registered for each instance individually?\n", "If everything extending the base class will behave like this, I would personally call from the base class's constructor. If not, and the behaviour varies, I would call from the sub class...\nAs for what is more Pythonic - don't subscribe to a cult - write code that works...\nMartin\n", "IMHO, the second way is better. The 'more pythonic' way is to make things as explicit as practical. You won't have to go track down the parent class constructor to see what it's doing with those arguments...\n", "I would definitely use the first form. The question I would ask myself is: \"What if the initialization for the base class is modified, one day? do I want subclasses to benefit from the update or not?\". In almost all of my code, the answer is a resounding yes… :)\n" ]
[ 3, 0, 0, 0 ]
[]
[]
[ "constructor", "oop", "python" ]
stackoverflow_0002749327_constructor_oop_python.txt
Q: Exit Tks mainloop in Python? I'm writing a slideshow program with Tkinter, but I don't know how to go to the next image without binding a key. import os, sys import Tkinter import Image, ImageTk import time root = Tkinter.Tk() w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.overrideredirect(1) root.geometry("%dx%d+0+0" % (w, h)) root.focus_set() root.bind("<Escape>", lambda e: e.widget.quit()) image_path = os.path.join(os.getcwd(), 'images/') dirlist = os.listdir(image_path) for f in dirlist: try: image = Image.open(image_path+f) tkpi = ImageTk.PhotoImage(image) label_image = Tkinter.Label(root, image=tkpi) # ? label_image.place(x=0,y=0,width=w,height=h) root.mainloop(0) except IOError: pass root.destroy() I would like to add a time.sleep(10) "instead" of the root.mainloop(0) so that it would go to the next image after 10s. Now it changes when I press ESC. How can I have a timer there? edit: I should add that I don't want another thread that does a sleep even though it works. A: You can try root.after(10*1000, root.quit) A: There's no need to do a loop over your images -- you're already running in a loop (mainloop) so take advantage of it. The typical way to do this is to create a method that draws something, waits for a period of time, then calls itself. This isn't recursion, it's just telling the main loop "after N seconds, call me again". Here's a working example: import glob import Tkinter class Slideshow: def __init__(self, pattern="*.gif", delay=10000): root = Tkinter.Tk() root.geometry("200x200") # this label will be used to display the image. Make # it automatically fill the whole window label = Tkinter.Label(root) label.pack(side="top", fill="both", expand=True) self.current_image = None self.image_label = label self.root = root self.image_files = glob.glob(pattern) self.delay = delay # milliseconds # schedule the first image to appear as soon after the # the loop starts as possible. root.after(1, self.showImage) root.mainloop() def showImage(self): # display the next file file = self.image_files.pop(0) self.current_image = Tkinter.PhotoImage(file=file) self.image_label.configure(image=self.current_image) # either reschedule to display the file, # or quit if there are no more files to display if len(self.image_files) > 0: self.root.after(self.delay, self.showImage) else: self.root.after(self.delay, self.root.quit) def quit(self): self.root.quit() if __name__ == "__main__": app=Slideshow("images/*.gif", 1000)
Exit Tks mainloop in Python?
I'm writing a slideshow program with Tkinter, but I don't know how to go to the next image without binding a key. import os, sys import Tkinter import Image, ImageTk import time root = Tkinter.Tk() w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.overrideredirect(1) root.geometry("%dx%d+0+0" % (w, h)) root.focus_set() root.bind("<Escape>", lambda e: e.widget.quit()) image_path = os.path.join(os.getcwd(), 'images/') dirlist = os.listdir(image_path) for f in dirlist: try: image = Image.open(image_path+f) tkpi = ImageTk.PhotoImage(image) label_image = Tkinter.Label(root, image=tkpi) # ? label_image.place(x=0,y=0,width=w,height=h) root.mainloop(0) except IOError: pass root.destroy() I would like to add a time.sleep(10) "instead" of the root.mainloop(0) so that it would go to the next image after 10s. Now it changes when I press ESC. How can I have a timer there? edit: I should add that I don't want another thread that does a sleep even though it works.
[ "You can try\nroot.after(10*1000, root.quit)\n\n", "There's no need to do a loop over your images -- you're already running in a loop (mainloop) so take advantage of it. The typical way to do this is to create a method that draws something, waits for a period of time, then calls itself. This isn't recursion, it's just telling the main loop \"after N seconds, call me again\".\nHere's a working example:\nimport glob\nimport Tkinter\n\nclass Slideshow:\n def __init__(self, pattern=\"*.gif\", delay=10000):\n\n root = Tkinter.Tk()\n root.geometry(\"200x200\")\n\n # this label will be used to display the image. Make\n # it automatically fill the whole window\n label = Tkinter.Label(root) \n label.pack(side=\"top\", fill=\"both\", expand=True)\n\n self.current_image = None\n self.image_label = label\n self.root = root\n self.image_files = glob.glob(pattern)\n self.delay = delay # milliseconds\n\n # schedule the first image to appear as soon after the \n # the loop starts as possible.\n root.after(1, self.showImage)\n root.mainloop()\n\n\n def showImage(self):\n # display the next file\n file = self.image_files.pop(0)\n self.current_image = Tkinter.PhotoImage(file=file)\n self.image_label.configure(image=self.current_image)\n\n # either reschedule to display the file, \n # or quit if there are no more files to display\n if len(self.image_files) > 0:\n self.root.after(self.delay, self.showImage)\n else:\n self.root.after(self.delay, self.root.quit)\n\n def quit(self):\n self.root.quit()\n\n\nif __name__ == \"__main__\":\n app=Slideshow(\"images/*.gif\", 1000)\n\n" ]
[ 5, 5 ]
[]
[]
[ "python", "tk_toolkit", "tkinter" ]
stackoverflow_0002732847_python_tk_toolkit_tkinter.txt
Q: Correct way to create a shell like environment in python? I'm trying to create a shell like environment, where a user is presented with ">>>" and can type in any of a number of pre-defined commands. However, the only way I can think of implementing this is with a dictionary mapping commands->code and python's "exec". Is there a more correct way of doing this? A: The standard library module cmd is specifically for this. If you do end up rolling your own solution, there's no need to involve exec. Your dictionary mapping commands to code should map strings to strings. It can map strings to actual functions. In fact, a class is a mapping of strings to code (method names to method definitions). A: If it is a Python interactive interpreter you are making, check out the code module.
Correct way to create a shell like environment in python?
I'm trying to create a shell like environment, where a user is presented with ">>>" and can type in any of a number of pre-defined commands. However, the only way I can think of implementing this is with a dictionary mapping commands->code and python's "exec". Is there a more correct way of doing this?
[ "The standard library module cmd is specifically for this.\nIf you do end up rolling your own solution, there's no need to involve exec. Your dictionary mapping commands to code should map strings to strings. It can map strings to actual functions. In fact, a class is a mapping of strings to code (method names to method definitions).\n", "If it is a Python interactive interpreter you are making, check out the code module.\n" ]
[ 6, 0 ]
[]
[]
[ "exec", "python", "shell" ]
stackoverflow_0002755660_exec_python_shell.txt
Q: default values for variable argument list in Python Is it possible to set a default value for a variable argument list in Python 3? Something like: def do_it(*args=(2, 5, 21)): pass I wonder that a variable argument list is of type tuple but no tuple is accepted here. A: If not syntactically, then depending on what behavior you want: def do_it(*args): if not args: args = (2, 5, 21) or def do_it(a=2, b=5, c=21, *args): args = (a,b,c)+args should do it. A: Initializing a list like that usually isn't a good idea. The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls def f(a, L=[]): L.append(a) return L print f(1) print f(2) rint f(3) This will print [1] [1, 2] [1, 2, 3] Stolen from: http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html I generally check it something is passed in and if not then init it in the function body.
default values for variable argument list in Python
Is it possible to set a default value for a variable argument list in Python 3? Something like: def do_it(*args=(2, 5, 21)): pass I wonder that a variable argument list is of type tuple but no tuple is accepted here.
[ "If not syntactically, then depending on what behavior you want:\ndef do_it(*args):\n if not args: args = (2, 5, 21)\n\nor\ndef do_it(a=2, b=5, c=21, *args):\n args = (a,b,c)+args\n\nshould do it. \n", "Initializing a list like that usually isn't a good idea.\nThe default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls\ndef f(a, L=[]):\n L.append(a)\n return L\n\nprint f(1)\nprint f(2)\nrint f(3)\n\nThis will print\n[1]\n[1, 2]\n[1, 2, 3]\n\n\nStolen from: http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html\n\nI generally check it something is passed in and if not then init it in the function body.\n" ]
[ 7, 1 ]
[]
[]
[ "arguments", "function", "python" ]
stackoverflow_0002759464_arguments_function_python.txt
Q: Django models: Use multiple values as a key? Here is a simple model: class TakingCourse(models.Model): course = models.ForeignKey(Course) term = models.ForeignKey(Term) Instead of Django creating a default primary key, I would like to use both course and term as the primary key - taken together, they uniquely identify a tuple. Is this allowed by Django? On a related note: I am trying to represent users taking courses in certain terms. Is there a better way to do this? class Course(models.Model): name = models.CharField(max_length=200) requiredFor = models.ManyToManyField(RequirementSubSet, blank=True) offeringSchool = models.ForeignKey(School) def __unicode__(self): return "%s at %s" % (self.name, self.offeringSchool) class MyUser(models.Model): user = models.ForeignKey(User, unique=True) takingReqSets = models.ManyToManyField(RequirementSet, blank=True) takingTerms = models.ManyToManyField(Term, blank=True) takingCourses = models.ManyToManyField(TakingCourse, blank=True) school = models.ForeignKey(School) class TakingCourse(models.Model): course = models.ForeignKey(Course) term = models.ForeignKey(Term) class Term(models.Model): school = models.ForeignKey(School) isPrimaryTerm = models.BooleanField() A: You can use the unique_together option. class TakingCourse(models.Model): course = models.ForeignKey(Course) term = models.ForeignKey(Term) class Meta: unique_together = ('course', 'term') It would be better if you do something like this, though: class MyUser(models.Model): user = models.OneToOneField(User) takingReqSets = models.ManyToManyField(RequirementSet, blank=True) takingCourses = models.ManyToManyField(Course, through='TakingCourse', blank=True, null=True) school = models.ForeignKey(School) class TakingCourse(models.Model): my_user = models.ForeignKey(MyUser) course = models.ForeignKey(Course) term = models.ForeignKey(Term) class Meta: unique_together = ('my_user', 'course') Read about one to one relationships and extra fields on many to many relationships.
Django models: Use multiple values as a key?
Here is a simple model: class TakingCourse(models.Model): course = models.ForeignKey(Course) term = models.ForeignKey(Term) Instead of Django creating a default primary key, I would like to use both course and term as the primary key - taken together, they uniquely identify a tuple. Is this allowed by Django? On a related note: I am trying to represent users taking courses in certain terms. Is there a better way to do this? class Course(models.Model): name = models.CharField(max_length=200) requiredFor = models.ManyToManyField(RequirementSubSet, blank=True) offeringSchool = models.ForeignKey(School) def __unicode__(self): return "%s at %s" % (self.name, self.offeringSchool) class MyUser(models.Model): user = models.ForeignKey(User, unique=True) takingReqSets = models.ManyToManyField(RequirementSet, blank=True) takingTerms = models.ManyToManyField(Term, blank=True) takingCourses = models.ManyToManyField(TakingCourse, blank=True) school = models.ForeignKey(School) class TakingCourse(models.Model): course = models.ForeignKey(Course) term = models.ForeignKey(Term) class Term(models.Model): school = models.ForeignKey(School) isPrimaryTerm = models.BooleanField()
[ "You can use the unique_together option.\nclass TakingCourse(models.Model):\n course = models.ForeignKey(Course)\n term = models.ForeignKey(Term)\n\n class Meta:\n unique_together = ('course', 'term')\n\nIt would be better if you do something like this, though:\nclass MyUser(models.Model):\n user = models.OneToOneField(User)\n takingReqSets = models.ManyToManyField(RequirementSet, blank=True)\n takingCourses = models.ManyToManyField(Course, through='TakingCourse', blank=True, null=True)\n school = models.ForeignKey(School)\n\nclass TakingCourse(models.Model):\n my_user = models.ForeignKey(MyUser)\n course = models.ForeignKey(Course)\n term = models.ForeignKey(Term)\n\n class Meta:\n unique_together = ('my_user', 'course')\n\nRead about one to one relationships and extra fields on many to many relationships.\n" ]
[ 5 ]
[]
[]
[ "database", "django", "models", "python" ]
stackoverflow_0002759503_database_django_models_python.txt
Q: Sorting numbers in string format with Python I have a list that has some chapter numbers in string. When I sort the keys using keys function, it gives me wrong results. keys = ['1.1', '1.2', '2.1', '10.1'] keys.sort() print keys ['1.1', '1.2', '10.1', '2.1'] How can I use the sort function to get ['1.1', '1.2', '2.1', '10.1'] What if the array has something like this? ['1.1.1', '1.2.1', '10.1', '2.1'] -> ['1.1.1','1.2.1','2.1','10.1'] A: keys.sort(key=lambda x: [int(y) for y in x.split('.')]) A: from distutils.version import StrictVersion keys.sort(key=StrictVersion) Since chapter numbers are a subset of version numbers, this covers your needs. A: This works: keys.sort(key=lambda x: map(int, x.split('.'))) A: Provide a custom key argument to sort or sorted. From http://docs.python.org/library/functions.html#sorted: key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
Sorting numbers in string format with Python
I have a list that has some chapter numbers in string. When I sort the keys using keys function, it gives me wrong results. keys = ['1.1', '1.2', '2.1', '10.1'] keys.sort() print keys ['1.1', '1.2', '10.1', '2.1'] How can I use the sort function to get ['1.1', '1.2', '2.1', '10.1'] What if the array has something like this? ['1.1.1', '1.2.1', '10.1', '2.1'] -> ['1.1.1','1.2.1','2.1','10.1']
[ "keys.sort(key=lambda x: [int(y) for y in x.split('.')])\n\n", "from distutils.version import StrictVersion\nkeys.sort(key=StrictVersion)\n\nSince chapter numbers are a subset of version numbers, this covers your needs.\n", "This works:\nkeys.sort(key=lambda x: map(int, x.split('.')))\n\n", "Provide a custom key argument to sort or sorted.\nFrom http://docs.python.org/library/functions.html#sorted:\n\nkey specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).\n\n" ]
[ 10, 4, 2, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002597099_python_sorting.txt
Q: Django: Admin with multiple sites & languages I'm supposed to build some Django apps, that allow you to administer multiple sites through one backend. The contrib.sites framework is quite perfect for my purposes. I can run multiple instances of manage.py with different settings for each site; but how should django's admin deal with different settings for different sites, eg. if they have different sets of languages, a different (default) language? So there are some problem s to face if you have to work on objects coming from different sites in one admin... I think settings.ADMIN_FOR is supposed to be quite helpful for cases like this, but theres hardly any documentation about it and I think it's not really used in the actual Django version (?). So any ideas/solutions are welcome and much appreciated! Thanks a lot... A: There is an old blog post by James Bennet which might be helpful: Create a new Site object in your admin for each domain, and put the id of that Site into its settings file as SITE_ID so Django knows which site in the database corresponds to this settings file. In the settings file for your original site (the one with id 1), add the other sites’ settings files to the ADMIN_FOR setting, to let Django know that this one instance of the admin application will handle all of the sites. As documented ADMIN_FOR (for which i can not post link) should be a tuple of settings modules much like INSTALED_APPS is a tuple of django app modules. Note that blog post is from 2006 so it uses a bit outdated API.
Django: Admin with multiple sites & languages
I'm supposed to build some Django apps, that allow you to administer multiple sites through one backend. The contrib.sites framework is quite perfect for my purposes. I can run multiple instances of manage.py with different settings for each site; but how should django's admin deal with different settings for different sites, eg. if they have different sets of languages, a different (default) language? So there are some problem s to face if you have to work on objects coming from different sites in one admin... I think settings.ADMIN_FOR is supposed to be quite helpful for cases like this, but theres hardly any documentation about it and I think it's not really used in the actual Django version (?). So any ideas/solutions are welcome and much appreciated! Thanks a lot...
[ "There is an old blog post by James Bennet which might be helpful:\n\n\nCreate a new Site object in your admin for each domain, and put the id of that Site into its settings file as SITE_ID so Django knows which site in the database corresponds to this settings file.\nIn the settings file for your original site (the one with id 1), add the other sites’ settings files to the ADMIN_FOR setting, to let Django know that this one instance of the admin application will handle all of the sites.\n\n\nAs documented ADMIN_FOR (for which i can not post link) should be a tuple of settings modules much like INSTALED_APPS is a tuple of django app modules.\nNote that blog post is from 2006 so it uses a bit outdated API.\n" ]
[ 1 ]
[]
[]
[ "django", "multilingual", "multiple_sites", "python", "sites" ]
stackoverflow_0002755087_django_multilingual_multiple_sites_python_sites.txt
Q: app_label in an abstract Django model I'm trying to get an abstract model working in Django and I hit a brick wall trying to set the related_name per the recommendation here: http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name This is what my abstract model looks like: class CommonModel(models.Model): created_on = models.DateTimeField(editable=False) creared_by = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_created", editable=False) updated_on = models.DateTimeField(editable=False) updated_by = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_updated", editable=False) def save(self): if not self.id: self.created_on = datetime.now() self.created_by = user.id self.updated_on = datetime.now() self.updated_by = user.id super(CommonModel, self).save() class Meta: abstract = True My common model is in [project_root]/models.py. It is the parent object of this model, which is located in an app called Feedback [project_root]/feedback/models.py: from django.db import models from mediasharks.models import CommonModel class Feedback(CommonModel): message = models.CharField(max_length=255) request_uri = models.CharField(max_length=255) domain = models.CharField(max_length=255) feedback_type = models.IntegerField() Basically I'm trying to set up a common model so that I'll always be able to tell when and by whom database entries were created. When I run "python manage.py validate" I get this error message: KeyError: 'app_label' Am I missing something here? A: Note the bold text on your link: "Changed in development version". If you're not using a recent checkout of Django trunk - for instance, you're on the latest released version, 1.1 - you should be using this link for the documentation. That version of the text makes no reference to app_label, because it had not yet been introduced.
app_label in an abstract Django model
I'm trying to get an abstract model working in Django and I hit a brick wall trying to set the related_name per the recommendation here: http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name This is what my abstract model looks like: class CommonModel(models.Model): created_on = models.DateTimeField(editable=False) creared_by = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_created", editable=False) updated_on = models.DateTimeField(editable=False) updated_by = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_updated", editable=False) def save(self): if not self.id: self.created_on = datetime.now() self.created_by = user.id self.updated_on = datetime.now() self.updated_by = user.id super(CommonModel, self).save() class Meta: abstract = True My common model is in [project_root]/models.py. It is the parent object of this model, which is located in an app called Feedback [project_root]/feedback/models.py: from django.db import models from mediasharks.models import CommonModel class Feedback(CommonModel): message = models.CharField(max_length=255) request_uri = models.CharField(max_length=255) domain = models.CharField(max_length=255) feedback_type = models.IntegerField() Basically I'm trying to set up a common model so that I'll always be able to tell when and by whom database entries were created. When I run "python manage.py validate" I get this error message: KeyError: 'app_label' Am I missing something here?
[ "Note the bold text on your link: \"Changed in development version\". If you're not using a recent checkout of Django trunk - for instance, you're on the latest released version, 1.1 - you should be using this link for the documentation. That version of the text makes no reference to app_label, because it had not yet been introduced.\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002759824_django_django_models_python.txt
Q: Regex optional match in python fails tickettypepat = (r'MIS Notes:.*(//p//)?.*') retype = re.search(tickettypepat,line) if retype: print retype.group(0) print retype.group(1) Given the input. MIS Notes: //p// Can anyone tell me why group(0) is MIS Notes: //p// and group(1) is returning as None? I was originally using regex because, before I ran into problems the matching was more complex than just matching //p// here's the full code. I'm fairly new at this so forgive my noobness, I'm sure there are better ways of accomplishing much of this and if anyonee feels like pointing those out that would be awesome. But aside from the problem with the regex for //[pewPEW]// being too greedy it seems to be functional. I appreciate the help. Takes Text and cleans up / converts some things. filename = (r'.\4-12_4-26.txt') import re import sys #Clean up output from the web to ensure that you have one catagory per line f = open(filename) w = open('cleantext.txt','w') origdatepat = (r'(Ticket Date: )([0-9]+/[0-9]+/[0-9]+),( [0-9]+:[0-9]+ [PA]M)') tickettypepat = (r'MIS Notes:.*(//[pewPEW]//)?.*') print 'Begining Blank Line Removal' for line in f: redate = re.search(origdatepat,line) retype = re.search(tickettypepat,line) if line == ' \n': line = '' print 'Removing blank Line' #remove ',' from time and date line elif redate: line = redate.group(1) + redate.group(2)+ redate.group(3)+'\n' print 'Redating... ' + line elif retype: print retype.group(0) print retype.group(1) if retype.group(1) == '//p//': line = line + 'Type: Phone\n' print 'Setting type for... ' + line elif retype.group(1) == '//e//': line = line + 'Type: Email\n' print 'Setting type for... ' + line elif retype.group(1) == '//w//': line = line + 'Type: Walk-in\n' print 'Setting type for... ' + line elif retype.group(1) == ('' or None): line = line + 'Type: Ticket\n' print 'Setting type for... ' + line w.write(line) print 'Closing Files' f.close() w.close() And here's some sample input. Ticket No.: 20100426132 Ticket Date: 04/26/10, 10:22 AM Close Date: Primary User: XXX Branch: XXX Help Tech: XXX Status: Pending Priority: Medium Application: xxx Description: some issue Resolution: some resolution MIS Notes: some random stuff //p// followed by more stuff Key Words: Ticket No.: 20100426132 Ticket Date: 04/26/10, 10:22 AM Close Date: Primary User: XXX Branch: XXX Help Tech: XXX Status: Pending Priority: Medium Application: xxx Description: some issue Resolution: some resolution MIS Notes: //p// Key Words: Ticket No.: 20100426132 Ticket Date: 04/26/10, 10:22 AM Close Date: Primary User: XXX Branch: XXX Help Tech: XXX Status: Pending Priority: Medium Application: xxx Description: some issue Resolution: some resolution MIS Notes: //e// stuff.... Key Words: Ticket No.: 20100426132 Ticket Date: 04/26/10, 10:22 AM Close Date: Primary User: XXX Branch: XXX Help Tech: XXX Status: Pending Priority: Medium Application: xxx Description: some issue Resolution: some resolution MIS Notes: Key Words: A: MIS Notes:.*(//p//)?.* works like this, on the example of "MIS Notes: //p//" as the target: MIS Notes: matches "MIS Notes:", no surprises here. .* immediately runs to the end of the string (match so far "MIS Notes: //p//") (//p//)? is optional. Nothing happens. .* has nothing left to match, we are at the end of the string already. Since the star allows zero matches for the preceding atom, the regex engine stops reporting the entire string as a match, and the sub-group as empty. Now when you change the regex to MIS Notes:.*(//p//).*, the behavior changes: MIS Notes: matches "MIS Notes:", still no surprises here. .* immediately runs to the end of the string (match so far "MIS Notes: //p//") (//p//) is necessary. The engine starts to backtrack character by character in order to fulfill this requirement. (Match so far "MIS Notes: ") (//p//) can match. Sub-group one is saved and contains "//p//". .* runs to the end of the string. Hint: If you are not interested in what it matches, it is superfluous and you can remove it. Now when you change the regex to MIS Notes:.*?//(p)//, the behavior changes again: MIS Notes: matches "MIS Notes:", and still no surprises here. .*? is non-greedy and checks the following atom before it proceeds (match so far "MIS Notes: ") //(p)// can match. Sub-group one is saved and contains "p". Done. Note that no backtracking occurs, this saves time. Now if you know that there can be no / before the //p//, you can use: MIS Notes:[^/]*//(p)//: MIS Notes: matches "MIS Notes:", you get the idea. [^/]* can fast-forward to the first slash (this is faster than .*?) //(p)// can match. Sub-group one is saved and contains "p". Done. Note that no backtracking occurs, this saves time. This should be faster than version #3. A: Regex are greedy, which means that .* matches as much as it can, the entire string. So there is nothing left to match for the optional group. group(0) is always the entire matched sting. From you comment, why do you event want regex? Isn't something like this enough: if line.startswith('MIS Notes:'): # starts with that string data = line[len('MIS Notes:'):] # the rest in the interesting part if '//p//' in data: stuff, sep, rest = data.partition('//p//') # or sothing like that else: pass #other stuff A: The pattern is ambiguous for your purposes. It would be good to group them by prefix or suffix. In the example here, I've chosen prefix grouping. Basically, if //p// occurs in the line, then prefix is non-empty. Suffix will everything after the //p// item, or everything in the line if it doesn't exist. import re lines = ['MIS Notes: //p//', 'MIS Notes: prefix//p//suffix'] tickettypepat = (r'MIS Notes: (?:(.*)//p//)?(.*)') for line in lines: m = re.search(tickettypepat,line) print 'line:', line if m: print 'groups:', m.groups() else: print 'groups:', m results: line: MIS Notes: //p// groups: ('', '') line: MIS Notes: prefix//p//suffix groups: ('prefix', 'suffix')
Regex optional match in python fails
tickettypepat = (r'MIS Notes:.*(//p//)?.*') retype = re.search(tickettypepat,line) if retype: print retype.group(0) print retype.group(1) Given the input. MIS Notes: //p// Can anyone tell me why group(0) is MIS Notes: //p// and group(1) is returning as None? I was originally using regex because, before I ran into problems the matching was more complex than just matching //p// here's the full code. I'm fairly new at this so forgive my noobness, I'm sure there are better ways of accomplishing much of this and if anyonee feels like pointing those out that would be awesome. But aside from the problem with the regex for //[pewPEW]// being too greedy it seems to be functional. I appreciate the help. Takes Text and cleans up / converts some things. filename = (r'.\4-12_4-26.txt') import re import sys #Clean up output from the web to ensure that you have one catagory per line f = open(filename) w = open('cleantext.txt','w') origdatepat = (r'(Ticket Date: )([0-9]+/[0-9]+/[0-9]+),( [0-9]+:[0-9]+ [PA]M)') tickettypepat = (r'MIS Notes:.*(//[pewPEW]//)?.*') print 'Begining Blank Line Removal' for line in f: redate = re.search(origdatepat,line) retype = re.search(tickettypepat,line) if line == ' \n': line = '' print 'Removing blank Line' #remove ',' from time and date line elif redate: line = redate.group(1) + redate.group(2)+ redate.group(3)+'\n' print 'Redating... ' + line elif retype: print retype.group(0) print retype.group(1) if retype.group(1) == '//p//': line = line + 'Type: Phone\n' print 'Setting type for... ' + line elif retype.group(1) == '//e//': line = line + 'Type: Email\n' print 'Setting type for... ' + line elif retype.group(1) == '//w//': line = line + 'Type: Walk-in\n' print 'Setting type for... ' + line elif retype.group(1) == ('' or None): line = line + 'Type: Ticket\n' print 'Setting type for... ' + line w.write(line) print 'Closing Files' f.close() w.close() And here's some sample input. Ticket No.: 20100426132 Ticket Date: 04/26/10, 10:22 AM Close Date: Primary User: XXX Branch: XXX Help Tech: XXX Status: Pending Priority: Medium Application: xxx Description: some issue Resolution: some resolution MIS Notes: some random stuff //p// followed by more stuff Key Words: Ticket No.: 20100426132 Ticket Date: 04/26/10, 10:22 AM Close Date: Primary User: XXX Branch: XXX Help Tech: XXX Status: Pending Priority: Medium Application: xxx Description: some issue Resolution: some resolution MIS Notes: //p// Key Words: Ticket No.: 20100426132 Ticket Date: 04/26/10, 10:22 AM Close Date: Primary User: XXX Branch: XXX Help Tech: XXX Status: Pending Priority: Medium Application: xxx Description: some issue Resolution: some resolution MIS Notes: //e// stuff.... Key Words: Ticket No.: 20100426132 Ticket Date: 04/26/10, 10:22 AM Close Date: Primary User: XXX Branch: XXX Help Tech: XXX Status: Pending Priority: Medium Application: xxx Description: some issue Resolution: some resolution MIS Notes: Key Words:
[ "MIS Notes:.*(//p//)?.* works like this, on the example of \"MIS Notes: //p//\" as the target:\n\nMIS Notes: matches \"MIS Notes:\", no surprises here.\n.* immediately runs to the end of the string (match so far \"MIS Notes: //p//\")\n(//p//)? is optional. Nothing happens.\n.* has nothing left to match, we are at the end of the string already. Since the star allows zero matches for the preceding atom, the regex engine stops reporting the entire string as a match, and the sub-group as empty.\n\nNow when you change the regex to MIS Notes:.*(//p//).*, the behavior changes:\n\nMIS Notes: matches \"MIS Notes:\", still no surprises here.\n.* immediately runs to the end of the string (match so far \"MIS Notes: //p//\")\n(//p//) is necessary. The engine starts to backtrack character by character in order to fulfill this requirement. (Match so far \"MIS Notes: \")\n(//p//) can match. Sub-group one is saved and contains \"//p//\".\n.* runs to the end of the string. Hint: If you are not interested in what it matches, it is superfluous and you can remove it.\n\nNow when you change the regex to MIS Notes:.*?//(p)//, the behavior changes again:\n\nMIS Notes: matches \"MIS Notes:\", and still no surprises here.\n.*? is non-greedy and checks the following atom before it proceeds (match so far \"MIS Notes: \")\n//(p)// can match. Sub-group one is saved and contains \"p\".\nDone. Note that no backtracking occurs, this saves time.\n\nNow if you know that there can be no / before the //p//, you can use: MIS Notes:[^/]*//(p)//:\n\nMIS Notes: matches \"MIS Notes:\", you get the idea.\n[^/]* can fast-forward to the first slash (this is faster than .*?)\n//(p)// can match. Sub-group one is saved and contains \"p\".\nDone. Note that no backtracking occurs, this saves time. This should be faster than version #3.\n\n", "Regex are greedy, which means that .* matches as much as it can, the entire string. So there is nothing left to match for the optional group. group(0) is always the entire matched sting.\nFrom you comment, why do you event want regex? Isn't something like this enough:\nif line.startswith('MIS Notes:'): # starts with that string\n data = line[len('MIS Notes:'):] # the rest in the interesting part\n if '//p//' in data:\n stuff, sep, rest = data.partition('//p//') # or sothing like that\n else:\n pass #other stuff\n\n", "The pattern is ambiguous for your purposes. It would be good to group them by prefix or suffix. In the example here, I've chosen prefix grouping. Basically, if //p// occurs in the line, then prefix is non-empty. Suffix will everything after the //p// item, or everything in the line if it doesn't exist. \nimport re\nlines = ['MIS Notes: //p//',\n 'MIS Notes: prefix//p//suffix']\n\ntickettypepat = (r'MIS Notes: (?:(.*)//p//)?(.*)')\nfor line in lines:\n m = re.search(tickettypepat,line)\n print 'line:', line\n if m: print 'groups:', m.groups()\n else: print 'groups:', m\n\nresults:\nline: MIS Notes: //p//\ngroups: ('', '')\nline: MIS Notes: prefix//p//suffix\ngroups: ('prefix', 'suffix')\n\n" ]
[ 4, 1, 0 ]
[]
[]
[ "option_type", "python", "regex", "regex_group" ]
stackoverflow_0002760083_option_type_python_regex_regex_group.txt
Q: limiting the rate of emails using python I have a python script which reads email addresses from a database for a particular date, example today, and sends out an email message to them one by one. It reads data from MySQL using the MySQLdb module and stores all results in a dictionary and sends out emails using : rows = cursor.fetchall () #All email addresses returned that are supposed to go out on todays date. for row is rows: #send email However, my hosting service only lets me send out 500 emails per hour. How can I limit my script from making sure only 500 emails are sent in an hour and then to check the database if more emails are left for today or not and then to send them in the next hour. The script is activated using a cron job. A: If you don't mind if the script is running for hours on end, you can just pause for a few seconds between each email. from time import sleep if address_count < 500: sleep_time = 0 else: sleep_time = 7.5 for address in addresses: send_message(address) sleep(sleep_time) (Note: This was written for maximum clarity, not maximum efficiency) A: When you send an email, do you record it in the database in some way so that the same email address wouldn't be returned by another query in the same day? (say, by removing the email address, or setting a flag, or something?) If so, you could just add a LIMIT 500 to your SQL query and run the Python script every hour. A: I would have the script run hourly using cron and limit the number of records that you take from the database to about 490 (just to be on the safe side) by using fetchmany instead of fetchall.
limiting the rate of emails using python
I have a python script which reads email addresses from a database for a particular date, example today, and sends out an email message to them one by one. It reads data from MySQL using the MySQLdb module and stores all results in a dictionary and sends out emails using : rows = cursor.fetchall () #All email addresses returned that are supposed to go out on todays date. for row is rows: #send email However, my hosting service only lets me send out 500 emails per hour. How can I limit my script from making sure only 500 emails are sent in an hour and then to check the database if more emails are left for today or not and then to send them in the next hour. The script is activated using a cron job.
[ "If you don't mind if the script is running for hours on end, you can just pause for a few seconds between each email.\nfrom time import sleep\n\nif address_count < 500:\n sleep_time = 0\nelse:\n sleep_time = 7.5\n\nfor address in addresses:\n send_message(address)\n sleep(sleep_time)\n\n(Note: This was written for maximum clarity, not maximum efficiency)\n", "When you send an email, do you record it in the database in some way so that the same email address wouldn't be returned by another query in the same day? (say, by removing the email address, or setting a flag, or something?) If so, you could just add a LIMIT 500 to your SQL query and run the Python script every hour.\n", "I would have the script run hourly using cron and limit the number of records that you take from the database to about 490 (just to be on the safe side) by using fetchmany instead of fetchall.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "email", "mysql", "python" ]
stackoverflow_0002760351_email_mysql_python.txt
Q: str is not callable error in python import sys import md5 from TOSSIM import * from RadioCountMsg import * t = Tossim([]) #The Tossim object is defined here m = t.mac()#The mac layer is defined here , in which the communication takes place r = t.radio()#The radio communication link object is defined here , as the communication needs Rf frequency to transfer t.addChannel("RadioCountToLedsC", sys.stdout)# The various channels through which communication will take place t.addChannel("LedsC", sys.stdout) #The no of nodes that would be required in the simulation has to be entered here print("enter the no of nodes you want ") n=input() for i in range(0, n): m = t.getNode(i) m.bootAtTime((31 + t.ticksPerSecond() / 10) * i + 1) #The booting time is defined so that the time at which the node would be booted is given f = open("topo.txt", "r") #The topography is defined in topo.txt so that the RF frequencies of the transmission between nodes are are set lines = f.readlines() for line in lines: s = line.split() if (len(s) > 0): if (s[0] == "gain"): r.add(int(s[1]), int(s[2]), float(s[3])) #The topogrography is added to the radio object noise = open("meyer-heavy.txt", "r") #The noise model is defined for the nodes lines = noise.readlines() for line in lines: str = line.strip() if (str != ""): val = int(str) for i in range(0, 4): t.getNode(i).addNoiseTraceReading(val) for i in range (0, n): t.getNode(i).createNoiseModel() #The noise model is created for each node for i in range(0,n): t.runNextEvent() fk=open("key.txt","w") for i in range(0,n): if i ==0 : key=raw_input() fk.write(key) ak=key key=md5.new() key.update(str(ak)) ak=key.digest() fk.write(ak) fk.close() fk=open("key.txt","w") plaint=open("pt.txt") for i in range(0,n): msg = RadioCountMsg() msg.set_counter(7) pkt = t.newPacket()#A packet is defined according to a certain format print("enter message to be transported") ms=raw_input()#The message to be transported is taken as input #The RC5 encryption has to be done here plaint.write(ms) pkt.setData(msg.data) pkt.setType(msg.get_amType()) pkt.setDestination(i+1)#The destination to which the packet will be sent is set print "Delivering " + " to" ,i+1 pkt.deliver(i+1, t.time() + 3) fk.close() print "the key to be displayed" ki=raw_input() fk=open("key.txt") for i in range(0,n): if i==ki: ms=fk.readline() for i in range(0,n): msg=RadioCountMsg() msg.set_counter(7) pkt=t.newPacket() msg.data=ms pkt.setData(msg.data) pkt.setType(msg.get_amType()) pkt.setDestination(i+1) pkt.deliver(i+1,t.time()+3) #The key has to be broadcasted here so that the decryption can take place for i in range(0, n): t.runNextEvent(); this code gives me error here key.update(str(ak)) . when i run a similar code on the python terminal there is no such error but this code pops up an error . why so? A: On line 35 you reassign 'str' from the built-in it originally references to a different object. Then, on line 53, you try to use it as the original built-in again. If you want to use 'str' as 'str()' on line 53, you need to use a different variable name up on line 35 (and 36, and 37) Don't use 'str' here: for line in lines: str = line.strip() if (str != ""): for i in range(0, 4): t.getNode(i).addNoiseTraceReading(val) A: Don't use the name str for variables. It's a the name of a type in Python.
str is not callable error in python
import sys import md5 from TOSSIM import * from RadioCountMsg import * t = Tossim([]) #The Tossim object is defined here m = t.mac()#The mac layer is defined here , in which the communication takes place r = t.radio()#The radio communication link object is defined here , as the communication needs Rf frequency to transfer t.addChannel("RadioCountToLedsC", sys.stdout)# The various channels through which communication will take place t.addChannel("LedsC", sys.stdout) #The no of nodes that would be required in the simulation has to be entered here print("enter the no of nodes you want ") n=input() for i in range(0, n): m = t.getNode(i) m.bootAtTime((31 + t.ticksPerSecond() / 10) * i + 1) #The booting time is defined so that the time at which the node would be booted is given f = open("topo.txt", "r") #The topography is defined in topo.txt so that the RF frequencies of the transmission between nodes are are set lines = f.readlines() for line in lines: s = line.split() if (len(s) > 0): if (s[0] == "gain"): r.add(int(s[1]), int(s[2]), float(s[3])) #The topogrography is added to the radio object noise = open("meyer-heavy.txt", "r") #The noise model is defined for the nodes lines = noise.readlines() for line in lines: str = line.strip() if (str != ""): val = int(str) for i in range(0, 4): t.getNode(i).addNoiseTraceReading(val) for i in range (0, n): t.getNode(i).createNoiseModel() #The noise model is created for each node for i in range(0,n): t.runNextEvent() fk=open("key.txt","w") for i in range(0,n): if i ==0 : key=raw_input() fk.write(key) ak=key key=md5.new() key.update(str(ak)) ak=key.digest() fk.write(ak) fk.close() fk=open("key.txt","w") plaint=open("pt.txt") for i in range(0,n): msg = RadioCountMsg() msg.set_counter(7) pkt = t.newPacket()#A packet is defined according to a certain format print("enter message to be transported") ms=raw_input()#The message to be transported is taken as input #The RC5 encryption has to be done here plaint.write(ms) pkt.setData(msg.data) pkt.setType(msg.get_amType()) pkt.setDestination(i+1)#The destination to which the packet will be sent is set print "Delivering " + " to" ,i+1 pkt.deliver(i+1, t.time() + 3) fk.close() print "the key to be displayed" ki=raw_input() fk=open("key.txt") for i in range(0,n): if i==ki: ms=fk.readline() for i in range(0,n): msg=RadioCountMsg() msg.set_counter(7) pkt=t.newPacket() msg.data=ms pkt.setData(msg.data) pkt.setType(msg.get_amType()) pkt.setDestination(i+1) pkt.deliver(i+1,t.time()+3) #The key has to be broadcasted here so that the decryption can take place for i in range(0, n): t.runNextEvent(); this code gives me error here key.update(str(ak)) . when i run a similar code on the python terminal there is no such error but this code pops up an error . why so?
[ "On line 35 you reassign 'str' from the built-in it originally references to a different object. Then, on line 53, you try to use it as the original built-in again. If you want to use 'str' as 'str()' on line 53, you need to use a different variable name up on line 35 (and 36, and 37)\nDon't use 'str' here:\nfor line in lines:\n str = line.strip()\n if (str != \"\"):\n for i in range(0, 4):\n t.getNode(i).addNoiseTraceReading(val)\n\n", "Don't use the name str for variables. It's a the name of a type in Python.\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002760526_python.txt
Q: how to pass a command line argument to a c++ file through a python code? i am compiling a c++ file in python code using this os.system("rc.cpp") and then os.system("./a.out") . I would like to pass a command line argument to the rc file . how do i do it? A: You should be using the subprocess module to call other executables. subprocess.Popen takes a list as it's first argument. The first item in the list is the executable you'd like to call. All list items are the arguments passed to the executable. from subprocess import Popen p = Popen(['/usr/bin/foo', 'arg1', 'arg2']) A: Take a look at scons: http://www.scons.org/ The build configuration files you write for it are python scripts.
how to pass a command line argument to a c++ file through a python code?
i am compiling a c++ file in python code using this os.system("rc.cpp") and then os.system("./a.out") . I would like to pass a command line argument to the rc file . how do i do it?
[ "You should be using the subprocess module to call other executables. subprocess.Popen takes a list as it's first argument. The first item in the list is the executable you'd like to call. All list items are the arguments passed to the executable.\nfrom subprocess import Popen\np = Popen(['/usr/bin/foo', 'arg1', 'arg2'])\n\n", "Take a look at scons: http://www.scons.org/\nThe build configuration files you write for it are python scripts.\n" ]
[ 1, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0002760541_c++_python.txt
Q: Bypass django form validation on new form instance I have a situation where we are trying to autofill some form data on the second page of a signup and I was wondering if there's a way to bypass the entire form validation when we pass in only a couple of fields? so we have something like form = NewForm(request.POST) Where request.POST only contains some of the fields in NewForm(). So the page loads and there is feedback about how some fields are not filled in yet. This all happens from the GET request of the second page. Is there a way to do something like... form = NewForm(request.POST, validate=False) A: If you're passing in initial values, you should use the initial parameter, not data (ie the first positional argument). This does not trigger validation. form = NewForm(initial=dict_of_field_values)
Bypass django form validation on new form instance
I have a situation where we are trying to autofill some form data on the second page of a signup and I was wondering if there's a way to bypass the entire form validation when we pass in only a couple of fields? so we have something like form = NewForm(request.POST) Where request.POST only contains some of the fields in NewForm(). So the page loads and there is feedback about how some fields are not filled in yet. This all happens from the GET request of the second page. Is there a way to do something like... form = NewForm(request.POST, validate=False)
[ "If you're passing in initial values, you should use the initial parameter, not data (ie the first positional argument). This does not trigger validation.\nform = NewForm(initial=dict_of_field_values)\n\n" ]
[ 6 ]
[]
[]
[ "django", "python", "validation" ]
stackoverflow_0002760793_django_python_validation.txt
Q: Navigation graphics overlayed over video Imagine I have a video playing.. Can I have some sort of motion graphics being played 'over' that video.. Like say the moving graphics is on an upper layer than the video, which would be the lower layer.. I am comfortable in a C++ and Python, so a solution that uses these two will be highly appreciated.. Thank you in advance, Rishi.. A: I'm not sure I understand the question correctly but a video file is a sequence of pictures that you can extract (for instance with the opencv library C++ interface) and then you can use it wherever you want. You can play the video on the sides of an opengl 3D cube (available in all opengl tutorials) and other 3D elements around it. Of course you can also displays it in a conventional 2D interface and draw stuff on top of it, but for this you need a graphical ui. Is it what you thought or am I completely lost?
Navigation graphics overlayed over video
Imagine I have a video playing.. Can I have some sort of motion graphics being played 'over' that video.. Like say the moving graphics is on an upper layer than the video, which would be the lower layer.. I am comfortable in a C++ and Python, so a solution that uses these two will be highly appreciated.. Thank you in advance, Rishi..
[ "I'm not sure I understand the question correctly but a video file is a sequence of pictures that you can extract (for instance with the opencv library C++ interface) and then you can use it wherever you want. You can play the video on the sides of an opengl 3D cube (available in all opengl tutorials) and other 3D elements around it.\nOf course you can also displays it in a conventional 2D interface and draw stuff on top of it, but for this you need a graphical ui.\nIs it what you thought or am I completely lost?\n" ]
[ 0 ]
[]
[]
[ "c++", "graphics", "python", "video", "video_processing" ]
stackoverflow_0002759738_c++_graphics_python_video_video_processing.txt
Q: Problem with list slice syntax in python The extended indexing syntax is mentioned in python's doc. slice([start], stop[, step]) Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator. a[start:stop:step] works as described. But what about the second one? How is it used? A: a[start:stop,i] calls the method a.__getitem__((slice(start,stop,None), i)). This raises a TypeError if a is a list, but it is valid and useful notation if a is a numpy array. In fact, I believe the developers of Numpy asked the developers of Python to extend valid Python slicing notation precisely so that numpy array slicing notation could be implemented more easily. For example, import numpy as np arr=np.arange(12).reshape(4,3) print(arr) # [[ 0 1 2] # [ 3 4 5] # [ 6 7 8] # [ 9 10 11]] 1:3 selects rows 1 and 2, and the 2 selects the third column: print(arr[1:3,2]) # [5 8] PS. To experiment with what slice is getting sent to __getitem__, you can play around with this toy code: class Foo(list): def __getitem__(self,key): return repr(key) foo=Foo(range(10)) print(foo[1:5,1,2]) # (slice(1, 5, None), 1, 2) A: The notation [:,:] is used to slice multidimensional arrays. Python doesn't have any multi-dimensional arrays by default, but the syntax supports it and numpy for example takes advantage of this syntax.
Problem with list slice syntax in python
The extended indexing syntax is mentioned in python's doc. slice([start], stop[, step]) Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator. a[start:stop:step] works as described. But what about the second one? How is it used?
[ "a[start:stop,i] calls the method a.__getitem__((slice(start,stop,None), i)).\nThis raises a TypeError if a is a list, but it is valid and useful notation if a is a numpy array. In fact, I believe the developers of Numpy asked the developers of Python to extend valid Python slicing notation precisely so that numpy array slicing notation could be implemented more easily.\nFor example, \nimport numpy as np\narr=np.arange(12).reshape(4,3)\nprint(arr)\n# [[ 0 1 2]\n# [ 3 4 5]\n# [ 6 7 8]\n# [ 9 10 11]]\n\n1:3 selects rows 1 and 2, and the 2 selects the third column:\nprint(arr[1:3,2])\n# [5 8]\n\nPS. To experiment with what slice is getting sent to __getitem__, you can \nplay around with this toy code:\nclass Foo(list):\n def __getitem__(self,key):\n return repr(key)\n\nfoo=Foo(range(10))\nprint(foo[1:5,1,2])\n# (slice(1, 5, None), 1, 2)\n\n", "The notation [:,:] is used to slice multidimensional arrays. Python doesn't have any multi-dimensional arrays by default, but the syntax supports it and numpy for example takes advantage of this syntax.\n" ]
[ 12, 4 ]
[]
[]
[ "python", "slice", "syntax" ]
stackoverflow_0002761003_python_slice_syntax.txt
Q: In python beyond 'exec string' is there a way to 'import' using the db as a filesystem Although it does not seem possible, I wanted to put this out there to see if others had some innovative solutions to 'dynamically loading and executing code in python' So if one saved code in a database, one could read it and 'exec it', however if one wanted to use it in a similar fashion to the filesystem, one would need to 'save and load the compiled .pyc' create an 'import dbimp' ala 'import imp' etc. any pointers? ideas? thoughts? A: See PEP 302: New Import Hooks, for details on how to hook the importer. Python 3.1 has an importlib, designed to make hooking the importer a bit easier. A: It is possible to implement customized import hooks and register them into sys.meta_path. See PEP 302 for the details.
In python beyond 'exec string' is there a way to 'import' using the db as a filesystem
Although it does not seem possible, I wanted to put this out there to see if others had some innovative solutions to 'dynamically loading and executing code in python' So if one saved code in a database, one could read it and 'exec it', however if one wanted to use it in a similar fashion to the filesystem, one would need to 'save and load the compiled .pyc' create an 'import dbimp' ala 'import imp' etc. any pointers? ideas? thoughts?
[ "See PEP 302: New Import Hooks, for details on how to hook the importer.\nPython 3.1 has an importlib, designed to make hooking the importer a bit easier.\n", "It is possible to implement customized import hooks and register them into sys.meta_path. See PEP 302 for the details.\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002761013_python.txt
Q: Writing a file shredder in python or ruby? In the effort to learn python and/or ruby, I was wondering how a file shredder would be implemented? I would like it to take in a file as an argument and then employ an algorithm to make that file unrecoverable. Would possibly add the support for multiple files or even whole directories later. A: Just as a warning, shredders generally will have varying levels of success on modern systems, thanks to journals, copy-on-write file systems, wear leveling (flash), and other techniques used in modern system. Might wanna check out wikipedia on some of the pitfalls. In short, you'd need to be able to write directly on top of the currently existing data. There's a few different patterns of varying levels of security, but often if you overwrite the file about 25 times with random data (rounding up to the next block size) the file should be completely unrecoverable (at least that copy of the data). There are other techniques that can securely overwrite it in less passes (3 passes, random, ones, then zeros also works decently well). A: Since this is a learning exercise and not a professional attempt to secure data. How about this: 1. Discover the length of the file. 2. Write 0's to the same length of the file. 3. Save the file. 4. Delete the file. Then make another program that tries to recover the file. But yes, if looking to make something professional and not just an exercise, look into kitsune's answer.
Writing a file shredder in python or ruby?
In the effort to learn python and/or ruby, I was wondering how a file shredder would be implemented? I would like it to take in a file as an argument and then employ an algorithm to make that file unrecoverable. Would possibly add the support for multiple files or even whole directories later.
[ "Just as a warning, shredders generally will have varying levels of success on modern systems, thanks to journals, copy-on-write file systems, wear leveling (flash), and other techniques used in modern system. Might wanna check out wikipedia on some of the pitfalls.\n\nIn short, you'd need to be able to write directly on top of the currently existing data. There's a few different patterns of varying levels of security, but often if you overwrite the file about 25 times with random data (rounding up to the next block size) the file should be completely unrecoverable (at least that copy of the data). There are other techniques that can securely overwrite it in less passes (3 passes, random, ones, then zeros also works decently well).\n", "Since this is a learning exercise and not a professional attempt to secure data. How about this:\n1. Discover the length of the file.\n2. Write 0's to the same length of the file.\n3. Save the file.\n4. Delete the file.\nThen make another program that tries to recover the file.\nBut yes, if looking to make something professional and not just an exercise, look into kitsune's answer.\n" ]
[ 4, 1 ]
[]
[]
[ "python", "ruby", "shred" ]
stackoverflow_0002758868_python_ruby_shred.txt
Q: Getting a RichTextCtrl's default font size in wxPython I have a RichTextCtrl, which I've modified to accept HTML input. The HTML parsing code needs to be able to increase and decrease the font size as it gets tags like <font size="-1">, but I can't work out how to get the control's default font size to adjust. I tried the following (where self is my RichTextCtrl): fred = wx.richtext.RichTextAttr() self.GetStyle(0,fred) print fred.GetFontSize() However, the final instruction fails, because GetStyle turns fred into a TextAttrEx and so I get AttributeError: 'TextAttrEx' object has no attribute 'GetFontSize'. Am I missing a vastly easier way of getting the default font size? A: Worked this out. Before any data is written to the control: self.defaultstyle = wx.richtext.RichTextAttr() self.GetStyle(self.GetInsertionPoint(), self.defaultstyle) self.defaultsize = self.defaultstyle.GetFont().GetPointSize()
Getting a RichTextCtrl's default font size in wxPython
I have a RichTextCtrl, which I've modified to accept HTML input. The HTML parsing code needs to be able to increase and decrease the font size as it gets tags like <font size="-1">, but I can't work out how to get the control's default font size to adjust. I tried the following (where self is my RichTextCtrl): fred = wx.richtext.RichTextAttr() self.GetStyle(0,fred) print fred.GetFontSize() However, the final instruction fails, because GetStyle turns fred into a TextAttrEx and so I get AttributeError: 'TextAttrEx' object has no attribute 'GetFontSize'. Am I missing a vastly easier way of getting the default font size?
[ "Worked this out. Before any data is written to the control:\nself.defaultstyle = wx.richtext.RichTextAttr()\nself.GetStyle(self.GetInsertionPoint(), self.defaultstyle)\nself.defaultsize = self.defaultstyle.GetFont().GetPointSize()\n\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0002751943_python_wxpython_wxwidgets.txt
Q: Are classes necessary for creating methods (defs) in Python? Are classes necessary for creating methods (defs) in Python? A: No. However, def's which aren't part of a class are usually called functions, not methods - but they are exactly the same thing, aside from not being associated with a class. def myFunction(arg1, arg2): # do something here A: No, you can create functions using def without having to wrap them in classes. If you are coming from a Java or C# background - where a class is required - you may want to read over An Introduction to Python: Functions or a similar article to understand how to work with functions in Python, as the language provides many other features such as first-class functions, returning multiple values, anonymous functions, etc. A: It depends on your definition of "method". In some sense, no, classes aren't necessary for creating methods in Python, because there are no methods anyway in Python. There are only procedures (which, for some strange reason, are called functions in Python). You can create a procedure anywhere you like. A method is just syntactic sugar for a procedure assigned to an attribute. In another sense, yes, classes are necessary for creating methods. It follows pretty much from the definition of what a method is in Python: a procedure stuck into a class's __dict__. (Note, however, that this means that you do not have to be inside a class definition to create method, you can create a procedure anywhere and any way you like and stick it into the class afterwards.) [Note: I have simplified a bit when it comes to exactly what a method is, how they are synthesized, how they are represented and how you can create your own.]
Are classes necessary for creating methods (defs) in Python?
Are classes necessary for creating methods (defs) in Python?
[ "No. However, def's which aren't part of a class are usually called functions, not methods - but they are exactly the same thing, aside from not being associated with a class.\ndef myFunction(arg1, arg2):\n # do something here\n\n", "No, you can create functions using def without having to wrap them in classes.\nIf you are coming from a Java or C# background - where a class is required - you may want to read over An Introduction to Python: Functions or a similar article to understand how to work with functions in Python, as the language provides many other features such as first-class functions, returning multiple values, anonymous functions, etc.\n", "It depends on your definition of \"method\".\nIn some sense, no, classes aren't necessary for creating methods in Python, because there are no methods anyway in Python. There are only procedures (which, for some strange reason, are called functions in Python). You can create a procedure anywhere you like. A method is just syntactic sugar for a procedure assigned to an attribute.\nIn another sense, yes, classes are necessary for creating methods. It follows pretty much from the definition of what a method is in Python: a procedure stuck into a class's __dict__. (Note, however, that this means that you do not have to be inside a class definition to create method, you can create a procedure anywhere and any way you like and stick it into the class afterwards.)\n[Note: I have simplified a bit when it comes to exactly what a method is, how they are synthesized, how they are represented and how you can create your own.]\n" ]
[ 12, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002761145_python.txt
Q: taking a character input in python from a file? in python , suppose i have file data.txt . which has 6 lines of data . I want to calculate the no of lines which i am planning to do by going through each character and finding out the number of '\n' in the file . How to take one character input from the file ? Readline takes the whole line . A: I think the method you're looking for is readlines, as in lines = open("inputfilex.txt", "r").readlines() This will give you a list of each of the lines in the file. To find out how many lines, you can just do: len(lines) And then access it using indexes, like lines[3] or lines[-1] as you would any normal Python list. A: You can use read(1) to read a single byte. help(file) says: read(size) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. Note that reading a file a byte at a time is quite un-"Pythonic". This is par for the course in C, but Python can do a lot more work with far less code. For example, you can read the entire file into an array in one line of code: lines = f.readlines() You could then access by line number with a simple lines[lineNumber] lookup. Or if you don't want to store the entire file in memory at once, you can iterate over it line-by-line: for line in f: # Do whatever you want. That is much more readable and idiomatic. A: It seems the simplest answer for you would be to do: for line in file: lines += 1 # do whatever else you need to do for each line Or the equivalent construction explicitly using readline(). I'm not sure why you want to look at every character when you said above that readline() is correctly reading each line in its entirety. A: To access a file based on its lines, make a list of its lines. with open('myfile') as f: lines = list(f) then simply access lines[3] to get the fourth line and so forth. (Note that this will not strip the newline characters.) The linecache module can also be useful for this.
taking a character input in python from a file?
in python , suppose i have file data.txt . which has 6 lines of data . I want to calculate the no of lines which i am planning to do by going through each character and finding out the number of '\n' in the file . How to take one character input from the file ? Readline takes the whole line .
[ "I think the method you're looking for is readlines, as in \nlines = open(\"inputfilex.txt\", \"r\").readlines()\n\nThis will give you a list of each of the lines in the file. To find out how many lines, you can just do:\nlen(lines)\n\nAnd then access it using indexes, like lines[3] or lines[-1] as you would any normal Python list.\n", "You can use read(1) to read a single byte. help(file) says:\n\nread(size) -> read at most size bytes, returned as a string.\nIf the size argument is negative or omitted, read until EOF is reached.\n Notice that when in non-blocking mode, less data than what was requested\n may be returned, even if no size parameter was given.\n\nNote that reading a file a byte at a time is quite un-\"Pythonic\". This is par for the course in C, but Python can do a lot more work with far less code. For example, you can read the entire file into an array in one line of code:\nlines = f.readlines()\n\nYou could then access by line number with a simple lines[lineNumber] lookup.\nOr if you don't want to store the entire file in memory at once, you can iterate over it line-by-line:\nfor line in f:\n # Do whatever you want.\n\nThat is much more readable and idiomatic.\n", "It seems the simplest answer for you would be to do:\nfor line in file:\n lines += 1\n # do whatever else you need to do for each line\n\nOr the equivalent construction explicitly using readline(). I'm not sure why you want to look at every character when you said above that readline() is correctly reading each line in its entirety.\n", "To access a file based on its lines, make a list of its lines.\nwith open('myfile') as f:\n lines = list(f)\n\nthen simply access lines[3] to get the fourth line and so forth. (Note that this will not strip the newline characters.)\nThe linecache module can also be useful for this.\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002761245_file_python.txt
Q: Third-party titlecase method in Python The standard string title() method in Python is pretty naive and doesn't correctly handle converting even fairly simple words and phrases to title case (hyphenated words, phrases with quotes, phrases with prepositions, etc.). In Googling around, I found a few solutions in different languages to this problem. Can anyone recommend a good implementation of this in Python? A: Found this via Google: http://muffinresearch.co.uk/archives/2008/05/27/titlecasepy-titlecase-in-python/
Third-party titlecase method in Python
The standard string title() method in Python is pretty naive and doesn't correctly handle converting even fairly simple words and phrases to title case (hyphenated words, phrases with quotes, phrases with prepositions, etc.). In Googling around, I found a few solutions in different languages to this problem. Can anyone recommend a good implementation of this in Python?
[ "Found this via Google: http://muffinresearch.co.uk/archives/2008/05/27/titlecasepy-titlecase-in-python/\n" ]
[ 2 ]
[]
[]
[ "capitalization", "python", "string" ]
stackoverflow_0002761160_capitalization_python_string.txt
Q: Python iterator question I have this list: names = ['john','Jonh','james','James','Jardel'] I want loop over the list and handle consecutive names with a case insensitive match in the same iteration. So in the first iteration I would do something with'john' and 'John' and I want the next iteration to start at 'james'. I can't think of a way to do this using Python's for loop, any suggestions? A: This would be one for itertools.groupby, which groups consecutive equal elements from a list or other iterable. you can specify a function to do the comparison, so that, in your case, the same name in different cases can still be counted as the same thing. for k, g in itertools.groupby(names, lambda s: s.lower()): # Example: in the first iteration: # k = "john" # g = an iterator over ["john", "John"] # Process them as you like A: names = ['john','John','james','James'] for name, capitalized_name in zip(names[::2], names[1::2]): print name, capitalized_name Note that you need an even amount of items for this to work properly. Or (maybe better; hard to tell with little context) use a set to filter the list to contain only unique names (note that this loses order): >>> names = ['john','John','james','James','Jardel'] >>> unique_names = set([x.lower() for x in names]) >>> for unique_name in unique_names: ... print unique_name ... jardel james john A: You could just use a while loop: i = 0 while i < len(names): # compare names[i] with names[i + 1] i = i + 2 # or + 1 if names not equal, for example Or are you looking for something a bit more involved? A: As you iterate thru the loop, you could try keeping track of the previous name in the list. At the same time, when you're going to store the names, you can make a call to lower() or capitalize() to make the formatting of each name consistent so that you can compare them easier. e.g. first = True prev= "" for name in names: if first: #First iteration prev = name.lower() #Need to get the first elem do_something_to(curr) first = False else: if prev == name.lower(): print "do nothing" else: do_something_to(curr) prev = name.lower() May not be the most efficient, but works. A: My $0.02: def byPairs(li): for i in xrange(1, len(li), 2): yield (li[i-1], li[i]) for a,b in byPairs(names): if a.lower()==b.lower(): doSomething(a,b) I'm not sure I understood the question exactly; what are you trying to accomplish?
Python iterator question
I have this list: names = ['john','Jonh','james','James','Jardel'] I want loop over the list and handle consecutive names with a case insensitive match in the same iteration. So in the first iteration I would do something with'john' and 'John' and I want the next iteration to start at 'james'. I can't think of a way to do this using Python's for loop, any suggestions?
[ "This would be one for itertools.groupby, which groups consecutive equal elements from a list or other iterable. you can specify a function to do the comparison, so that, in your case, the same name in different cases can still be counted as the same thing.\nfor k, g in itertools.groupby(names, lambda s: s.lower()):\n # Example: in the first iteration:\n # k = \"john\"\n # g = an iterator over [\"john\", \"John\"]\n # Process them as you like\n\n", "names = ['john','John','james','James']\nfor name, capitalized_name in zip(names[::2], names[1::2]):\n print name, capitalized_name\n\nNote that you need an even amount of items for this to work properly.\nOr (maybe better; hard to tell with little context) use a set to filter the list to contain only unique names (note that this loses order):\n>>> names = ['john','John','james','James','Jardel']\n>>> unique_names = set([x.lower() for x in names])\n>>> for unique_name in unique_names:\n... print unique_name\n... \njardel\njames\njohn\n\n", "You could just use a while loop:\ni = 0\nwhile i < len(names):\n # compare names[i] with names[i + 1]\n i = i + 2 # or + 1 if names not equal, for example\n\nOr are you looking for something a bit more involved?\n", "As you iterate thru the loop, you could try keeping track of the previous name in the list. At the same time, when you're going to store the names, you can make a call to lower() or capitalize() to make the formatting of each name consistent so that you can compare them easier.\ne.g.\nfirst = True\nprev= \"\"\nfor name in names:\n if first: #First iteration\n prev = name.lower() #Need to get the first elem\n do_something_to(curr)\n first = False\n else:\n if prev == name.lower():\n print \"do nothing\"\n else:\n do_something_to(curr)\n prev = name.lower()\n\nMay not be the most efficient, but works.\n", "My $0.02:\ndef byPairs(li):\n for i in xrange(1, len(li), 2):\n yield (li[i-1], li[i])\n\nfor a,b in byPairs(names):\n if a.lower()==b.lower():\n doSomething(a,b)\n\nI'm not sure I understood the question exactly; what are you trying to accomplish?\n" ]
[ 6, 2, 0, 0, 0 ]
[]
[]
[ "for_in_loop", "for_loop", "python" ]
stackoverflow_0002760183_for_in_loop_for_loop_python.txt
Q: python blocking sockets, send returns immediately I am writing a multithreaded socket application in Python using the socket module. the server listens for connections and when it gets one it spawns a thread for that socket. the server thread sends some data to the client. but the client is not yet ready to receive it. I thought this would have caused the server to wait until the client starts recv but instead returns immediately the client then calls recv which is blocking and no data is ever received. client socket constructor self.__clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__clientSocket.connect((server, port)) server socket constructor self.servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.servSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #self.servSock.settimeout(None) self.servSock.setblocking(1) self.servSock.bind((self.addr,self.port)) self.servSock.listen(5) listening accept thread try: (cs, address) = self.servSock.accept() except socket.timeout: return threadName = '\r\nClient %s:%s\r\n' % (cs, address) print threadName clientSocketHandler = ClientSocket() clientSocketHandler.setClientSocket(cs) self.clients.newThread(self.clientFunc, {clientSocketHandler : "1"}, threadName).start() server and clients send/rec methods from inside ClientSocket receivedData = self.__clientSocket.recv(1024*1024) self.__clientSocket.send(s) any ideas why send() is returning straight away? A: any ideas why send() is returning straight away? all send() does is fill the network buffer and return the ammount of bytes sent. if you want a send that blocks just recv an acknowledgement message from the client. A: The client doesn't have to be ready to receive data - data will queue up in the socket's receive buffer until you are ready to recv() it. Send returns instantly because the send buffer isn't full - if it was full, send() would block until there was room for the data you wanted to send. Most of the time you'll never fill it - hence what you are experiencing. On a side, you probably don't want a recv call with 1024*1024 in it - that's a little on the high side. A: Sorry about the delay i fixed the problem shortly after asking this question. @Lee thanks for your answer it pointed me in the right direction. the solution was to send a 4byte int specifying the size of the data to follow. the client would always receive these four bytes and then the size of the data. from commandClass import Command from commandActionClass import CommandAction import socket from time import * import struct class ClientSocket(): instance = None __connected = False __clientSocket = None @staticmethod def getInstance(): if ClientSocket.instance == None: ClientSocket.instance = ClientSocket() return ClientSocket.instance def __init__(self): self.__connected = False self.receivedData = '' self.bufSize = 4096 self.buffer = '' def connect(self, server, port): if self.isConnected(): raise Exception('Already connected.') self.__clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__clientSocket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) self.__clientSocket.connect((server, port)) self.__clientSocket.setblocking(1) self.__connected = True def disconnect(self): try: self.receivedData = '' self.buffer = '' self.__clientSocket.close() except Exception, e: print e finally: self.__connected = False def sendString(self,s): try: if (self.isConnected()): self.__clientSocket.send(s) except Exception, e: print e self.disconnect() def __pop(self, size): data = self.receivedData[:size] self.receivedData = self.receivedData[size:] return data def __recv(self,toRead): self.flush() while ((len(self.receivedData)<toRead)and(self.isConnected())): data = self.__clientSocket.recv(self.bufSize) if not data: self.disconnect() self.receivedData = self.receivedData + data return self.__pop(toRead) def __sendint(self, x): self.__sendall(struct.pack("i", x)) def __recvint(self): data = self.__recv(4) if not data: raise Exception('Expected to receive buffer size') return struct.unpack("i", data)[0] def flush(self): if len(self.buffer)>0: self.__clientSocket.sendall(self.buffer) self.buffer = '' def __sendall(self, s): self.buffer = self.buffer + s def send(self,s): try: if (not self.isConnected()): raise Exception('Socket is not connected') data = s.pickle() self.__sendint(len(data)) self.__sendall(data) except Exception, e: self.disconnect() raise e def sendEOC(self): self.send(Command(CommandAction.EOC, time()))#send our system time. can be used for ping def receive(self): if (not self.isConnected()): raise Exception('Socket Error. Not Connected') try: #first receive the size of packet buffsize = self.__recvint() #now receive the actual data data = self.__recv(buffsize) if not data: raise Exception('No data to receive') command = Command.unpickle(data) except Exception, e: self.disconnect() command = Command(CommandAction.Invalid, None) raise e #finally? return command def isConnected(self): return self.__connected def setClientSocket(self, clientSocket): self.__clientSocket = clientSocket self.__connected = True #assume its connected
python blocking sockets, send returns immediately
I am writing a multithreaded socket application in Python using the socket module. the server listens for connections and when it gets one it spawns a thread for that socket. the server thread sends some data to the client. but the client is not yet ready to receive it. I thought this would have caused the server to wait until the client starts recv but instead returns immediately the client then calls recv which is blocking and no data is ever received. client socket constructor self.__clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__clientSocket.connect((server, port)) server socket constructor self.servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.servSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #self.servSock.settimeout(None) self.servSock.setblocking(1) self.servSock.bind((self.addr,self.port)) self.servSock.listen(5) listening accept thread try: (cs, address) = self.servSock.accept() except socket.timeout: return threadName = '\r\nClient %s:%s\r\n' % (cs, address) print threadName clientSocketHandler = ClientSocket() clientSocketHandler.setClientSocket(cs) self.clients.newThread(self.clientFunc, {clientSocketHandler : "1"}, threadName).start() server and clients send/rec methods from inside ClientSocket receivedData = self.__clientSocket.recv(1024*1024) self.__clientSocket.send(s) any ideas why send() is returning straight away?
[ "\nany ideas why send() is returning straight away?\n\nall send() does is fill the network buffer and return the ammount of bytes sent.\nif you want a send that blocks just recv an acknowledgement message from the client. \n", "The client doesn't have to be ready to receive data - data will queue up in the socket's receive buffer until you are ready to recv() it. Send returns instantly because the send buffer isn't full - if it was full, send() would block until there was room for the data you wanted to send.\nMost of the time you'll never fill it - hence what you are experiencing. On a side, you probably don't want a recv call with 1024*1024 in it - that's a little on the high side.\n", "Sorry about the delay i fixed the problem shortly after asking this question. @Lee thanks for your answer it pointed me in the right direction.\nthe solution was to send a 4byte int specifying the size of the data to follow. the client would always receive these four bytes and then the size of the data.\nfrom commandClass import Command\nfrom commandActionClass import CommandAction\nimport socket\nfrom time import *\nimport struct\n\nclass ClientSocket():\n instance = None\n __connected = False\n __clientSocket = None\n\n @staticmethod\n def getInstance():\n if ClientSocket.instance == None:\n ClientSocket.instance = ClientSocket()\n return ClientSocket.instance\n\n def __init__(self):\n self.__connected = False\n self.receivedData = ''\n self.bufSize = 4096\n self.buffer = ''\n\n def connect(self, server, port):\n if self.isConnected():\n raise Exception('Already connected.')\n\n self.__clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.__clientSocket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)\n self.__clientSocket.connect((server, port))\n self.__clientSocket.setblocking(1)\n self.__connected = True\n\n def disconnect(self):\n try:\n self.receivedData = ''\n self.buffer = ''\n self.__clientSocket.close()\n except Exception, e:\n print e\n finally:\n self.__connected = False\n\n def sendString(self,s):\n try:\n if (self.isConnected()):\n self.__clientSocket.send(s)\n except Exception, e:\n print e\n self.disconnect()\n\n def __pop(self, size):\n data = self.receivedData[:size]\n self.receivedData = self.receivedData[size:]\n return data\n\n def __recv(self,toRead):\n self.flush()\n while ((len(self.receivedData)<toRead)and(self.isConnected())):\n data = self.__clientSocket.recv(self.bufSize)\n if not data:\n self.disconnect()\n self.receivedData = self.receivedData + data\n\n return self.__pop(toRead)\n\n def __sendint(self, x):\n self.__sendall(struct.pack(\"i\", x))\n\n def __recvint(self):\n data = self.__recv(4)\n if not data:\n raise Exception('Expected to receive buffer size')\n return struct.unpack(\"i\", data)[0]\n\n def flush(self):\n if len(self.buffer)>0:\n self.__clientSocket.sendall(self.buffer)\n self.buffer = ''\n\n def __sendall(self, s):\n self.buffer = self.buffer + s\n\n def send(self,s):\n try:\n if (not self.isConnected()):\n raise Exception('Socket is not connected')\n data = s.pickle()\n self.__sendint(len(data))\n self.__sendall(data)\n except Exception, e:\n self.disconnect()\n raise e\n\n def sendEOC(self):\n self.send(Command(CommandAction.EOC, time()))#send our system time. can be used for ping\n\n def receive(self):\n if (not self.isConnected()):\n raise Exception('Socket Error. Not Connected')\n try:\n #first receive the size of packet\n buffsize = self.__recvint()\n #now receive the actual data\n data = self.__recv(buffsize)\n\n if not data:\n raise Exception('No data to receive')\n\n command = Command.unpickle(data)\n except Exception, e:\n self.disconnect()\n command = Command(CommandAction.Invalid, None)\n raise e\n #finally?\n return command\n\n def isConnected(self):\n return self.__connected\n\n def setClientSocket(self, clientSocket):\n self.__clientSocket = clientSocket\n self.__connected = True #assume its connected\n\n" ]
[ 4, 1, 1 ]
[]
[]
[ "blocking", "multithreading", "python", "send", "sockets" ]
stackoverflow_0002432814_blocking_multithreading_python_send_sockets.txt
Q: RSA encrypted data block size how do you store an rsa encrypted data block? the output might be significantly greater than the original input data block size, and i dont think people waste memory by padding bucket loads of 0s in front of each data block. besides, how would they be removed? or is each block stored on new lines within the file? if that is the case, how would you tell the difference between legitimate new line and a '\n' char written into the file? what am i missing? im writing the "write to file" part in python, so maybe its one of the differences between: open(file,'w') open(file,'w+b') open(file,'wb') that i dont know. or is it something else? A: You are missing that they do indeed pad with bucket loads of random bits. Some padding schemes use the first few bytes to describe how many bytes are padding; others have "everything until the first 0x00" is padding.
RSA encrypted data block size
how do you store an rsa encrypted data block? the output might be significantly greater than the original input data block size, and i dont think people waste memory by padding bucket loads of 0s in front of each data block. besides, how would they be removed? or is each block stored on new lines within the file? if that is the case, how would you tell the difference between legitimate new line and a '\n' char written into the file? what am i missing? im writing the "write to file" part in python, so maybe its one of the differences between: open(file,'w') open(file,'w+b') open(file,'wb') that i dont know. or is it something else?
[ "You are missing that they do indeed pad with bucket loads of random bits.\nSome padding schemes use the first few bytes to describe how many bytes are padding; others have \"everything until the first 0x00\" is padding.\n" ]
[ 1 ]
[]
[]
[ "cryptography", "python", "rsa" ]
stackoverflow_0002761529_cryptography_python_rsa.txt
Q: Need a workaround to filter on related model and aggregated fields in Django I opened a ticket for this problem. In a nutshell here is my model: class Plan(models.Model): cap = models.IntegerField() class Phone(models.Model): plan = models.ForeignKey(Plan, related_name='phones') class Call(models.Model): phone = models.ForeignKey(Phone, related_name='calls') cost = models.IntegerField() I want to run a query like this one: Phone.objects.annotate(total_cost=Sum('calls__cost')).filter(total_cost__gte=0.5*F('plan__cap')) Unfortunately Django generates bad SQL: SELECT "app_phone"."id", "app_phone"."plan_id", SUM("app_call"."cost") AS "total_cost" FROM "app_phone" INNER JOIN "app_plan" ON ("app_phone"."plan_id" = "app_plan"."id") LEFT OUTER JOIN "app_call" ON ("app_phone"."id" = "app_call"."phone_id") GROUP BY "app_phone"."id", "app_phone"."plan_id" HAVING SUM("app_call"."cost") >= 0.5 * "app_plan"."cap" and errors with: ProgrammingError: column "app_plan.cap" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...."plan_id" HAVING SUM("app_call"."cost") >= 0.5 * "app_plan".... Is there any workaround apart from running raw SQL? A: When aggregating, SQL requires any value in a field either be unique within a group, or that the field be wrapped in an aggregation function which ensures that only one value will come out for each group. The problem here is that "app_plan.cap" could have many different values for each combination of "app_phone.id" and "app_phone.plan_id", so you need to tell the DB how to treat those. So, valid SQL for your result is one of two different possibilities, depending on the result you want. First, you could include app_plan.cap in the GROUP BY function, so that any distinct combination of (app_phone.id, app_phone.plan_id, app_plan.cap) will be a different group: SELECT "app_phone"."id", "app_phone"."plan_id", "app_plan"."cap", SUM("app_call"."cost") AS "total_cost" FROM "app_phone" INNER JOIN "app_plan" ON ("app_phone"."plan_id" = "app_plan"."id") LEFT OUTER JOIN "app_call" ON ("app_phone"."id" = "app_call"."phone_id") GROUP BY "app_phone"."id", "app_phone"."plan_id", "app_plan"."cap" HAVING SUM("app_call"."cost") >= 0.5 * "app_plan"."cap" The trick is to get the extra value into the "GROUP BY" call. We can weasel our way into this by abusing "extra", though this hard-codes the table name for "app_plan" which is unideal -- you could do it programmatically with the Plan class instead if you wanted: Phone.objects.extra({ "plan_cap": "app_plan.cap" }).annotate( total_cost=Sum('calls__cost') ).filter(total_cost__gte=0.5*F('plan__cap')) Alternatively, you could wrap app_plan.cap in an aggregation function, turning it into a unique value. Aggregation functions vary by DB provider, but might include things like AVG, MAX, MIN, etc. SELECT "app_phone"."id", "app_phone"."plan_id", SUM("app_call"."cost") AS "total_cost", AVG("app_plan"."cap") AS "avg_cap", FROM "app_phone" INNER JOIN "app_plan" ON ("app_phone"."plan_id" = "app_plan"."id") LEFT OUTER JOIN "app_call" ON ("app_phone"."id" = "app_call"."phone_id") GROUP BY "app_phone"."id", "app_phone"."plan_id" HAVING SUM("app_call"."cost") >= 0.5 * AVG("app_plan"."cap") You could get this result in Django using the following: Phone.objects.annotate( total_cost=Sum('calls__cost'), avg_cap=Avg('plan__cap') ).filter(total_cost__gte=0.5 * F("avg_cap")) You may want to consider updating the bug report you left with a clearer specification of the result you expect -- for example, the valid SQL you're after.
Need a workaround to filter on related model and aggregated fields in Django
I opened a ticket for this problem. In a nutshell here is my model: class Plan(models.Model): cap = models.IntegerField() class Phone(models.Model): plan = models.ForeignKey(Plan, related_name='phones') class Call(models.Model): phone = models.ForeignKey(Phone, related_name='calls') cost = models.IntegerField() I want to run a query like this one: Phone.objects.annotate(total_cost=Sum('calls__cost')).filter(total_cost__gte=0.5*F('plan__cap')) Unfortunately Django generates bad SQL: SELECT "app_phone"."id", "app_phone"."plan_id", SUM("app_call"."cost") AS "total_cost" FROM "app_phone" INNER JOIN "app_plan" ON ("app_phone"."plan_id" = "app_plan"."id") LEFT OUTER JOIN "app_call" ON ("app_phone"."id" = "app_call"."phone_id") GROUP BY "app_phone"."id", "app_phone"."plan_id" HAVING SUM("app_call"."cost") >= 0.5 * "app_plan"."cap" and errors with: ProgrammingError: column "app_plan.cap" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...."plan_id" HAVING SUM("app_call"."cost") >= 0.5 * "app_plan".... Is there any workaround apart from running raw SQL?
[ "When aggregating, SQL requires any value in a field either be unique within a group, or that the field be wrapped in an aggregation function which ensures that only one value will come out for each group. The problem here is that \"app_plan.cap\" could have many different values for each combination of \"app_phone.id\" and \"app_phone.plan_id\", so you need to tell the DB how to treat those.\nSo, valid SQL for your result is one of two different possibilities, depending on the result you want. First, you could include app_plan.cap in the GROUP BY function, so that any distinct combination of (app_phone.id, app_phone.plan_id, app_plan.cap) will be a different group:\nSELECT \"app_phone\".\"id\", \"app_phone\".\"plan_id\", \"app_plan\".\"cap\",\nSUM(\"app_call\".\"cost\") AS \"total_cost\"\nFROM \"app_phone\"\nINNER JOIN \"app_plan\" ON (\"app_phone\".\"plan_id\" = \"app_plan\".\"id\")\nLEFT OUTER JOIN \"app_call\" ON (\"app_phone\".\"id\" = \"app_call\".\"phone_id\")\nGROUP BY \"app_phone\".\"id\", \"app_phone\".\"plan_id\", \"app_plan\".\"cap\"\nHAVING SUM(\"app_call\".\"cost\") >= 0.5 * \"app_plan\".\"cap\"\n\nThe trick is to get the extra value into the \"GROUP BY\" call. We can weasel our way into this by abusing \"extra\", though this hard-codes the table name for \"app_plan\" which is unideal -- you could do it programmatically with the Plan class instead if you wanted:\nPhone.objects.extra({\n \"plan_cap\": \"app_plan.cap\"\n}).annotate(\n total_cost=Sum('calls__cost')\n).filter(total_cost__gte=0.5*F('plan__cap'))\n\nAlternatively, you could wrap app_plan.cap in an aggregation function, turning it into a unique value. Aggregation functions vary by DB provider, but might include things like AVG, MAX, MIN, etc.\nSELECT \"app_phone\".\"id\", \"app_phone\".\"plan_id\",\nSUM(\"app_call\".\"cost\") AS \"total_cost\",\nAVG(\"app_plan\".\"cap\") AS \"avg_cap\",\nFROM \"app_phone\"\nINNER JOIN \"app_plan\" ON (\"app_phone\".\"plan_id\" = \"app_plan\".\"id\")\nLEFT OUTER JOIN \"app_call\" ON (\"app_phone\".\"id\" = \"app_call\".\"phone_id\")\nGROUP BY \"app_phone\".\"id\", \"app_phone\".\"plan_id\"\nHAVING SUM(\"app_call\".\"cost\") >= 0.5 * AVG(\"app_plan\".\"cap\")\n\nYou could get this result in Django using the following:\nPhone.objects.annotate(\n total_cost=Sum('calls__cost'), \n avg_cap=Avg('plan__cap')\n).filter(total_cost__gte=0.5 * F(\"avg_cap\"))\n\nYou may want to consider updating the bug report you left with a clearer specification of the result you expect -- for example, the valid SQL you're after.\n" ]
[ 1 ]
[]
[]
[ "django", "orm", "python", "sql" ]
stackoverflow_0002755382_django_orm_python_sql.txt
Q: Import module stored in a cStringIO data structure vs. physical disk file Is there a way to import a Python module stored in a cStringIO data structure vs. physical disk file? It looks like "imp.load_compiled(name, pathname[, file])" is what I need, but the description of this method (and similar methods) has the following disclaimer: Quote: "The file argument is the byte-compiled code file, open for reading in binary mode, from the beginning. It must currently be a real file object, not a user-defined class emulating a file." [1] I tried using a cStringIO object vs. a real file object, but the help documentation is correct - only a real file object can be used. Any ideas on why these modules would impose such a restriction or is this just an historical artifact? Are there any techniques I can use to avoid this physical file requirement? Thanks, Malcolm [1] http://docs.python.org/library/imp.html#imp.load_module A: Something like this perhaps? import types import sys src = """ def hello(who): print 'hello', who """ def module_from_text(modulename, src): if modulename in sys.modules: module = sys.modules[modulename] else: module = sys.modules[modulename] = types.ModuleType(modulename) exec compile(src, '<no-file>', 'exec') in module.__dict__ return module module_from_text('flup', src) import flup flup.hello('world') Which prints: hello world EDIT: Evaluating code in this way treads nearish the realm of writing custom importers. It may be useful to look at PEP 302, and Doug Hellmann's PyMOTW: Modules and Imports.
Import module stored in a cStringIO data structure vs. physical disk file
Is there a way to import a Python module stored in a cStringIO data structure vs. physical disk file? It looks like "imp.load_compiled(name, pathname[, file])" is what I need, but the description of this method (and similar methods) has the following disclaimer: Quote: "The file argument is the byte-compiled code file, open for reading in binary mode, from the beginning. It must currently be a real file object, not a user-defined class emulating a file." [1] I tried using a cStringIO object vs. a real file object, but the help documentation is correct - only a real file object can be used. Any ideas on why these modules would impose such a restriction or is this just an historical artifact? Are there any techniques I can use to avoid this physical file requirement? Thanks, Malcolm [1] http://docs.python.org/library/imp.html#imp.load_module
[ "Something like this perhaps?\nimport types\nimport sys\n\nsrc = \"\"\"\ndef hello(who):\n print 'hello', who\n\"\"\"\n\ndef module_from_text(modulename, src):\n if modulename in sys.modules:\n module = sys.modules[modulename]\n else:\n module = sys.modules[modulename] = types.ModuleType(modulename)\n exec compile(src, '<no-file>', 'exec') in module.__dict__\n return module\n\nmodule_from_text('flup', src)\nimport flup\nflup.hello('world')\n\nWhich prints:\nhello world\n\nEDIT:\nEvaluating code in this way treads nearish the realm of writing custom importers. It may be useful to look at PEP 302, and Doug Hellmann's PyMOTW: Modules and Imports. \n" ]
[ 3 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0002761490_import_module_python.txt
Q: changing .emacs to use IronPython.exe and using code completion for IronPython modules? I configured my Emacs for code completion and other help using this link (from another question here on SO). I am a complete newbie to emacs. Can anyone tell me what should I change so it (rope, ropemacs, pymacs, yasnippet etc) picks up symbols of IronPython modules for code completion and snippets. Also I want to map: C-x RET - to invoke IronPython.exe and not Python.exe (any clue on how to do that) PS I am using Emacs with Cygwin on XP machine A: The variable python-command contains the path of the python interpreter to be run. By default, this is usually just set to "python", which runs the first python in your path. Try changing it to point directly to the IronPython exe file: (setq python-command "C:/Program Files/IronPython 2.6/ipy.exe")
changing .emacs to use IronPython.exe and using code completion for IronPython modules?
I configured my Emacs for code completion and other help using this link (from another question here on SO). I am a complete newbie to emacs. Can anyone tell me what should I change so it (rope, ropemacs, pymacs, yasnippet etc) picks up symbols of IronPython modules for code completion and snippets. Also I want to map: C-x RET - to invoke IronPython.exe and not Python.exe (any clue on how to do that) PS I am using Emacs with Cygwin on XP machine
[ "The variable python-command contains the path of the python interpreter to be run. By default, this is usually just set to \"python\", which runs the first python in your path.\nTry changing it to point directly to the IronPython exe file:\n(setq python-command \"C:/Program Files/IronPython 2.6/ipy.exe\")\n\n" ]
[ 1 ]
[]
[]
[ "cygwin", "emacs", "ironpython", "python" ]
stackoverflow_0002752209_cygwin_emacs_ironpython_python.txt
Q: Set language code inside a view in django How do I set the language code inside a view (in django)? I'm sending a HttpResponse that contains a python-date.strftime("%A"). %A is the day (e.g. 'Monday'), but I want to get the day in Swedish instead of English. A: The documentation for locale suggests that fiddling with the locale too much is a bad idea: It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored. If it's okay for your entire application to use the Swedish locale, you should just set it once and be on your way. On the other hand if you only want that page to use the Swedish locale or you need to be able to switch on a per-request basis, locale and consequently datetime.strftime aren't the way to go. The reason for this limitation seems to be that python calls into the C runtime for strftime which doesn't play well with a frequently changing locale. Provided your needs are relatively limited, your best bet is to write your own function that formats dates the way you want them without leaning on strftime for any of the locale specific specifiers {%a, %A, %b, %B, %c, %p}. This will probably entail building a list of locale specific month/day names, but that's not that big a deal. Here's a really basic implementation that lets you switch between English and French (I don't have the Swedish locale installed ;) and handles %a and %b and calls down to datetime.strftime for everything else: import datetime def wrap_strftime(d, fmt, locale = "en"): """ Preprocess a strftime format so we can pass in the locale. >>> dt = datetime.datetime(2010, 1, 1) >>> wrap_strftime(dt, "%a %b %d, %Y") 'Fri Jan 01, 2010' >>> wrap_strftime(dt, "%a %b %d, %Y", "fr") 'Ven jan 01, 2010' """ data = { "fr": { "%a": ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'], "%b": [ 'jan', 'f\xc3\xa9v', 'mar', 'avr', 'mai', 'jui', 'jul', 'ao\xc3\xbb', 'sep', 'oct', 'nov', 'd\xc3\xa9c' ], }, "en": { "%a": ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], "%b": [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], }, } getters = { "%a": lambda dt: dt.weekday(), "%b": lambda dt: dt.month - 1, } for pattern in data[locale]: getter = getters[pattern] fmt = fmt.replace(pattern, data[locale][pattern][getter(d)]) return d.strftime(fmt) if __name__ == "__main__": import doctest doctest.testmod() You probably also want to check out Babel which will be much more robust than trying to wrap strftime and lets you do things like: >>> from babel.dates import format_datetime >>> import datetime >>> format_datetime(datetime.datetime.now(), "EEE dd MMM yyyy", locale="fr") u'lun. 03 mai 2010'
Set language code inside a view in django
How do I set the language code inside a view (in django)? I'm sending a HttpResponse that contains a python-date.strftime("%A"). %A is the day (e.g. 'Monday'), but I want to get the day in Swedish instead of English.
[ "The documentation for locale suggests that fiddling with the locale too much is a bad idea:\n\nIt is generally a bad idea to call\n setlocale() in some library routine,\n since as a side effect it affects the\n entire program. Saving and restoring\n it is almost as bad: it is expensive\n and affects other threads that happen\n to run before the settings have been\n restored.\n\nIf it's okay for your entire application to use the Swedish locale, you should just set it once and be on your way. On the other hand if you only want that page to use the Swedish locale or you need to be able to switch on a per-request basis, locale and consequently datetime.strftime aren't the way to go. The reason for this limitation seems to be that python calls into the C runtime for strftime which doesn't play well with a frequently changing locale.\nProvided your needs are relatively limited, your best bet is to write your own function that formats dates the way you want them without leaning on strftime for any of the locale specific specifiers {%a, %A, %b, %B, %c, %p}. This will probably entail building a list of locale specific month/day names, but that's not that big a deal. \nHere's a really basic implementation that lets you switch between English and French (I don't have the Swedish locale installed ;) and handles %a and %b and calls down to datetime.strftime for everything else:\nimport datetime\n\ndef wrap_strftime(d, fmt, locale = \"en\"):\n \"\"\"\n Preprocess a strftime format so we can pass in the locale.\n\n >>> dt = datetime.datetime(2010, 1, 1)\n >>> wrap_strftime(dt, \"%a %b %d, %Y\")\n 'Fri Jan 01, 2010'\n >>> wrap_strftime(dt, \"%a %b %d, %Y\", \"fr\")\n 'Ven jan 01, 2010'\n \"\"\"\n\n data = {\n \"fr\": {\n \"%a\": ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'],\n \"%b\": [\n 'jan', 'f\\xc3\\xa9v', 'mar', 'avr', 'mai', 'jui',\n 'jul', 'ao\\xc3\\xbb', 'sep', 'oct', 'nov', 'd\\xc3\\xa9c'\n ],\n },\n \"en\": {\n \"%a\": ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],\n \"%b\": [\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'\n ],\n },\n }\n\n getters = {\n \"%a\": lambda dt: dt.weekday(),\n \"%b\": lambda dt: dt.month - 1,\n }\n\n\n for pattern in data[locale]:\n getter = getters[pattern]\n fmt = fmt.replace(pattern, data[locale][pattern][getter(d)])\n\n return d.strftime(fmt)\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\nYou probably also want to check out Babel which will be much more robust than trying to wrap strftime and lets you do things like:\n>>> from babel.dates import format_datetime\n>>> import datetime\n>>> format_datetime(datetime.datetime.now(), \"EEE dd MMM yyyy\", locale=\"fr\")\nu'lun. 03 mai 2010'\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002760783_django_python.txt
Q: Splitting a filename into words and numbers in Python The following code splits a string into a list of words but does not include numbers: txt="there_once was,a-monkey.called phillip?09.txt" sep=re.compile(r"[\s\.,-_\?]+") sep.split(txt) ['there', 'once', 'was', 'a', 'monkey', 'called', 'phillip', 'txt'] This code gives me words and numbers but still includes "_" as a valid character: re.findall(r"\w+|\d+",txt) ['there_once', 'was', 'a', 'monkey', 'called', 'phillip', '09', 'txt'] What do I need to alter in either piece of code to end up with the desired result of: ['there', 'once', 'was', 'a', 'monkey', 'called', 'phillip', '09', 'txt'] A: Here's a quick way that should do it: re.findall(r"[a-zA-Z0-9]+",txt) Here's another: re.split(r"[\s\.,\-_\?]+",txt) (you just needed to escape the hyphen because it has a special meaning in a character class) A: For the example case, sep = re.compile(r"[^a-zA-Z0-9]+") sea.split(txt) should work. To separate numbers from words, try re.findall(r"[a-zA-Z]+|\d+", txt)
Splitting a filename into words and numbers in Python
The following code splits a string into a list of words but does not include numbers: txt="there_once was,a-monkey.called phillip?09.txt" sep=re.compile(r"[\s\.,-_\?]+") sep.split(txt) ['there', 'once', 'was', 'a', 'monkey', 'called', 'phillip', 'txt'] This code gives me words and numbers but still includes "_" as a valid character: re.findall(r"\w+|\d+",txt) ['there_once', 'was', 'a', 'monkey', 'called', 'phillip', '09', 'txt'] What do I need to alter in either piece of code to end up with the desired result of: ['there', 'once', 'was', 'a', 'monkey', 'called', 'phillip', '09', 'txt']
[ "Here's a quick way that should do it:\nre.findall(r\"[a-zA-Z0-9]+\",txt)\n\nHere's another:\nre.split(r\"[\\s\\.,\\-_\\?]+\",txt)\n\n(you just needed to escape the hyphen because it has a special meaning in a character class)\n", "For the example case,\nsep = re.compile(r\"[^a-zA-Z0-9]+\")\nsea.split(txt)\n\nshould work. To separate numbers from words, try\nre.findall(r\"[a-zA-Z]+|\\d+\", txt)\n\n" ]
[ 2, 2 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0002762292_python_regex_string.txt
Q: How should I check that a given argument is a datetime.date object? I'm currently using an assert statement with isinstance. Because datetime is a subclass of date, I also need to check that it isn't an instance of datetime. Surely there's a better way? from datetime import date, datetime def some_func(arg): assert isinstance(arg, date) and not isinstance(arg, datetime),\ 'arg must be a datetime.date object' # ... A: I don't understand your motivation for rejecting instances of subclasses (given that by definition they support all the behavior the superclass supports!), but if that's really what you insist on doing, then: if type(arg) is not datetime.date: raise TypeError('arg must be a datetime.date, not a %s' % type(arg)) Don't use assert except for sanity check during development (it gets turned to a no-op when you run with python -o), and don't raise the wrong kind of exception (such as, an AssertionError when a TypeError is clearly what you mean here). Using isinstance and then excluding one specific subclass is not a sound way to get a rigidly specified exact type with subclasses excluded: after all, the user might perfectly well subclass datetime.date and add whatever it is you're so keep to avoid by rejecting instances of datetime.datetime specifically!-) A: If your problem is that the graph goes wonky because it is using fractions of a day, you can test for that in other ways e.g. hasattr(arg, 'hour') distinguishes between a datetime instance and a date instance. A: The Python way is not to check it, just go ahead and let your code do what it needs to do, and if the object doesn't have a required method or something, the code will fail with an exception at the point where that method will be called. This is called duck typing and it is part of what makes Python so flexible. Now, if you really can't accept a datetime.datetime object... well, why can't you? A datetime can do anything a date can do, so I can't imagine what reason you'd have for disallowing a datetime, or indeed any subclass of date. If you really really have a good reason for doing this (I guess maybe as a debugging thing, but even then, I don't get it...): assert type(arg) == datetime.date
How should I check that a given argument is a datetime.date object?
I'm currently using an assert statement with isinstance. Because datetime is a subclass of date, I also need to check that it isn't an instance of datetime. Surely there's a better way? from datetime import date, datetime def some_func(arg): assert isinstance(arg, date) and not isinstance(arg, datetime),\ 'arg must be a datetime.date object' # ...
[ "I don't understand your motivation for rejecting instances of subclasses (given that by definition they support all the behavior the superclass supports!), but if that's really what you insist on doing, then:\nif type(arg) is not datetime.date:\n raise TypeError('arg must be a datetime.date, not a %s' % type(arg))\n\nDon't use assert except for sanity check during development (it gets turned to a no-op when you run with python -o), and don't raise the wrong kind of exception (such as, an AssertionError when a TypeError is clearly what you mean here).\nUsing isinstance and then excluding one specific subclass is not a sound way to get a rigidly specified exact type with subclasses excluded: after all, the user might perfectly well subclass datetime.date and add whatever it is you're so keep to avoid by rejecting instances of datetime.datetime specifically!-)\n", "If your problem is that the graph goes wonky because it is using fractions of a day, you can test for that in other ways e.g. hasattr(arg, 'hour') distinguishes between a datetime instance and a date instance.\n", "The Python way is not to check it, just go ahead and let your code do what it needs to do, and if the object doesn't have a required method or something, the code will fail with an exception at the point where that method will be called. This is called duck typing and it is part of what makes Python so flexible.\nNow, if you really can't accept a datetime.datetime object... well, why can't you? A datetime can do anything a date can do, so I can't imagine what reason you'd have for disallowing a datetime, or indeed any subclass of date.\nIf you really really have a good reason for doing this (I guess maybe as a debugging thing, but even then, I don't get it...):\nassert type(arg) == datetime.date\n\n" ]
[ 33, 5, 4 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002762265_datetime_python.txt
Q: Installing Mercurial on Mac OS X 10.6 Snow Leopard Installing Mercurial on Mac OS X 10.6 Snow Leopard I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following: cd ~/src curl -O https://www.mercurial-scm.org/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install This installs the site-packages files for Mercurial in /usr/local/lib/python2.6/site-packages/. I know that installing Mercurial from the Mac Disk Image will install the files into /Library/Python/2.6/site-packages/, which is the site-packages directory for the Mac OS X default Python install. I have Python 2.6.2+ installed as a Framework with its site-packages directory in: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages With Mercurial installed this way, I have to issue: PYTHONPATH=/usr/local/lib/python2.6/site-packages:"${PYTHONPATH}" in order to get Mercurial to work. Questions How can I install Mercurial from source with the site-packages in a different directory? Is there an advantage or disadvantage to having the site-packages in the current location? Would it be better in one of the Python site-package directories that already exist? Do I need to be concerned about virtualenv working correctly since I have modified PYTHONPATH (or any other conflicts for that matter)? Reasons for Installing from Source Dan Benjamin of Hivelogic provides the benefits of and instructions for installing Mercurial from source in his article Installing Mercurial on Snow Leopard. A: Why need to use macports? python easy_install is the easiest way and error free: easy_install -U mercurial It's just a simple gold bullet, all the time. A: Especially since you have Python 2.6 available you can do something like python setup.py install --user, which will install Mercurial with ~/.local as prefix. You don't have to change the PYTHONPATH for this but only add ~/.local/bin to your PATH. Regarding advantages and disadvantages: That all depends on what your PYTHONPATH in general looks like since modifying it will naturally modify the load order of packages (which becomes relevant if you have one version of Mercurial installed with one prefix and another with a different prefix). In general, I try to put all custom packages into a certain site-packages folder (say /usr/local/lib/python2.6/site-packages). Again: If you are the only person who will use those libs, the --user flag provided by Python 2.6's distutils makes something like this pretty easy (with adding ~/.local to the default search path for modules). virtualenv should work just fine as long you your PYTHONPATH is used consistently. A: Install mercurial - or any Python package in general - into your user home directory. Thus you can access them from any Python (of same version) or any virtualenv. See PEP 370 for details. $ cd mercurial-x.y.z/ $ python2.6 setup.py install --user $ ~/.local/bin/hg ... But why do you want to build mercurial manually? I use macports. $ sudo port install mercurial $ which hg /opt/local/bin/hg Update: Nowadays, I simply use PyPM to install mercurial into ~/.local/bin/hg. A: as suggested by Sridhar, macports works fine on multiple architecture and versions of MacOsX + allows updates and more: $ port variants mercurial mercurial has the variants: bash_completion: Completion support for bash zsh_completion: Install mercurial zsh completion file $ so that you may use: $ sudo port install mercurial +bash_completion ---> Computing dependencies for mercurial ---> Fetching mercurial ---> Attempting to fetch mercurial-1.3.1.tar.gz from http://arn.se.distfiles.macports.org/python ---> Attempting to fetch mercurial-1.3.1.tar.gz from http://www.selenic.com/mercurial/release/ ---> Verifying checksum(s) for mercurial ---> Extracting mercurial ---> Configuring mercurial ---> Building mercurial ---> Staging mercurial into destroot ---> Installing mercurial @1.3.1_0+bash_completion ---> Activating mercurial @1.3.1_0+bash_completion ---> Cleaning mercurial $ A: All those answers look complicated to the average mac OS X users, because they are specific to other install platforms. As of now the Mercurial website offers an installer package (compressed as a zip file).
Installing Mercurial on Mac OS X 10.6 Snow Leopard
Installing Mercurial on Mac OS X 10.6 Snow Leopard I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following: cd ~/src curl -O https://www.mercurial-scm.org/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install This installs the site-packages files for Mercurial in /usr/local/lib/python2.6/site-packages/. I know that installing Mercurial from the Mac Disk Image will install the files into /Library/Python/2.6/site-packages/, which is the site-packages directory for the Mac OS X default Python install. I have Python 2.6.2+ installed as a Framework with its site-packages directory in: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages With Mercurial installed this way, I have to issue: PYTHONPATH=/usr/local/lib/python2.6/site-packages:"${PYTHONPATH}" in order to get Mercurial to work. Questions How can I install Mercurial from source with the site-packages in a different directory? Is there an advantage or disadvantage to having the site-packages in the current location? Would it be better in one of the Python site-package directories that already exist? Do I need to be concerned about virtualenv working correctly since I have modified PYTHONPATH (or any other conflicts for that matter)? Reasons for Installing from Source Dan Benjamin of Hivelogic provides the benefits of and instructions for installing Mercurial from source in his article Installing Mercurial on Snow Leopard.
[ "Why need to use macports? python easy_install is the easiest way and error free:\neasy_install -U mercurial\n\nIt's just a simple gold bullet, all the time.\n", "Especially since you have Python 2.6 available you can do something like python setup.py install --user, which will install Mercurial with ~/.local as prefix. You don't have to change the PYTHONPATH for this but only add ~/.local/bin to your PATH.\nRegarding advantages and disadvantages: That all depends on what your PYTHONPATH in general looks like since modifying it will naturally modify the load order of packages (which becomes relevant if you have one version of Mercurial installed with one prefix and another with a different prefix). In general, I try to put all custom packages into a certain site-packages folder (say /usr/local/lib/python2.6/site-packages). Again: If you are the only person who will use those libs, the --user flag provided by Python 2.6's distutils makes something like this pretty easy (with adding ~/.local to the default search path for modules).\nvirtualenv should work just fine as long you your PYTHONPATH is used consistently.\n", "Install mercurial - or any Python package in general - into your user home directory. Thus you can access them from any Python (of same version) or any virtualenv. See PEP 370 for details.\n$ cd mercurial-x.y.z/\n$ python2.6 setup.py install --user\n$ ~/.local/bin/hg\n...\n\nBut why do you want to build mercurial manually? I use macports.\n$ sudo port install mercurial\n$ which hg\n/opt/local/bin/hg\n\nUpdate: Nowadays, I simply use PyPM to install mercurial into ~/.local/bin/hg.\n", "as suggested by Sridhar, macports works fine on multiple architecture and versions of MacOsX + allows updates and more:\n$ port variants mercurial\nmercurial has the variants:\n bash_completion: Completion support for bash\n zsh_completion: Install mercurial zsh completion file\n$\n\nso that you may use:\n$ sudo port install mercurial +bash_completion\n---> Computing dependencies for mercurial\n---> Fetching mercurial\n---> Attempting to fetch mercurial-1.3.1.tar.gz from http://arn.se.distfiles.macports.org/python\n---> Attempting to fetch mercurial-1.3.1.tar.gz from http://www.selenic.com/mercurial/release/\n---> Verifying checksum(s) for mercurial\n---> Extracting mercurial\n---> Configuring mercurial\n---> Building mercurial\n---> Staging mercurial into destroot\n---> Installing mercurial @1.3.1_0+bash_completion\n---> Activating mercurial @1.3.1_0+bash_completion\n---> Cleaning mercurial\n$\n\n", "All those answers look complicated to the average mac OS X users, because they are specific to other install platforms. As of now the Mercurial website offers an installer package (compressed as a zip file).\n" ]
[ 13, 8, 8, 5, 1 ]
[]
[]
[ "macos", "mercurial", "osx_snow_leopard", "python" ]
stackoverflow_0001461374_macos_mercurial_osx_snow_leopard_python.txt
Q: how can i randomly print an element from a list in python So far i have this, which prints out every word in my list, but i am trying to print only one word at random. Any suggestions? def main(): # open a file wordsf = open('words.txt', 'r') word=random.choice('wordsf') words_count=0 for line in wordsf: word= line.rstrip('\n') print(word) words_count+=1 # close the file wordsf.close() A: Try: print random.choice([x.rstrip() for x in open("words.txt")]) Note that this strips the '\n' from every line before choosing a random one; a better solution is left as an exercise for the reader. A: To print one random word per line, your loop could be: for line in wordsf: word = random.choice(line.split()) print(word) If there are lines with nothing but whitespace, you also need to skip those: for line in wordsf: if line.isspace(): continue word = random.choice(line.split()) print(word) The counting part you have seems to be correct, but unrelated to your question. Edit: I see you meant something different in your Q (as other A's also intepreted): you want to choose a random line from the file, not a random word from each lines. That being the case, the other A's are correct, but they take O(N) auxiliary memory for a file of N lines. There's a nice algorithm due to Knuth to pick a random sample from a stream without knowing in advance how many items it has (unfortunately it requires generating N random numbers, so it's slower than the simpler one if you have enough memory for the latter... but it's still interesting to consider!-)...: n = 0 word = None for line in wordsf: n += 1 if random.randrange(n) == 0: word = line print(word.strip()) Basically, at each line n, we're picking it to replace the previous one (if any) with a probability of 1.0/n -- so the first time probability 1 (certainty), the second time probability 0.5, and so on. I'm doing the stripping only at the end as it would be a waste of effort to strip temporary choices that are later replaced; and I'm avoiding the division and floating point hassles by generating a random number with uniform probability between 0 and n-1 included (so the probability of that random number being 0 is 1/n) -- minor issues, but since they don't make the code any less clear, we might as well take care of them;-). A: import random def main(): wordsf = open('words.txt', 'r') words = [line.rstrip('\n') for line in wordsf] wordsf.close() random_number = random.randint(0, len(words)-1) random_word = words[random_number] print random_word This works well, but if the file wordsf is too huge, then I think you'll start to encounter memory issues, but I think this should do fine for most cases Hope this helps.
how can i randomly print an element from a list in python
So far i have this, which prints out every word in my list, but i am trying to print only one word at random. Any suggestions? def main(): # open a file wordsf = open('words.txt', 'r') word=random.choice('wordsf') words_count=0 for line in wordsf: word= line.rstrip('\n') print(word) words_count+=1 # close the file wordsf.close()
[ "Try:\nprint random.choice([x.rstrip() for x in open(\"words.txt\")])\n\nNote that this strips the '\\n' from every line before choosing a random one; a better solution is left as an exercise for the reader.\n", "To print one random word per line, your loop could be:\nfor line in wordsf:\n word = random.choice(line.split())\n print(word)\n\nIf there are lines with nothing but whitespace, you also need to skip those:\nfor line in wordsf:\n if line.isspace(): continue\n word = random.choice(line.split())\n print(word)\n\nThe counting part you have seems to be correct, but unrelated to your question.\nEdit: I see you meant something different in your Q (as other A's also intepreted): you want to choose a random line from the file, not a random word from each lines. That being the case, the other A's are correct, but they take O(N) auxiliary memory for a file of N lines. There's a nice algorithm due to Knuth to pick a random sample from a stream without knowing in advance how many items it has (unfortunately it requires generating N random numbers, so it's slower than the simpler one if you have enough memory for the latter... but it's still interesting to consider!-)...:\nn = 0\nword = None\nfor line in wordsf:\n n += 1\n if random.randrange(n) == 0:\n word = line\nprint(word.strip())\n\nBasically, at each line n, we're picking it to replace the previous one (if any) with a probability of 1.0/n -- so the first time probability 1 (certainty), the second time probability 0.5, and so on. I'm doing the stripping only at the end as it would be a waste of effort to strip temporary choices that are later replaced; and I'm avoiding the division and floating point hassles by generating a random number with uniform probability between 0 and n-1 included (so the probability of that random number being 0 is 1/n) -- minor issues, but since they don't make the code any less clear, we might as well take care of them;-).\n", "import random\ndef main():\n wordsf = open('words.txt', 'r')\n words = [line.rstrip('\\n') for line in wordsf]\n wordsf.close()\n\n random_number = random.randint(0, len(words)-1)\n random_word = words[random_number]\n print random_word\n\nThis works well, but if the file wordsf is too huge, then I think you'll start to encounter memory issues, but I think this should do fine for most cases\nHope this helps.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "file", "python", "random" ]
stackoverflow_0002762365_file_python_random.txt
Q: Access to module denied from within GAE dev server I am developing an app for GAE. Having installed the "feedparser" module with setuptools, I tried importing it (with "import feedparser") statement. However, the module does not load and when I look at the dev_appserver.py debug log on screen, I see the following: Access to module file denied: /usr/local/lib/python2.6/dist-packages/feedparser-4.1-py2.6.egg/feedparser.py So GAE dev server cannot access the module but I can't figure out why. The path is correct and the file is accessible. I am fairly new to Python/Django/GAE - what am I missing? A: App Engine runs Python code in a sandbox, and only authorized standard library modules & packages can be imported from your application. as @mg has mentioned, if you want to allow for 3rd-party modules & packages, you need to bundle them with your application. to do that specifically for feedparser, just drop the feedparser.py file into your top-level App Engine directory (where your app.yaml, index.yaml, and main.py are located). (UPDATED Oct 2011) also keep in mind the hard limits: max total number of files (app files and static files): 3,000 (upped to 10k in 1.5.5, Oct 2011) max size of an application or static file: 10MB (upped to 32MB in 1.5.5) max total size of all application and static files: 150MB if you want to save on the total number of files, you can put a wad of .py files in a ZIP so you only pay for one file. although this article is slightly out-of-date -- recommending bundling of Django 1.0 which is now included -- the technique of bundling modules & packages into ZIP files still apply: http://code.google.com/appengine/articles/django10_zipimport.html Official page in the docs which discusses the file limitations: http://code.google.com/appengine/docs/python/runtime.html#Pure_Python (UPDATED Nov 2011): The link below features a list of whitelisted Python modules/packages with C code for 2.5. The Python 2.7 runtime frees up many restrictions so much so that the whitelist has become a blacklist. Here are the allowed/whitelisted 2.5 C modules as well as the disallowed/blacklisted 2.7 C modules: http://code.google.com/appengine/kb/libraries.html A: Because in GAE you cannot access libraries that are not parts of GAE itself, are not included in GAE, like django 0.96.1, or are not part of your application. Install that library, and every one else, in the same path of your web application. EDIT From the documentation: You can include other pure Python libraries with your application by putting the code in your application directory. If you make a symbolic link to a module's directory in your application directory, appcfg.py will follow the link and include the module in your app. The Python module include path includes your application's root directory (the directory containing the app.yaml file). Modules you create in your application's root directory are available using a path from the root. Don't forget to create init.py files in sub-directories, so Python will recognize the sub-directories as packages.
Access to module denied from within GAE dev server
I am developing an app for GAE. Having installed the "feedparser" module with setuptools, I tried importing it (with "import feedparser") statement. However, the module does not load and when I look at the dev_appserver.py debug log on screen, I see the following: Access to module file denied: /usr/local/lib/python2.6/dist-packages/feedparser-4.1-py2.6.egg/feedparser.py So GAE dev server cannot access the module but I can't figure out why. The path is correct and the file is accessible. I am fairly new to Python/Django/GAE - what am I missing?
[ "App Engine runs Python code in a sandbox, and only authorized standard library modules & packages can be imported from your application.\nas @mg has mentioned, if you want to allow for 3rd-party modules & packages, you need to bundle them with your application. to do that specifically for feedparser, just drop the feedparser.py file into your top-level App Engine directory (where your app.yaml, index.yaml, and main.py are located).\n(UPDATED Oct 2011) also keep in mind the hard limits:\n\nmax total number of files (app files and static files): 3,000 (upped to 10k in 1.5.5, Oct 2011)\nmax size of an application or static file: 10MB (upped to 32MB in 1.5.5)\nmax total size of all application and static files: 150MB\n\nif you want to save on the total number of files, you can put a wad of .py files in a ZIP so you only pay for one file. although this article is slightly out-of-date -- recommending bundling of Django 1.0 which is now included -- the technique of bundling modules & packages into ZIP files still apply:\nhttp://code.google.com/appengine/articles/django10_zipimport.html\nOfficial page in the docs which discusses the file limitations:\nhttp://code.google.com/appengine/docs/python/runtime.html#Pure_Python\n(UPDATED Nov 2011): The link below features a list of whitelisted Python modules/packages with C code for 2.5. The Python 2.7 runtime frees up many restrictions so much so that the whitelist has become a blacklist. Here are the allowed/whitelisted 2.5 C modules as well as the disallowed/blacklisted 2.7 C modules:\nhttp://code.google.com/appengine/kb/libraries.html\n", "Because in GAE you cannot access libraries that are not parts of GAE itself, are not included in GAE, like django 0.96.1, or are not part of your application. Install that library, and every one else, in the same path of your web application.\nEDIT\nFrom the documentation:\n\nYou can include other pure Python\n libraries with your application by\n putting the code in your application\n directory. If you make a symbolic link\n to a module's directory in your\n application directory, appcfg.py will\n follow the link and include the module\n in your app.\nThe Python module include path\n includes your application's root\n directory (the directory containing\n the app.yaml file). Modules you create\n in your application's root directory\n are available using a path from the\n root. Don't forget to create\n init.py files in sub-directories, so Python will recognize the\n sub-directories as packages.\n\n" ]
[ 6, 1 ]
[]
[]
[ "django", "google_app_engine", "permissions", "python" ]
stackoverflow_0002756790_django_google_app_engine_permissions_python.txt
Q: pyobj access to iTunes application Let's say I managed to get the dictionary opened for iTunes in the Applescript editor: How would I access the "search" commands using Python with pyobjc? I know I get can hold of the iTunes application using: iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes") but after I do a dir on it, I don't see the search command in the returned dictionary. Help please! A: Use appscript instead of Scripting Bridge. There are versions available for Python, Ruby and Objective-C. Unlike Scripting Bridge, appscript is designed to work with Apple Events rather than make it pretend to be something it isn't; it's also quite a bit more flexible and less buggy. As a bonus, you don't have to go through PyObjC. The appscript documentation is good and worth reading. You can install ASTranslate which will convert an AppleScript script into appscript code for any of the above languages. When I'm doing something tricky, I often write it in (Apple)Script Editor, then convert into Python with ASTranslate. There's also ASDictionary, which produces HTML-formatted versions of dictionaries formatted for appscript languages; I don't use it much since I find experimenting with Script Editor more accessible. (However, if you don't have much experience with AppleScript, maybe it'd be a better choice.) For some examples of controlling iTunes with Python appscript, you can see some scripts I wrote.
pyobj access to iTunes application
Let's say I managed to get the dictionary opened for iTunes in the Applescript editor: How would I access the "search" commands using Python with pyobjc? I know I get can hold of the iTunes application using: iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes") but after I do a dir on it, I don't see the search command in the returned dictionary. Help please!
[ "Use appscript instead of Scripting Bridge. There are versions available for Python, Ruby and Objective-C. Unlike Scripting Bridge, appscript is designed to work with Apple Events rather than make it pretend to be something it isn't; it's also quite a bit more flexible and less buggy. As a bonus, you don't have to go through PyObjC.\nThe appscript documentation is good and worth reading. You can install ASTranslate which will convert an AppleScript script into appscript code for any of the above languages. When I'm doing something tricky, I often write it in (Apple)Script Editor, then convert into Python with ASTranslate. There's also ASDictionary, which produces HTML-formatted versions of dictionaries formatted for appscript languages; I don't use it much since I find experimenting with Script Editor more accessible. (However, if you don't have much experience with AppleScript, maybe it'd be a better choice.)\nFor some examples of controlling iTunes with Python appscript, you can see some scripts I wrote.\n" ]
[ 3 ]
[]
[]
[ "applescript", "itunes", "macos", "pyobjc", "python" ]
stackoverflow_0002762358_applescript_itunes_macos_pyobjc_python.txt
Q: ImportError: No module named optparse in jython getting Traceback (most recent call last): File "C:\projects\myproject\convert.py", line 139, in <module> import optparse ImportError: No module named optparse. when executing it using jython. Same module works fine when i execute it through python. I am usinng window7 operating system. The same modle works fine on windows XP machine with both python and Jython. A: My guess is that you're using Jython 2.2, which, according to the FAQ: Jython 2.2 does not implement any features added to CPython in version 2.3 or later. Where optparse was added in Python 2.3. The newest version of Jython is 2.5.1, so you'll probably want to go ahead and download it.
ImportError: No module named optparse in jython
getting Traceback (most recent call last): File "C:\projects\myproject\convert.py", line 139, in <module> import optparse ImportError: No module named optparse. when executing it using jython. Same module works fine when i execute it through python. I am usinng window7 operating system. The same modle works fine on windows XP machine with both python and Jython.
[ "My guess is that you're using Jython 2.2, which, according to the FAQ:\n\nJython 2.2 does not implement any features added to CPython in version 2.3 or later.\n\nWhere optparse was added in Python 2.3.\nThe newest version of Jython is 2.5.1, so you'll probably want to go ahead and download it.\n" ]
[ 1 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0002762571_jython_python.txt
Q: Python: cleaner list comprehension Is there a cleaner way to write this: for w in [w for w in words if w != '']: I want to loop over a dictionary words, but only words that != ''. Thanks! A: You don't need a listcomp here. Just write: for w in words: if w != '': # ... A: Assuming that you are after the keys, why not try: [w for w in words if w] A: filter(lambda w: w != '', words) or filter(None, words) this is suggestion, it may not be the best solution for your problem. A: Testing that an element does not equal '' isn't going to filter out whitespace elements. If that's what you're after, you probably want to use str.isspace (or a regular expression). If you use a list comprehension, you'll make an extra copy of the list as an intermediary object. Probably not a big deal, but a generator won't use the extra memory. I'd do it like this, with a generator: for word in (w for w in words if not w.isspace()): # do stuff A: I think your solution is sub optimal. You're iterating over the list words twice - once in the list comprehension to create the non-null terms and again in the loop to do the processing. It would be better if you used a genexp like so. for w in (x for x in words if x): process(w) That way, the genexp will lazily return a list of non-nulls. A: What does the body of the outer for loop do? If it's a function call you could potentially just do: [f(w) for w in words if w != '']
Python: cleaner list comprehension
Is there a cleaner way to write this: for w in [w for w in words if w != '']: I want to loop over a dictionary words, but only words that != ''. Thanks!
[ "You don't need a listcomp here. Just write:\nfor w in words:\n if w != '':\n # ...\n\n", "Assuming that you are after the keys, why not try:\n[w for w in words if w]\n\n", "filter(lambda w: w != '', words) or filter(None, words)\nthis is suggestion, it may not be the best solution for your problem.\n", "Testing that an element does not equal '' isn't going to filter out whitespace elements. If that's what you're after, you probably want to use str.isspace (or a regular expression).\nIf you use a list comprehension, you'll make an extra copy of the list as an intermediary object. Probably not a big deal, but a generator won't use the extra memory.\nI'd do it like this, with a generator:\nfor word in (w for w in words if not w.isspace()):\n # do stuff\n\n", "I think your solution is sub optimal. You're iterating over the list words twice - once in the list comprehension to create the non-null terms and again in the loop to do the processing. It would be better if you used a genexp like so.\nfor w in (x for x in words if x): process(w)\n\nThat way, the genexp will lazily return a list of non-nulls.\n", "What does the body of the outer for loop do?\nIf it's a function call you could potentially just do:\n[f(w) for w in words if w != '']\n" ]
[ 6, 2, 1, 1, 1, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0002762623_list_comprehension_python.txt
Q: Retrieving my own data via FaceBook API I am building a website for a comedy group which uses Facebook as one of their marketing platforms; one of the requirements for the new site is to display all of their Facebook events on a calendar. Currently, I am just trying to put together a Python script which can pull some data from my own Facebook account, like a list of all my friends. I presume once I can accomplish this I can move to pulling more complicated data out of my clients account (since they have given me access to their account). I have looked at many of the posts here, and also went through the Facebook API documentation, including Facebook Connect, but am really beating my head against the wall. Everything I have read seems like overkill, as it involves setting up a good deal of infrastructure to allow my app to set up connections to any arbitrary user's account (who authorizes me). Shouldn't it be much simpler, given I only ever need to access 1 account? I cannot find a way to retrieve data without having to display the Facebook login window. I have a script which will retrieve all my friends, but it includes a redirect where I have to physically log myself in to Facebook. Would appreciate any advice or links, I just feel like I must be missing something simple. Thank you! A: Just posting up my notes on the successful advice, should others find this post; Per Daniel and William's advice, I obtained the right permissions using the Connect options. From William, this link explains how the Facebook connection works https://developers.facebook.com/docs/authentication/ This section on setting up the actual authentication was most helpful to me. http://developers.facebook.com/docs/api Basically, it goes as follows: Post a link to the following URL. A user will need to physically click on it (even if that user is just you, the site admin). https://graph.facebook.com/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=http://www.example.com/HANDLER This will redirect to a Facebook login, which will return to http://www.example.com/HANDLER after the user authenticates. If you wish to do more than basic reads and news feed updates you will need to include this variable in the above link: scope=offline_access,user_photos. The scope variable just includes a comma separated list of values, which Facebook will explicitly tell the authenticating user about during the login process, and they will have to OK. Most helpful for me was the offline_access flag (user_photos lets you get at their photos too), so I can pull content without someone logging in regularly (so long as I store the access token obtained later) Have a script located at http://www.example.com/HANDLER that will take a variable from the request (so facebook will redirect to http://www.example.com/HANDLER&code=YOUR_CODE after authentication). Your handler needs to pull out the code variable, and then send the following request: https://graph.facebook.com/oauth/access_token? client_id=YOUR_CLIENT_ID& redirect_uri=http://www.example.com/oauth_redirect& client_secret=YOUR_SECRET_KEY& code=YOUR_CODE This request will return a string of the form access_token=YOUR_ACCESS_TOKEN. Just parse off the 'access_token=', and you will have a token that you can use to access the facebook graph API, in requests like http://graph.facebook.com/me/friends?access_token=YOUR_ACCESS_TOKEN This will return a JSON object containing all of your friends Hope this saves someone else some not fun time straining through documentation. Thanks for the help! A: It is true, that Facebook's API is targeted at developers who are creating apps that will be used by many users. Thankfully, the new Graph API is much simpler to use than its predecessor, and shouldn't be terribly difficult for you to work with without using or creating a lot of underlying infrastructure. You will need to implement authorization, but this is not difficult, and as long as you prompt the user for the offline_access permission, it'll only need to be done once. The documentation on Desktop Authentication would probably be most relevant to you at this point, though you might want to move to the javascript-based authentication once you've got a web app up and running. Once the authentication is done, all you're doing is making GET requests to various urls and working with the resulting JSON. Here's the documentation about Events, and you can get a list of friends from the friends connection of a User. A: I'm not expert on Facebook/Facebook Connect, however I've seen it used/used applications with it and it seems there's really only the 'official' way to do it. I'm afraid it looks like your best bet would probably be something along the lines of this. http://wiki.developers.facebook.com/index.php/Connect/Authentication_and_Authorization Regardless of how you actually 'use' it, you'll still need to authorize the application to connect to the account and this means having a Facebook App as well. A: The answer to Facebook application authentication is hard to find but is actually found within the "Analytics" page of the Graph API. Specify the following: https://graph.facebook.com/oauth/access_token?client_cred&client_id=yourappid&client_secret=yourappsecret , you will then be given an access_token that you may use on all other calls. The Facebook provided APIs do NOT currently provide this level of functionality.
Retrieving my own data via FaceBook API
I am building a website for a comedy group which uses Facebook as one of their marketing platforms; one of the requirements for the new site is to display all of their Facebook events on a calendar. Currently, I am just trying to put together a Python script which can pull some data from my own Facebook account, like a list of all my friends. I presume once I can accomplish this I can move to pulling more complicated data out of my clients account (since they have given me access to their account). I have looked at many of the posts here, and also went through the Facebook API documentation, including Facebook Connect, but am really beating my head against the wall. Everything I have read seems like overkill, as it involves setting up a good deal of infrastructure to allow my app to set up connections to any arbitrary user's account (who authorizes me). Shouldn't it be much simpler, given I only ever need to access 1 account? I cannot find a way to retrieve data without having to display the Facebook login window. I have a script which will retrieve all my friends, but it includes a redirect where I have to physically log myself in to Facebook. Would appreciate any advice or links, I just feel like I must be missing something simple. Thank you!
[ "Just posting up my notes on the successful advice, should others find this post;\nPer Daniel and William's advice, I obtained the right permissions using the Connect options. From William, this link explains how the Facebook connection works\nhttps://developers.facebook.com/docs/authentication/\nThis section on setting up the actual authentication was most helpful to me.\nhttp://developers.facebook.com/docs/api\nBasically, it goes as follows:\nPost a link to the following URL. A user will need to physically click on it (even if that user is just you, the site admin).\nhttps://graph.facebook.com/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=http://www.example.com/HANDLER\nThis will redirect to a Facebook login, which will return to http://www.example.com/HANDLER after the user authenticates. If you wish to do more than basic reads and news feed updates you will need to include this variable in the above link: scope=offline_access,user_photos. The scope variable just includes a comma separated list of values, which Facebook will explicitly tell the authenticating user about during the login process, and they will have to OK. Most helpful for me was the offline_access flag (user_photos lets you get at their photos too), so I can pull content without someone logging in regularly (so long as I store the access token obtained later)\nHave a script located at http://www.example.com/HANDLER that will take a variable from the request (so facebook will redirect to http://www.example.com/HANDLER&code=YOUR_CODE after authentication). Your handler needs to pull out the code variable, and then send the following request:\nhttps://graph.facebook.com/oauth/access_token?\n client_id=YOUR_CLIENT_ID&\n redirect_uri=http://www.example.com/oauth_redirect&\n client_secret=YOUR_SECRET_KEY&\n code=YOUR_CODE\nThis request will return a string of the form access_token=YOUR_ACCESS_TOKEN.\nJust parse off the 'access_token=', and you will have a token that you can use to access the facebook graph API, in requests like \nhttp://graph.facebook.com/me/friends?access_token=YOUR_ACCESS_TOKEN\nThis will return a JSON object containing all of your friends\nHope this saves someone else some not fun time straining through documentation. Thanks for the help!\n", "It is true, that Facebook's API is targeted at developers who are creating apps that will be used by many users.\nThankfully, the new Graph API is much simpler to use than its predecessor, and shouldn't be terribly difficult for you to work with without using or creating a lot of underlying infrastructure.\nYou will need to implement authorization, but this is not difficult, and as long as you prompt the user for the offline_access permission, it'll only need to be done once.\nThe documentation on Desktop Authentication would probably be most relevant to you at this point, though you might want to move to the javascript-based authentication once you've got a web app up and running.\nOnce the authentication is done, all you're doing is making GET requests to various urls and working with the resulting JSON.\nHere's the documentation about Events, and you can get a list of friends from the friends connection of a User.\n", "I'm not expert on Facebook/Facebook Connect, however I've seen it used/used applications with it and it seems there's really only the 'official' way to do it. I'm afraid it looks like your best bet would probably be something along the lines of this.\nhttp://wiki.developers.facebook.com/index.php/Connect/Authentication_and_Authorization\nRegardless of how you actually 'use' it, you'll still need to authorize the application to connect to the account and this means having a Facebook App as well.\n", "The answer to Facebook application authentication is hard to find but is actually found within the \"Analytics\" page of the Graph API.\nSpecify the following: https://graph.facebook.com/oauth/access_token?client_cred&client_id=yourappid&client_secret=yourappsecret , you will then be given an access_token that you may use on all other calls.\nThe Facebook provided APIs do NOT currently provide this level of functionality.\n" ]
[ 7, 2, 0, 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0002756237_facebook_python.txt
Q: Python modules not updating after restarting the main module I've recently come back to a project having had to stop for about 6 months, and after reinstalling my operating system and coming back to it I'm having all kinds of crazy things happen. I made sure to install the same version(2.6) of python that I was using before. It started by giving me strange tkinter error that I hadn't had trouble with before, the program is relatively simple and the 2 or 3 bugs that were left when i quit, I had documented and weren't related to the interface. Things got even weirder when the same error would pop up even after I had removed the offending section of code. In fact, the traceback pointed to a line that didn't even exist in the module it was referencing, eg: line 262 when the module was only 200 lines long. After just starting a completely new file for the main module and copy/pasting it finally recognized that the offending code was gone and I stopped getting the error only to find that any updates to the code I made in another module didn't show up when I restarted the program through the shell. (I didn't forget to save.) After fiddling with this, of course, the old interface error came back, only in a different section of code that had been working previously. In fact, if I revert back to the files I had six months ago, the program works fine. As soon as I change anything in the main module, however, the interface bug comes back. Here's the original error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "C:\PyStuff\interface.py", line 202, in dispOne __main__.top.destroy() File "C:\Python26\lib\lib-tk\Tkinter.py", line 1938, in destroy self.tk.call('destroy', self._w) TclError: can't invoke "destroy" command: application has been destroyed I'm guessing something else is going on here other than my own poor programming. Anyone have any ideas? Edit: Thinking back, I believe I read something about it being a bad idea to run Tkinter programs through IDLE's shell, and it appears, at least, that the TclError has vanished if I instead start the main module by double clicking the .pyc file. Perhaps my problems were just a combination of that plus the timestamp/PYTHONPATH issues mentioned below by Chris Atlee and Vlad? A: I've had something similar happen. The cause for my problems was that my source control software (hg) was setting the date of files to a date in the past. Because of this, python chose to use previously generated .pyc files which had newer timestamps. The solution was to delete all the .pyc files before testing the code. A: Check your PYTHON_PATH variable, you probably have an older version of the file. Also start your python interpreter and type the following commands to check the path: import sys print sys.path Take a careful look at the output and make sure you don't have any old directories sitting there.
Python modules not updating after restarting the main module
I've recently come back to a project having had to stop for about 6 months, and after reinstalling my operating system and coming back to it I'm having all kinds of crazy things happen. I made sure to install the same version(2.6) of python that I was using before. It started by giving me strange tkinter error that I hadn't had trouble with before, the program is relatively simple and the 2 or 3 bugs that were left when i quit, I had documented and weren't related to the interface. Things got even weirder when the same error would pop up even after I had removed the offending section of code. In fact, the traceback pointed to a line that didn't even exist in the module it was referencing, eg: line 262 when the module was only 200 lines long. After just starting a completely new file for the main module and copy/pasting it finally recognized that the offending code was gone and I stopped getting the error only to find that any updates to the code I made in another module didn't show up when I restarted the program through the shell. (I didn't forget to save.) After fiddling with this, of course, the old interface error came back, only in a different section of code that had been working previously. In fact, if I revert back to the files I had six months ago, the program works fine. As soon as I change anything in the main module, however, the interface bug comes back. Here's the original error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "C:\PyStuff\interface.py", line 202, in dispOne __main__.top.destroy() File "C:\Python26\lib\lib-tk\Tkinter.py", line 1938, in destroy self.tk.call('destroy', self._w) TclError: can't invoke "destroy" command: application has been destroyed I'm guessing something else is going on here other than my own poor programming. Anyone have any ideas? Edit: Thinking back, I believe I read something about it being a bad idea to run Tkinter programs through IDLE's shell, and it appears, at least, that the TclError has vanished if I instead start the main module by double clicking the .pyc file. Perhaps my problems were just a combination of that plus the timestamp/PYTHONPATH issues mentioned below by Chris Atlee and Vlad?
[ "I've had something similar happen. The cause for my problems was that my source control software (hg) was setting the date of files to a date in the past. Because of this, python chose to use previously generated .pyc files which had newer timestamps.\nThe solution was to delete all the .pyc files before testing the code.\n", "Check your PYTHON_PATH variable, you probably have an older version of the file.\nAlso start your python interpreter and type the following commands to check the path:\nimport sys\nprint sys.path\n\nTake a careful look at the output and make sure you don't have any old directories sitting there.\n" ]
[ 2, 0 ]
[]
[]
[ "interface", "python", "tkinter" ]
stackoverflow_0002762883_interface_python_tkinter.txt
Q: Horizontal scrolling in a wx.RichTextCtrl I have a RichTextCtrl created as follows: self.userlist = wx.richtext.RichTextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL) It all works fine, except for the wx.HSCROLL style. If I change the RichTextCtrl to a regular TextCtrl, it correctly horizontal scrolls on long lines, rather than wrapping, but on the RichTextCtrl it wraps regardless. Is there an easy way to make it scroll horizontally? (I do, unfortunately, need the RichTextCtrl's featureset for this object.) A: sorry, I can't post this as a comment as I don't have the reputation, and I'm not sure this is an answer per se http://trac.wxwidgets.org/ticket/9382 it looks old, but I confirm the behaviour you are seeing. Does setting the wx.TE_RICH or wx.TE_RICH2 on a regular TextCtrl give you the behaviour you need? A: This is a bug in wxRitchText see http://trac.wxwidgets.org/ticket/9382 Also instead of wx.TE_MULTILINE|wx.TE_READONLY you should be using values from richtext module i.e. wx.richtext.RE_MULTILINE |wx.richtext.RE_READONLY, though that doesn't make any difference, still.
Horizontal scrolling in a wx.RichTextCtrl
I have a RichTextCtrl created as follows: self.userlist = wx.richtext.RichTextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL) It all works fine, except for the wx.HSCROLL style. If I change the RichTextCtrl to a regular TextCtrl, it correctly horizontal scrolls on long lines, rather than wrapping, but on the RichTextCtrl it wraps regardless. Is there an easy way to make it scroll horizontally? (I do, unfortunately, need the RichTextCtrl's featureset for this object.)
[ "sorry, I can't post this as a comment as I don't have the reputation, and I'm not sure this is an answer per se\nhttp://trac.wxwidgets.org/ticket/9382 it looks old, but I confirm the behaviour you are seeing. \nDoes setting the wx.TE_RICH or wx.TE_RICH2 on a regular TextCtrl give you the behaviour you need?\n", "This is a bug in wxRitchText see http://trac.wxwidgets.org/ticket/9382\nAlso instead of wx.TE_MULTILINE|wx.TE_READONLY you should be using values from richtext module i.e. wx.richtext.RE_MULTILINE |wx.richtext.RE_READONLY, though that doesn't make any difference, still.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0002759409_python_wxpython_wxwidgets.txt
Q: how to create http headers from scratch So, I made a simple socket server using python. And now I'm trying to structure a proper http response. However, I can't seem to find any sort of tutorial or spec that discusses how to format http responses. Could someone point me to the right place? A: RFC 2616. A: You may want to check out the following article: HTTP Made Really Easy: A Practical Guide to Writing Clients and Servers The section Sample HTTP Exchange could help you getting started. Quoting: The server should respond with something like the following, sent back through the same socket: HTTP/1.0 200 OK Date: Fri, 31 Dec 1999 23:59:59 GMT Content-Type: text/html Content-Length: 1354 <html> <body> <h1>Happy New Millennium!</h1> (more file contents) . . . </body> </html> After sending the response, the server closes the socket. The full protocol is defined in RFC 2616 if you want to get serious about this. A: The urllib2 python standard library module helps you add http headers to your request. Look in here for an example.
how to create http headers from scratch
So, I made a simple socket server using python. And now I'm trying to structure a proper http response. However, I can't seem to find any sort of tutorial or spec that discusses how to format http responses. Could someone point me to the right place?
[ "RFC 2616.\n", "You may want to check out the following article:\n\nHTTP Made Really Easy: A Practical Guide to Writing Clients and Servers\n\nThe section Sample HTTP Exchange could help you getting started. Quoting:\n\nThe server should respond with something like the following, sent back through the same socket:\n\nHTTP/1.0 200 OK\nDate: Fri, 31 Dec 1999 23:59:59 GMT\nContent-Type: text/html\nContent-Length: 1354\n\n<html>\n<body>\n<h1>Happy New Millennium!</h1>\n(more file contents)\n .\n .\n .\n</body>\n</html>\n\n\nAfter sending the response, the server closes the socket.\n\nThe full protocol is defined in RFC 2616 if you want to get serious about this.\n", "The urllib2 python standard library module helps you add http headers to your request.\nLook in here for an example.\n" ]
[ 3, 2, 2 ]
[]
[]
[ "http", "http_headers", "python", "sockets" ]
stackoverflow_0002763265_http_http_headers_python_sockets.txt
Q: Likelihood of IOError during print vs. write I recently encountered an IOError writing to a file on NFS. There wasn't a disk space or permission issue, so I assume this was just a network hiccup. The obvious solution is to wrap the write in a try-except, but I was curious whether the implementation of print and write in Python make either of the following more or less likely to raise IOError: f_print = open('print.txt', 'w') print >>f_print, 'test_print' f_print.close() vs. f_write = open('write.txt', 'w') f_write.write('test_write\n') f_write.close() (If it matters, specifically in Python 2.4 on Linux). A: prints are implemented in terms of writes which ultimately result in a write(2) call to the kernel. You could run strace on those two samples and (after wading through a lot of chaff) see the same resultant calls to write(2). Indeed, I just did that and omitting 2000+ lines of output yielded: execve("/usr/bin/python", ["python", "a.py"], [/* 43 vars */]) = 0 open("print.txt", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3 write(3, "test_print\n", 11) = 11 close(3) = 0 and execve("/usr/bin/python", ["python", "b.py"], [/* 43 vars */]) = 0 open("write.txt", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3 write(3, "test_write\n", 11) = 11 close(3) = 0 not a whole lot of difference to be seen, there. Whether the destination file is on a local disk or an NFS mount, the write() call will be the same. The oft-named Nightmare File System will - all other things being equal - fail more often than your local disk.
Likelihood of IOError during print vs. write
I recently encountered an IOError writing to a file on NFS. There wasn't a disk space or permission issue, so I assume this was just a network hiccup. The obvious solution is to wrap the write in a try-except, but I was curious whether the implementation of print and write in Python make either of the following more or less likely to raise IOError: f_print = open('print.txt', 'w') print >>f_print, 'test_print' f_print.close() vs. f_write = open('write.txt', 'w') f_write.write('test_write\n') f_write.close() (If it matters, specifically in Python 2.4 on Linux).
[ "prints are implemented in terms of writes which ultimately result in a write(2) call to the kernel. You could run strace on those two samples and (after wading through a lot of chaff) see the same resultant calls to write(2).\nIndeed, I just did that and omitting 2000+ lines of output yielded:\nexecve(\"/usr/bin/python\", [\"python\", \"a.py\"], [/* 43 vars */]) = 0\nopen(\"print.txt\", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3\nwrite(3, \"test_print\\n\", 11) = 11\nclose(3) = 0\n\nand\nexecve(\"/usr/bin/python\", [\"python\", \"b.py\"], [/* 43 vars */]) = 0\nopen(\"write.txt\", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3\nwrite(3, \"test_write\\n\", 11) = 11\nclose(3) = 0\n\nnot a whole lot of difference to be seen, there. Whether the destination file is on a local disk or an NFS mount, the write() call will be the same. The oft-named Nightmare File System will - all other things being equal - fail more often than your local disk.\n" ]
[ 1 ]
[]
[]
[ "exception", "file_io", "python" ]
stackoverflow_0002763120_exception_file_io_python.txt
Q: How do I use Python to prevent a file from being copied? I have a file that I need to "protect" so that it cannot be copied! I am using Python on Windows XP. I think it may just be changing file permissions?? A: You can prevent the file being copied only by removing read permission from the user that shouldn't be able to copy the file. You can use os.chmod for this, or see this page explaining to set permissions with the full Windows security model. A: Is this a temporary or a permanent file? If it's temporary, take a look at the tempfile module, especially tempfile.mkstemp().
How do I use Python to prevent a file from being copied?
I have a file that I need to "protect" so that it cannot be copied! I am using Python on Windows XP. I think it may just be changing file permissions??
[ "You can prevent the file being copied only by removing read permission from the user that shouldn't be able to copy the file. You can use os.chmod for this, or see this page explaining to set permissions with the full Windows security model.\n", "Is this a temporary or a permanent file? If it's temporary, take a look at the tempfile module, especially tempfile.mkstemp().\n" ]
[ 2, 0 ]
[]
[]
[ "copy", "file", "python", "windows" ]
stackoverflow_0002763350_copy_file_python_windows.txt
Q: Python New-style Classes and the Super Function This is not the result I expect to see: class A(dict): def __init__(self, *args, **kwargs): self['args'] = args self['kwargs'] = kwargs class B(A): def __init__(self, *args, **kwargs): super(B, self).__init__(args, kwargs) print 'Instance A:', A('monkey', banana=True) #Instance A: {'args': ('monkey',), 'kwargs': {'banana': True}} print 'Instance B:', B('monkey', banana=True) #Instance B: {'args': (('monkey',), {'banana': True}), 'kwargs': {}} I'm just trying to get classes A and B to have consistent values set. I'm not sure why the kwargs are being inserted into the args, but I'm to presume I am either calling __init__() wrong from the subclass or I'm trying to do something that you just can't do. Any tips? A: Try this instead: super(B, self).__init__(*args, **kwargs) Since the init function for A is expecting actual args/kwargs (and not just two arguments), you have to actually pass it the unpacked versions of args/kwargs so that they'll be repacked properly. Otherwise, the already-packed list of args and dict of kwargs gets re-packed as just an args list with two elements, and an empty kwargs dict, due to the fact that you're passing a list and a dict, instead of actual unnamed and named parameters. A: While I agree entirely with Dav, are you aware that if the __init__ of B has no other purpose than invoking its super, you can safely omit it? What I mean is that with your examples you could simply define B as >>> class B(A): ... pass
Python New-style Classes and the Super Function
This is not the result I expect to see: class A(dict): def __init__(self, *args, **kwargs): self['args'] = args self['kwargs'] = kwargs class B(A): def __init__(self, *args, **kwargs): super(B, self).__init__(args, kwargs) print 'Instance A:', A('monkey', banana=True) #Instance A: {'args': ('monkey',), 'kwargs': {'banana': True}} print 'Instance B:', B('monkey', banana=True) #Instance B: {'args': (('monkey',), {'banana': True}), 'kwargs': {}} I'm just trying to get classes A and B to have consistent values set. I'm not sure why the kwargs are being inserted into the args, but I'm to presume I am either calling __init__() wrong from the subclass or I'm trying to do something that you just can't do. Any tips?
[ "Try this instead:\nsuper(B, self).__init__(*args, **kwargs)\n\nSince the init function for A is expecting actual args/kwargs (and not just two arguments), you have to actually pass it the unpacked versions of args/kwargs so that they'll be repacked properly.\nOtherwise, the already-packed list of args and dict of kwargs gets re-packed as just an args list with two elements, and an empty kwargs dict, due to the fact that you're passing a list and a dict, instead of actual unnamed and named parameters.\n", "While I agree entirely with Dav, are you aware that if the __init__ of B has no other purpose than invoking its super, you can safely omit it? What I mean is that with your examples you could simply define B as\n>>> class B(A):\n... pass\n\n" ]
[ 14, 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002763335_class_python.txt
Q: Grid within a frame? Is it possible to place a grid of buttons in Tkinter inside another frame? I'm wanting to create a tic-tac-toe like game and want to use the grid feature to put gamesquares (that will be buttons). However, I'd like to have other stuff in the GUI other than just the game board so it's not ideal to just have everything in the one grid. To illustrate: O | X | X | ---------- | O | O | X | Player 2 wins! ---------- | X | O | X | The tic tac toe board is in a grid that is made up of all buttons and the 'player 2 wins' is a label inside a frame. This is an oversimplification of what I'm trying to do so bear with me, for the way I've designed the program so far (the board is dynamically created) a grid makes the most sense. Edit: Had a thought but when I run it, nothing happens? If I take out the frame bit it does. Any ideas? from Tkinter import * root = Tk() b = Button(root, text = "1") b.grid(row=1, column=3) b2 = Button(root, text = "2") b2.grid(row=1, column=4) f = Frame(root, bg = "red") f.pack(side=RIGHT) root.mainloop() A: Figured out a way to do it finally: from Tkinter import * root = Tk() f = Frame(root, bg = "orange", width = 500, height = 500) f.pack(side=LEFT, expand = 1) f3 = Frame(f, bg = "red", width = 500) f3.pack(side=LEFT, expand = 1, pady = 50, padx = 50) f2 = Frame(root, bg = "black", height=100, width = 100) f2.pack(side=LEFT, fill = Y) b = Button(f2, text = "test") b.pack() b = Button(f3, text = "1", bg = "red") b.grid(row=1, column=3) b2 = Button(f3, text = "2") b2.grid(row=1, column=4) b3 = Button(f3, text = "2") b3.grid(row=2, column=0) root.mainloop() Having the grid inside a frame inside a frame is a bit of a hack to get the padding around the grid working but it works so I'm happy. A: You can nest Tk widgets arbitrarily deep. Quoth the manual: The size of any master widget is determined by the size of the “slave widgets” inside. The packer is used to control where slave widgets appear inside the master into which they are packed. You can pack widgets into frames, and frames into other frames, in order to achieve the kind of layout you desire. Additionally, the arrangement is dynamically adjusted to accommodate incremental changes to the configuration, once it is packed. Indeed, a frame containing a (frame of buttons) and a label is how you must structure the layout you describe.
Grid within a frame?
Is it possible to place a grid of buttons in Tkinter inside another frame? I'm wanting to create a tic-tac-toe like game and want to use the grid feature to put gamesquares (that will be buttons). However, I'd like to have other stuff in the GUI other than just the game board so it's not ideal to just have everything in the one grid. To illustrate: O | X | X | ---------- | O | O | X | Player 2 wins! ---------- | X | O | X | The tic tac toe board is in a grid that is made up of all buttons and the 'player 2 wins' is a label inside a frame. This is an oversimplification of what I'm trying to do so bear with me, for the way I've designed the program so far (the board is dynamically created) a grid makes the most sense. Edit: Had a thought but when I run it, nothing happens? If I take out the frame bit it does. Any ideas? from Tkinter import * root = Tk() b = Button(root, text = "1") b.grid(row=1, column=3) b2 = Button(root, text = "2") b2.grid(row=1, column=4) f = Frame(root, bg = "red") f.pack(side=RIGHT) root.mainloop()
[ "Figured out a way to do it finally:\nfrom Tkinter import * \n\nroot = Tk()\n\nf = Frame(root, bg = \"orange\", width = 500, height = 500)\nf.pack(side=LEFT, expand = 1)\n\nf3 = Frame(f, bg = \"red\", width = 500)\nf3.pack(side=LEFT, expand = 1, pady = 50, padx = 50)\n\nf2 = Frame(root, bg = \"black\", height=100, width = 100)\nf2.pack(side=LEFT, fill = Y)\n\nb = Button(f2, text = \"test\")\nb.pack()\n\nb = Button(f3, text = \"1\", bg = \"red\")\nb.grid(row=1, column=3)\nb2 = Button(f3, text = \"2\")\nb2.grid(row=1, column=4)\nb3 = Button(f3, text = \"2\")\nb3.grid(row=2, column=0)\n\nroot.mainloop()\n\nHaving the grid inside a frame inside a frame is a bit of a hack to get the padding around the grid working but it works so I'm happy.\n", "You can nest Tk widgets arbitrarily deep. Quoth the manual:\n\nThe size of any master widget is\n determined by the size of the “slave\n widgets” inside. The packer is used to\n control where slave widgets appear\n inside the master into which they are\n packed. You can pack widgets into\n frames, and frames into other frames,\n in order to achieve the kind of layout\n you desire. Additionally, the\n arrangement is dynamically adjusted to\n accommodate incremental changes to the\n configuration, once it is packed.\n\nIndeed, a frame containing a (frame of buttons) and a label is how you must structure the layout you describe.\n" ]
[ 10, 1 ]
[]
[]
[ "frame", "grid", "python", "tkinter" ]
stackoverflow_0002763266_frame_grid_python_tkinter.txt
Q: I am using Python on Windows. How do I delete my script after it is run? I have written a Python script and compiled it into a MS Windows EXE file. I can modify the code, but how do I make it remove itself after running? A: I think the easiest solution is make an external .bat file that executes your exe file and deletes it when finished.
I am using Python on Windows. How do I delete my script after it is run?
I have written a Python script and compiled it into a MS Windows EXE file. I can modify the code, but how do I make it remove itself after running?
[ "I think the easiest solution is make an external .bat file that executes your exe file and deletes it when finished.\n" ]
[ 3 ]
[]
[]
[ "python", "scripting", "windows" ]
stackoverflow_0002763541_python_scripting_windows.txt
Q: Python: How to write data in file in specific format? i have an array called MAC1_Val: MAC1_Val array([ 1.00000000e+00, -1.00000000e+01, -2.06306600e+02, 2.22635749e+02, 1.00000000e+00, 1.00000000e+01, 1.00000000e+01, -2.06306600e+02, 2.22635749e+02, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, -1.08892735e+01, 1.88607749e+01, 1.03153300e+01, -1.78666757e+01, 3.33333333e-07, -3.33333333e-07, -4.21637021e-05, 4.21637021e-05, 9.98844400e-01, -1.73973001e-03, 1.20938900e-03, 1.87742948e-03, -3.33333333e-03, 6.66666667e-03, -3.33333333e-03, -2.64911064e-01, -2.60959501e+01, 2.81614422e+01, 3.33333333e-03, -6.66666667e-03, 3.33333333e-03, 0.00000000e+00, 0.00000000e+00]) and i want to write in file (.txt) values in specific format like this: 1.000000e+00 -1.000000e+01 -2.063066e+02 2.226357e+02 1.000000e+00 1.000000e+01 ....... note that are 6 digits behind floating point any suggestions how to do this? thanks in advance! A: printf standard is your friend: for i in MAC1_Val: print "%.6e" % i 1.000000e+00 -1.000000e+01 -2.063066e+02 2.226357e+02 1.000000e+00 1.000000e+01 1.000000e+01 A: Use string interpolation to format the number. '%.3f' % (1.23456,)
Python: How to write data in file in specific format?
i have an array called MAC1_Val: MAC1_Val array([ 1.00000000e+00, -1.00000000e+01, -2.06306600e+02, 2.22635749e+02, 1.00000000e+00, 1.00000000e+01, 1.00000000e+01, -2.06306600e+02, 2.22635749e+02, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, -1.08892735e+01, 1.88607749e+01, 1.03153300e+01, -1.78666757e+01, 3.33333333e-07, -3.33333333e-07, -4.21637021e-05, 4.21637021e-05, 9.98844400e-01, -1.73973001e-03, 1.20938900e-03, 1.87742948e-03, -3.33333333e-03, 6.66666667e-03, -3.33333333e-03, -2.64911064e-01, -2.60959501e+01, 2.81614422e+01, 3.33333333e-03, -6.66666667e-03, 3.33333333e-03, 0.00000000e+00, 0.00000000e+00]) and i want to write in file (.txt) values in specific format like this: 1.000000e+00 -1.000000e+01 -2.063066e+02 2.226357e+02 1.000000e+00 1.000000e+01 ....... note that are 6 digits behind floating point any suggestions how to do this? thanks in advance!
[ "printf standard is your friend:\nfor i in MAC1_Val:\n print \"%.6e\" % i\n\n1.000000e+00\n-1.000000e+01\n-2.063066e+02\n2.226357e+02\n1.000000e+00\n1.000000e+01\n1.000000e+01\n\n", "Use string interpolation to format the number.\n'%.3f' % (1.23456,)\n\n" ]
[ 2, 1 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0002763784_python_string_formatting.txt
Q: Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language? Is it guaranteed that False == 0 and True == 1, in Python (assuming that they are not reassigned by the user)? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever the version of Python (both existing and, likely, future ones)? 0 == False # True 1 == True # True ['zero', 'one'][False] # is 'zero' Any reference to the official documentation would be much appreciated! Edit: As noted in many answers, bool inherits from int. The question can therefore be recast as: "Does the documentation officially say that programmers can rely on booleans inheriting from integers, with the values 0 and 1?". This question is relevant for writing robust code that won't fail because of implementation details! A: In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons. In Python 3.x True and False are keywords and will always be equal to 1 and 0. Under normal circumstances in Python 2, and always in Python 3: False object is of type bool which is a subclass of int: object | int | bool It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__ method (thanks mark-dickinson). Edit: It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say: There are two types of integers: [...] Integers (int) [...] Booleans (bool) and in the boolean subsection: Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively. There is also, for Python 2: In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively. So booleans are explicitly considered as integers in Python 2 and 3. So you're safe until Python 4 comes along. ;-) A: Here's the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/. When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0. >>> int(False) 0 >>> int(True) 1 >>> bool(5) True >>> bool(-5) True >>> bool(0) False A: In Python 2.x, it is not guaranteed at all: >>> False = 5 >>> 0 == False False So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work. In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1, but on Python 3.x, this will always be the case, no matter what.
Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?
Is it guaranteed that False == 0 and True == 1, in Python (assuming that they are not reassigned by the user)? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever the version of Python (both existing and, likely, future ones)? 0 == False # True 1 == True # True ['zero', 'one'][False] # is 'zero' Any reference to the official documentation would be much appreciated! Edit: As noted in many answers, bool inherits from int. The question can therefore be recast as: "Does the documentation officially say that programmers can rely on booleans inheriting from integers, with the values 0 and 1?". This question is relevant for writing robust code that won't fail because of implementation details!
[ "In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.\nIn Python 3.x True and False are keywords and will always be equal to 1 and 0.\nUnder normal circumstances in Python 2, and always in Python 3:\nFalse object is of type bool which is a subclass of int:\n object\n |\n int\n |\n bool\n\nIt is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__ method (thanks mark-dickinson).\nEdit:\nIt is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:\n\nThere are two types of integers: [...] Integers (int) [...] Booleans (bool)\n\nand in the boolean subsection:\n\nBooleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings \"False\" or \"True\" are returned, respectively.\n\nThere is also, for Python 2:\n\nIn numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.\n\nSo booleans are explicitly considered as integers in Python 2 and 3.\nSo you're safe until Python 4 comes along. ;-)\n", "Here's the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.\nWhen converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.\n>>> int(False)\n0\n>>> int(True)\n1\n>>> bool(5)\nTrue\n>>> bool(-5)\nTrue\n>>> bool(0)\nFalse\n\n", "In Python 2.x, it is not guaranteed at all:\n>>> False = 5\n>>> 0 == False\nFalse\n\nSo it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.\nIn general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1, but on Python 3.x, this will always be the case, no matter what.\n" ]
[ 228, 84, 23 ]
[]
[]
[ "boolean", "equality", "language_specifications", "python" ]
stackoverflow_0002764017_boolean_equality_language_specifications_python.txt
Q: Python fCGI + sqlAlchemy = malformed header from script. Bad header=FROM tags : index.py I'm writing an Fast-CGI application that makes use of sqlAlchemy & MySQL for persistent data storage. I have no problem connecting to the DB and setting up ORM (so that tables get mapped to classes); I can even add data to tables (in memory). But, as soon as I query the DB (and push any changes from memory to storage) I get a 500 Internal Server Error and my error.log records malformed header from script. Bad header=FROM tags : index.py, when tags is the table name. Any idea what could be causing this? Also, I don't think it matters, but its a Linux development server talking to an off-site (across the country) MySQL server. A: Looks like SQLalchemy is pushing or echoing the query to your output (where fast-cgi) is instead looking for headers, then body. Maybe setting sqlalchemy.echo to False can help. A: Instead of setting echo=True you can configure logging to output debugging information. SQLAlchemy has very flexible loggers hierarchy. The following lines will enable logging of the same info as echo does: import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
Python fCGI + sqlAlchemy = malformed header from script. Bad header=FROM tags : index.py
I'm writing an Fast-CGI application that makes use of sqlAlchemy & MySQL for persistent data storage. I have no problem connecting to the DB and setting up ORM (so that tables get mapped to classes); I can even add data to tables (in memory). But, as soon as I query the DB (and push any changes from memory to storage) I get a 500 Internal Server Error and my error.log records malformed header from script. Bad header=FROM tags : index.py, when tags is the table name. Any idea what could be causing this? Also, I don't think it matters, but its a Linux development server talking to an off-site (across the country) MySQL server.
[ "Looks like SQLalchemy is pushing or echoing the query to your output (where fast-cgi) is instead looking for headers, then body. Maybe setting sqlalchemy.echo to False can help.\n", "Instead of setting echo=True you can configure logging to output debugging information. SQLAlchemy has very flexible loggers hierarchy. The following lines will enable logging of the same info as echo does:\nimport logging\n\nlogging.basicConfig()\nlogging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)\n\n" ]
[ 2, 0 ]
[]
[]
[ "apache", "fastcgi", "mysql", "python", "sqlalchemy" ]
stackoverflow_0002751957_apache_fastcgi_mysql_python_sqlalchemy.txt
Q: Python get raw_input but manually decide when string is done I want someone to type words in the console, and autocomplete from a list when they hit "tab" key. However, raw_input won't return a string until someone hits [Enter]. How do I read characters into a variable until the user hits [Enter]? *Note: I don't want to use import readline for autocompletion because of OS issues. A: There is an official FAQ entry on this question, for Unix: http://www.python.org/doc/faq/library/#how-do-i-get-a-single-keypress-at-a-time Edit (copied from Donal Fellows' comment below): "The problem is that the terminal is in “cooked” mode by default (allowing simple line editing) and that to get the keys as they're typed, it has to be placed in “raw” mode." (Thanks!) A: On *nix use select on sys.stdin to wait for a character, then .read() it in. On Windows use msvcrt.kbhit() and msvcrt.getch().
Python get raw_input but manually decide when string is done
I want someone to type words in the console, and autocomplete from a list when they hit "tab" key. However, raw_input won't return a string until someone hits [Enter]. How do I read characters into a variable until the user hits [Enter]? *Note: I don't want to use import readline for autocompletion because of OS issues.
[ "There is an official FAQ entry on this question, for Unix: http://www.python.org/doc/faq/library/#how-do-i-get-a-single-keypress-at-a-time\nEdit (copied from Donal Fellows' comment below): \"The problem is that the terminal is in “cooked” mode by default (allowing simple line editing) and that to get the keys as they're typed, it has to be placed in “raw” mode.\" (Thanks!)\n", "On *nix use select on sys.stdin to wait for a character, then .read() it in. On Windows use msvcrt.kbhit() and msvcrt.getch().\n" ]
[ 5, 1 ]
[]
[]
[ "console", "python", "user_input" ]
stackoverflow_0002764121_console_python_user_input.txt
Q: How do I read binary pickle data first, then unpickle it? I'm unpickling a NetworkX object that's about 1GB in size on disk. Although I saved it in the binary format (using protocol 2), it is taking a very long time to unpickle this file---at least half an hour. The system I'm running on has plenty of system memory (128 GB), so that's not the bottleneck. I've read here that pickling can be sped up by first reading the entire file into memory, and then unpickling it (that particular thread refers to python 3.0, which I'm not using, but the point should still be true in python 2.6). How do I first read the binary file, and then unpickle it? I have tried: import cPickle as pickle f = open("big_networkx_graph.pickle","rb") bin_data = f.read() graph_data = pickle.load(bin_data) But this returns: TypeError: argument must have 'read' and 'readline' attributes Any ideas? A: pickle.load(file) expects a file-like object. Instead, use: pickle.loads(string) Read a pickled object hierarchy from a string. Characters in the string past the pickled object’s representation are ignored. A: The documentation mentions StringIO, which I think is one possible solution. Try: f = open("big_networkx_graph.pickle","rb") bin_data = f.read() sio = StringIO(bin_data) graph_data = pickle.load(sio)
How do I read binary pickle data first, then unpickle it?
I'm unpickling a NetworkX object that's about 1GB in size on disk. Although I saved it in the binary format (using protocol 2), it is taking a very long time to unpickle this file---at least half an hour. The system I'm running on has plenty of system memory (128 GB), so that's not the bottleneck. I've read here that pickling can be sped up by first reading the entire file into memory, and then unpickling it (that particular thread refers to python 3.0, which I'm not using, but the point should still be true in python 2.6). How do I first read the binary file, and then unpickle it? I have tried: import cPickle as pickle f = open("big_networkx_graph.pickle","rb") bin_data = f.read() graph_data = pickle.load(bin_data) But this returns: TypeError: argument must have 'read' and 'readline' attributes Any ideas?
[ "pickle.load(file) expects a file-like object. Instead, use:\npickle.loads(string)\n\nRead a pickled object hierarchy from a string. Characters in the string past the pickled object’s representation are ignored.\n\n", "The documentation mentions StringIO, which I think is one possible solution.\nTry:\nf = open(\"big_networkx_graph.pickle\",\"rb\")\nbin_data = f.read()\nsio = StringIO(bin_data)\ngraph_data = pickle.load(sio)\n\n" ]
[ 8, 1 ]
[]
[]
[ "pickle", "python", "serialization" ]
stackoverflow_0002764237_pickle_python_serialization.txt
Q: How to decode javascript code within I would like to implement a Python script which has the same functionality as http://www.greymagic.com/security/tools/decoder/ Is the encoding rule open for this type of javascript code encoding? Thanks. An example of this: <Script LANGUAGE="JScript.Encode">#@~^TBQAAA==-mD~kk9P'8*R0%p\CD,wr[&fP{~xhPz..lH`EFTc+{W*v~Eq!W {*+B~vqZc+GW{E~v8!W GW%ESB8!* Fc1vBBFZ* F*!ESvFZcyGXFvSEFTcy{*yBSv8!c+{l&v~EqZc+F*WB~EFZ* F*XBBBqTW GlBBBFZ*+GlGE~vFT*yGX%ESB8!*+F*,vSEFTcy{+!vBB8!cyG+qBBBq!W {yB~Eq!W G+fv~EFZc+G*E~vFZ* FvXvBBFT*yGvESEFTW FvGE~Eq!W {vRBSv8!cy{vOB~EqTcyGF!v~vqZc+GFqBBBqTW G{+E~vFZ*yG{2BBBFZcy{GWBSB8!*+FG*ESB8!cy{{vE~EFTc+{FGv~Eq!W {{RB~vqZc+GF1E~v8!W GR!ESB8!* F%qvBBFZ* F% ESvFZcyG0&vSEFTcy{%WBSv8!c+{R*v~EqZc+F%+B~EFZ* F%{BBBqTW GR0BBBFZ*+GR,E~vFT*yG1!ESB8!*+F,FvSEFTcy{O vBB8!cyGOfBBBq!W {1WB~Eq!W GOXv~EFZc+G1E~vFZ* F,{vBBFT*yG1%ESEFTW F,,E~Eq!W 0!ZBSv8!cy0!8B~EqTcy%Z v~vqZc+%ZfBBBqTW %T*E~vFZ*y%TlBBBFZcy0!+BSB8!*+R!GESB8!cy0T%E~EFTc+0Z,v~Eq!W 0qZB~vqZc+%8qE~v8!W %8 ESB8!* RFfvBBFZ* RFcESvFZcy%q*vSEFTcy0F+BSv8!c+08Gv~EqZc+RFRB~EFZ* RF1BBBqTW %yTBBBFZ*+%yFE~vFT*y%+ ESB8!*+R &vSEFTcy0ycvBB8!cy%yXBBBq!W 0++B~Eq!W %y{v~EFZc+%+0E~vFZ* R 1vBBFT*y%f!ESEFTW R&FE~Eq!W 0&yBSv8!cy0&2B~EqTcy%2cv~vqZc+%2XBBBqTW %fE~vFZ*y%fFB*i\mD,2k1b.DmX~x,x+S~bMDlHcvtDYa)&z2r1Rhl 4Em* ^K:zo&6;^yM%J&0J!ZFRNwTv~EtOYa)&&akmchl tEmX mK:Js&05^.D%z20zZ!+ NwovSEtOYalJz2bmc:l t!C*cmG:Js&W$myM%z2%zZTfRNwTBSB4ODwlzJ2k1RhC tECXcmG:JoJ051yMLz2%JT!WR%wTBSv4YYalzJwk1 hl t!lXR^Gszoz65m.D%&2%zTTlR%wTvBB4DYa)zJwb^RslUt!lX 1W:Joz6;m..%z2%J!Tv %aov~E4YDwl&Jwk^ slUt!ClR^K:Jsz6;1"DNzf%J!T{cLwTv~EtYD2lzJwbm :CU4EC*c^Wszo&6;m".Nzf%JTZ% NwTB~EtDOw=z&wbm hmxt!C*cmWs&oz6;1y.L&fRzT!O LaovSEtYO2=z&wb^c:C t!l*cmKhzwzW;1y.%J&%JTFZRLaLv~EtDY2)&&ak^RsCx4ECXcmWh&wzW;1"ML&2%J!F8RN2oE~vtDY2lJzwb^Rslx4;C*cmK:&s&W$m"DN&&RzTqyRL2LE~vtDOa)&JwbmRsl 4Em* mK:&oJ0;1"DNz&R&TF2RNwLBSv4YOw=&zak^ slx4;m* mKhJs&6;1yDNz20zZF*RNwLvBBtDOw=zzar^Rsl t;lX 1Whzw&0$m".Nz&0&ZFXRN2TBSEtDYw=zJ2k1Rhl t;ClRmKhzwz0$^"DNz2%&!qcL2oESB4YO2=zz2r1Rhl 4!lXcmK:zwz65m.D%z2%&T8GRN2oE~B4OOw=zJwrm hmx4EmXR1Wh&wz05^.D%z20J!qRRNwoE~E4YDwlzJwr^c:l 4Em*R1Ghzwz6;^y.%J&0zZq,cL2LE~B4ODwlzJ2bm sl tEm*c^Wszoz6;^"MLz20zZ !c%2oE~EtOY2lJz2k1 :mx4;m*R^Gszoz651y.Nz2%zZ 8 Laov~EtOOa)zJ2k1R:mU4Em*cmG:&oJ05m..LJ&0&Z %aov~E4DY2=zJwk1RsCx4EC*cmGhJsz65m.DLJf0zZ 2R%wLvBB4YD2)Jz2r1R:CU4EC*c^K:&wz6;m.DN&&RzT WR%2TB~E4YDw)J&2k1RslUt;ClR^Ws&sJ05^.DL&fRzT l NwLE~EtYDw=&zak^RslU4!l*c^WszsJW5m.DNzf%&Tyv LaLBBB4ODw)&&ak^RsC t;m*cmWszw&0$m"DNzf0J! F LaoBBv4YDw=z&wr^c:Cx4;llR^Gszs&W$m"DN&2%&Z RRLaoESB4YOw=z&2bmRsCx4Ell ^WszwzW;^"ML&&R&!y, %aoBSv4YOw=&Jwr1Rslx4EmXR1WhzwzW51yDN&&Rz!2T LaoE~vtOOa)&zarmc:CU4ElX 1Whzw&6;^.DNz&RzZfFcL2oE~v4DYw=&zakmchCx4Em* mGhJs&0$^yML&fRz!f+cL2oESEtODw=zzak1 :mx4Em* ^K:zw&0$myM%&&RzZ&fR%2TBSB4OYa)&&akm hmx4EmXcmGszwz0$m..LJ&0zZ&* NwoESB4YYal&zak1RhlU4!lXR1G:Js&W$my.%J&0zZflR%aoE~B4YD2)Jz2k1RhC tEmXR1W:Jo&0$m.D%zf0J!fvc%wTBSv4YY2lJz2k1 slU4Em*R1Ws&sJ05m.D%&2%zZfGcLwTvSB4YDwlz&2bm :mUt!lX 1W:&oJ05m..NzfRzZ&%cLaLBBB4YDwl&Jwk1 :mxt!CXR1WszozW51y.LJf%J!f1cLwLvBB4YD2=z&ak1R:mx4;llR^Wszo&6;m..LJ&%JT*!cLaov~v4DY2)J&wbm hmxt;ClR^Ws&wzW$m.DLJ&R&!WF LaovSEtYD2)Jzwb^ :mx4EC* ^K:&sJW;1y.%J&%&TW LaLE~v4YDw)Jzarmc:Cx4ECXcmWs&sJ0;1".LJ&RzTcf NwLBBvtDY2lJzwr^c:Cx4;m* 1WszsJ0$^yML&&RzT*WRLaLBBBtDO2)Jzak^RhC t;ll mK:&oJ0;^"ML&&R&ZcXcLaoBBB4OYa)&zak^ slx4;llRmKh&sJ0$m"D%&2%&!WRNwLvBBtOOa)&zar1Rhmx4EllR1G:Js&0$m".Nz&R&!WGRN2LBBB4YOwl&Jwrmchl t;ClRmGhJs&0$^.D%J&Rz!W%c%wTBSB4YO2=zzarmc:l 4;llR1Whzo&6;^yM%z2%&TW,R%2TBSB4ODwlJzakmc:mUt!lXR1Wh&wz0$^yMLz20&!l!cL2ovSEtOYalzJwr^c:lU4!lXR1GszoJ0$myMLJf%J!XFcL2LE~B4OYa)zJ2rmc:mx4ECXcmG:Joz6;^"MLzf0J!X c%aovBB4YYa)J&wbm :mx4;m*R1G:Jsz65^yMLJ&0zTX2R%wTv~EtOOa)z&2bm :mU4EClR1W:JsJW;1y.LJ&0&Z*cc%wTB~E4OYa)Jz2k^ slUt!C*cmGhJszW51y.LJfRzTl*cLwTBBvtDY2)Jz2r1R:mUt!l*c^G:JsJ05m".Nzf%JT*+R%2TB~v4DY2)J&ak^c:mxt!ll mK:&sJ05^.DLJf%J!*F %wTBBB4YO2=z&wb^RslU4!l* ^K:&sJW$m"MLJ&%J!l0RNwLBBB4ODw)J&wbmRsCUt!llR^Wh&wzW;1"DNzf0J!*1 NwLBBv4YOa)Jzwbmchl t;llR^GszsJW;1yDN&f%J!+! L2LE~vtDOw=z&2bmRhC t;ll 1WhJsJ0;1yM%z2%&!+F %aoBBvtDYw=&&wbmc:Cx4;m* mKhzwzW51yD%&2%&!++cL2TBBBtDYalzJwrmc:CU4Ell mK:zw&W;1yML&&0&ZvfRN2oE~v4DYwl&Jwrmchmx4!llRmK:Joz6;^yML&fRz!+*RNwoESvtDYa)&z2r1Rhl 4Em* ^K:zo&6;^yM%J&0J!+*RNwTv~EtOYa)&&akmchl tEmX mK:Js&05^.D%z20zZv NwovSEtOYalJz2bmc:l t!C*cmG:Js&W$myM%z2%zZ{RNwTBSB4ODwlzJ2k1RhC tECXcmG:JoJ051yMLz2%JTvRR%wTBSv4YYalzJwk1 hl t!lXR^Gszoz65m.D%&2%zTOR%wTvBB4DYa)zJwb^RslUt!lX 1W:Joz6;m..%z2%J!{! %aov~E4YDwl&Jwk^ slUt!ClR^K:Jsz6;1"DNzf%J!{qcLwTv~EtYD2lzJwbm :CU4EC*c^Wszo&6;m".Nzf%JTF NwTB~EtDOw=z&wbm hmxt!C*cmWs&oz6;1y.L&fRzTG2 LaovSEtYO2=z&wb^c:C t!l*cmKhzwzW;1y.%J&%JTGWRLaLv~EtDY2)&&ak^RsCx4ECXcmWh&wzW;1"ML&2%J!GlRN2oE~vtDY2lJzwb^Rslx4;C*cmK:&s&W$m"DN&&RzT{+RL2LE~vtDOa)&JwbmRsl 4Em* mK:&oJ0;1"DNz&R&TGFRNwLBSv4YOw=&zak^ slx4;m* mKhJs&6;1yDNz20zZG0RNwLvBBtDOw=zzar^Rsl t;lX 1Whzw&0$m".Nz&0&ZG1RN2TBSEtDYw=zJ2k1Rhl t;ClRmKhzwz0$^"DNz2%&!0TcL2oESB4YO2=zz2r1Rhl 4!lXcmK:zwz65m.D%z2%&TRFRN2oE~B4OOw=zJwrm hmx4EmXR1Wh&wz05^.D%z20J!0yRNwoE~E4YDwlzJwr^c:l4Em*R1Ghzwz6;^y.%J&0zZ0&cL2LE~B4ODwlzJ2bm sl tEm*c^Wszoz6;^"MLz20zZ%cc%2oE~EtOY2lJz2k1 :mx4;m*R^Gszoz651y.Nz2%zZ%l Laov~EtOOa)zJ2k1R:mU4Em*cmG:&oJ05m..LJ&0&Z%v %aov~E4DY2=zJwk1RsCx4EC*cmGhJsz65m.DLJf0zZ%FR%wLvBB4YD2)Jz2r1R:CU4EC*c^K:&wz6;m.DN&&RzT%RR%2TB~E4YDw)J&2k1RslUt;ClR^Ws&sJ05^.DL&fRzT%O NwLE~EtYDw=&zak^RslU4!l*c^WszsJW5m.DNzf%&TO! LaLBBB4ODw)&&ak^RsC t;m*cmWszw&0$m"DNzf0J!,8 LaoBBv4YDw=z&wr^c:Cx4;llR^Gszs&W$m"DN&2%&Z,yRLaoESB4YOw=z&2bmRsCx4Ell ^WszwzW;^"ML&&R&!O& %aoBbI7l.Par11;sP{P,2i,YwAGAA==^#~@</Script> A: No, its not open, its just broken. Google "windows script decoder" for examples.
How to decode javascript code within
I would like to implement a Python script which has the same functionality as http://www.greymagic.com/security/tools/decoder/ Is the encoding rule open for this type of javascript code encoding? Thanks. An example of this: <Script LANGUAGE="JScript.Encode">#@~^TBQAAA==-mD~kk9P'8*R0%p\CD,wr[&fP{~xhPz..lH`EFTc+{W*v~Eq!W {*+B~vqZc+GW{E~v8!W GW%ESB8!* Fc1vBBFZ* F*!ESvFZcyGXFvSEFTcy{*yBSv8!c+{l&v~EqZc+F*WB~EFZ* F*XBBBqTW GlBBBFZ*+GlGE~vFT*yGX%ESB8!*+F*,vSEFTcy{+!vBB8!cyG+qBBBq!W {yB~Eq!W G+fv~EFZc+G*E~vFZ* FvXvBBFT*yGvESEFTW FvGE~Eq!W {vRBSv8!cy{vOB~EqTcyGF!v~vqZc+GFqBBBqTW G{+E~vFZ*yG{2BBBFZcy{GWBSB8!*+FG*ESB8!cy{{vE~EFTc+{FGv~Eq!W {{RB~vqZc+GF1E~v8!W GR!ESB8!* F%qvBBFZ* F% ESvFZcyG0&vSEFTcy{%WBSv8!c+{R*v~EqZc+F%+B~EFZ* F%{BBBqTW GR0BBBFZ*+GR,E~vFT*yG1!ESB8!*+F,FvSEFTcy{O vBB8!cyGOfBBBq!W {1WB~Eq!W GOXv~EFZc+G1E~vFZ* F,{vBBFT*yG1%ESEFTW F,,E~Eq!W 0!ZBSv8!cy0!8B~EqTcy%Z v~vqZc+%ZfBBBqTW %T*E~vFZ*y%TlBBBFZcy0!+BSB8!*+R!GESB8!cy0T%E~EFTc+0Z,v~Eq!W 0qZB~vqZc+%8qE~v8!W %8 ESB8!* RFfvBBFZ* RFcESvFZcy%q*vSEFTcy0F+BSv8!c+08Gv~EqZc+RFRB~EFZ* RF1BBBqTW %yTBBBFZ*+%yFE~vFT*y%+ ESB8!*+R &vSEFTcy0ycvBB8!cy%yXBBBq!W 0++B~Eq!W %y{v~EFZc+%+0E~vFZ* R 1vBBFT*y%f!ESEFTW R&FE~Eq!W 0&yBSv8!cy0&2B~EqTcy%2cv~vqZc+%2XBBBqTW %fE~vFZ*y%fFB*i\mD,2k1b.DmX~x,x+S~bMDlHcvtDYa)&z2r1Rhl 4Em* ^K:zo&6;^yM%J&0J!ZFRNwTv~EtOYa)&&akmchl tEmX mK:Js&05^.D%z20zZ!+ NwovSEtOYalJz2bmc:l t!C*cmG:Js&W$myM%z2%zZTfRNwTBSB4ODwlzJ2k1RhC tECXcmG:JoJ051yMLz2%JT!WR%wTBSv4YYalzJwk1 hl t!lXR^Gszoz65m.D%&2%zTTlR%wTvBB4DYa)zJwb^RslUt!lX 1W:Joz6;m..%z2%J!Tv %aov~E4YDwl&Jwk^ slUt!ClR^K:Jsz6;1"DNzf%J!T{cLwTv~EtYD2lzJwbm :CU4EC*c^Wszo&6;m".Nzf%JTZ% NwTB~EtDOw=z&wbm hmxt!C*cmWs&oz6;1y.L&fRzT!O LaovSEtYO2=z&wb^c:C t!l*cmKhzwzW;1y.%J&%JTFZRLaLv~EtDY2)&&ak^RsCx4ECXcmWh&wzW;1"ML&2%J!F8RN2oE~vtDY2lJzwb^Rslx4;C*cmK:&s&W$m"DN&&RzTqyRL2LE~vtDOa)&JwbmRsl 4Em* mK:&oJ0;1"DNz&R&TF2RNwLBSv4YOw=&zak^ slx4;m* mKhJs&6;1yDNz20zZF*RNwLvBBtDOw=zzar^Rsl t;lX 1Whzw&0$m".Nz&0&ZFXRN2TBSEtDYw=zJ2k1Rhl t;ClRmKhzwz0$^"DNz2%&!qcL2oESB4YO2=zz2r1Rhl 4!lXcmK:zwz65m.D%z2%&T8GRN2oE~B4OOw=zJwrm hmx4EmXR1Wh&wz05^.D%z20J!qRRNwoE~E4YDwlzJwr^c:l 4Em*R1Ghzwz6;^y.%J&0zZq,cL2LE~B4ODwlzJ2bm sl tEm*c^Wszoz6;^"MLz20zZ !c%2oE~EtOY2lJz2k1 :mx4;m*R^Gszoz651y.Nz2%zZ 8 Laov~EtOOa)zJ2k1R:mU4Em*cmG:&oJ05m..LJ&0&Z %aov~E4DY2=zJwk1RsCx4EC*cmGhJsz65m.DLJf0zZ 2R%wLvBB4YD2)Jz2r1R:CU4EC*c^K:&wz6;m.DN&&RzT WR%2TB~E4YDw)J&2k1RslUt;ClR^Ws&sJ05^.DL&fRzT l NwLE~EtYDw=&zak^RslU4!l*c^WszsJW5m.DNzf%&Tyv LaLBBB4ODw)&&ak^RsC t;m*cmWszw&0$m"DNzf0J! F LaoBBv4YDw=z&wr^c:Cx4;llR^Gszs&W$m"DN&2%&Z RRLaoESB4YOw=z&2bmRsCx4Ell ^WszwzW;^"ML&&R&!y, %aoBSv4YOw=&Jwr1Rslx4EmXR1WhzwzW51yDN&&Rz!2T LaoE~vtOOa)&zarmc:CU4ElX 1Whzw&6;^.DNz&RzZfFcL2oE~v4DYw=&zakmchCx4Em* mGhJs&0$^yML&fRz!f+cL2oESEtODw=zzak1 :mx4Em* ^K:zw&0$myM%&&RzZ&fR%2TBSB4OYa)&&akm hmx4EmXcmGszwz0$m..LJ&0zZ&* NwoESB4YYal&zak1RhlU4!lXR1G:Js&W$my.%J&0zZflR%aoE~B4YD2)Jz2k1RhC tEmXR1W:Jo&0$m.D%zf0J!fvc%wTBSv4YY2lJz2k1 slU4Em*R1Ws&sJ05m.D%&2%zZfGcLwTvSB4YDwlz&2bm :mUt!lX 1W:&oJ05m..NzfRzZ&%cLaLBBB4YDwl&Jwk1 :mxt!CXR1WszozW51y.LJf%J!f1cLwLvBB4YD2=z&ak1R:mx4;llR^Wszo&6;m..LJ&%JT*!cLaov~v4DY2)J&wbm hmxt;ClR^Ws&wzW$m.DLJ&R&!WF LaovSEtYD2)Jzwb^ :mx4EC* ^K:&sJW;1y.%J&%&TW LaLE~v4YDw)Jzarmc:Cx4ECXcmWs&sJ0;1".LJ&RzTcf NwLBBvtDY2lJzwr^c:Cx4;m* 1WszsJ0$^yML&&RzT*WRLaLBBBtDO2)Jzak^RhC t;ll mK:&oJ0;^"ML&&R&ZcXcLaoBBB4OYa)&zak^ slx4;llRmKh&sJ0$m"D%&2%&!WRNwLvBBtOOa)&zar1Rhmx4EllR1G:Js&0$m".Nz&R&!WGRN2LBBB4YOwl&Jwrmchl t;ClRmGhJs&0$^.D%J&Rz!W%c%wTBSB4YO2=zzarmc:l 4;llR1Whzo&6;^yM%z2%&TW,R%2TBSB4ODwlJzakmc:mUt!lXR1Wh&wz0$^yMLz20&!l!cL2ovSEtOYalzJwr^c:lU4!lXR1GszoJ0$myMLJf%J!XFcL2LE~B4OYa)zJ2rmc:mx4ECXcmG:Joz6;^"MLzf0J!X c%aovBB4YYa)J&wbm :mx4;m*R1G:Jsz65^yMLJ&0zTX2R%wTv~EtOOa)z&2bm :mU4EClR1W:JsJW;1y.LJ&0&Z*cc%wTB~E4OYa)Jz2k^ slUt!C*cmGhJszW51y.LJfRzTl*cLwTBBvtDY2)Jz2r1R:mUt!l*c^G:JsJ05m".Nzf%JT*+R%2TB~v4DY2)J&ak^c:mxt!ll mK:&sJ05^.DLJf%J!*F %wTBBB4YO2=z&wb^RslU4!l* ^K:&sJW$m"MLJ&%J!l0RNwLBBB4ODw)J&wbmRsCUt!llR^Wh&wzW;1"DNzf0J!*1 NwLBBv4YOa)Jzwbmchl t;llR^GszsJW;1yDN&f%J!+! L2LE~vtDOw=z&2bmRhC t;ll 1WhJsJ0;1yM%z2%&!+F %aoBBvtDYw=&&wbmc:Cx4;m* mKhzwzW51yD%&2%&!++cL2TBBBtDYalzJwrmc:CU4Ell mK:zw&W;1yML&&0&ZvfRN2oE~v4DYwl&Jwrmchmx4!llRmK:Joz6;^yML&fRz!+*RNwoESvtDYa)&z2r1Rhl 4Em* ^K:zo&6;^yM%J&0J!+*RNwTv~EtOYa)&&akmchl tEmX mK:Js&05^.D%z20zZv NwovSEtOYalJz2bmc:l t!C*cmG:Js&W$myM%z2%zZ{RNwTBSB4ODwlzJ2k1RhC tECXcmG:JoJ051yMLz2%JTvRR%wTBSv4YYalzJwk1 hl t!lXR^Gszoz65m.D%&2%zTOR%wTvBB4DYa)zJwb^RslUt!lX 1W:Joz6;m..%z2%J!{! %aov~E4YDwl&Jwk^ slUt!ClR^K:Jsz6;1"DNzf%J!{qcLwTv~EtYD2lzJwbm :CU4EC*c^Wszo&6;m".Nzf%JTF NwTB~EtDOw=z&wbm hmxt!C*cmWs&oz6;1y.L&fRzTG2 LaovSEtYO2=z&wb^c:C t!l*cmKhzwzW;1y.%J&%JTGWRLaLv~EtDY2)&&ak^RsCx4ECXcmWh&wzW;1"ML&2%J!GlRN2oE~vtDY2lJzwb^Rslx4;C*cmK:&s&W$m"DN&&RzT{+RL2LE~vtDOa)&JwbmRsl 4Em* mK:&oJ0;1"DNz&R&TGFRNwLBSv4YOw=&zak^ slx4;m* mKhJs&6;1yDNz20zZG0RNwLvBBtDOw=zzar^Rsl t;lX 1Whzw&0$m".Nz&0&ZG1RN2TBSEtDYw=zJ2k1Rhl t;ClRmKhzwz0$^"DNz2%&!0TcL2oESB4YO2=zz2r1Rhl 4!lXcmK:zwz65m.D%z2%&TRFRN2oE~B4OOw=zJwrm hmx4EmXR1Wh&wz05^.D%z20J!0yRNwoE~E4YDwlzJwr^c:l4Em*R1Ghzwz6;^y.%J&0zZ0&cL2LE~B4ODwlzJ2bm sl tEm*c^Wszoz6;^"MLz20zZ%cc%2oE~EtOY2lJz2k1 :mx4;m*R^Gszoz651y.Nz2%zZ%l Laov~EtOOa)zJ2k1R:mU4Em*cmG:&oJ05m..LJ&0&Z%v %aov~E4DY2=zJwk1RsCx4EC*cmGhJsz65m.DLJf0zZ%FR%wLvBB4YD2)Jz2r1R:CU4EC*c^K:&wz6;m.DN&&RzT%RR%2TB~E4YDw)J&2k1RslUt;ClR^Ws&sJ05^.DL&fRzT%O NwLE~EtYDw=&zak^RslU4!l*c^WszsJW5m.DNzf%&TO! LaLBBB4ODw)&&ak^RsC t;m*cmWszw&0$m"DNzf0J!,8 LaoBBv4YDw=z&wr^c:Cx4;llR^Gszs&W$m"DN&2%&Z,yRLaoESB4YOw=z&2bmRsCx4Ell ^WszwzW;^"ML&&R&!O& %aoBbI7l.Par11;sP{P,2i,YwAGAA==^#~@</Script>
[ "No, its not open, its just broken. Google \"windows script decoder\" for examples.\n" ]
[ 1 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0002764229_javascript_python.txt
Q: making urllib request in Python from the client side I've written a Python application that makes web requests using the urllib2 library after which it scrapes the data. I could deploy this as a web application which means all urllib2 requests go through my web-server. This leads to the danger of the server's IP being banned due to the high number of web requests for many users. The other option is to create an desktop application which I don't want to do. Is there any way I could deploy my application so that I can get my web-requests through the client side. One way was to use Jython to create an applet but I've read that Java applets can only make web-requests to the server it is deployed on and the only way to to circumvent this is to create a server side proxy which leads us back to the problem of the server's ip getting banned. This might sounds sound like and impossible situation and I'll probably end up creating a desktop application but I thought I'd ask if anyone knew of an alternate solution. Thanks. A: You probably can use AJAX requests made from JavaScript that is a part of client-side. Use server → client communication to give commands and necessary data to make a request …and use AJAX communication from client to 3rd party server then. A: You can use a signed Java applet, they can use the Java security mechanism to enable access to any site. This tutorial explains exactly what you have to do: http://www-personal.umich.edu/~lsiden/tutorials/signed-applet/signed-applet.html The same might be possible from a Flash applet. Javascript is also restricted to the published site and doesn't allow being signed or security exceptions like this, AFAIK. A: This depends on the form of "scraping" you intend to do: You might run into problems running an AJAX call to a third-party site. Please see Screen scraping through AJAX and javascript. An alternative would be to do it server-side, but to cache the results so that you don't hit the third-party server unnecessarily. Check out diggstripper on google code.
making urllib request in Python from the client side
I've written a Python application that makes web requests using the urllib2 library after which it scrapes the data. I could deploy this as a web application which means all urllib2 requests go through my web-server. This leads to the danger of the server's IP being banned due to the high number of web requests for many users. The other option is to create an desktop application which I don't want to do. Is there any way I could deploy my application so that I can get my web-requests through the client side. One way was to use Jython to create an applet but I've read that Java applets can only make web-requests to the server it is deployed on and the only way to to circumvent this is to create a server side proxy which leads us back to the problem of the server's ip getting banned. This might sounds sound like and impossible situation and I'll probably end up creating a desktop application but I thought I'd ask if anyone knew of an alternate solution. Thanks.
[ "You probably can use AJAX requests made from JavaScript that is a part of client-side.\n\nUse server → client communication to give commands and necessary data to make a request\n…and use AJAX communication from client to 3rd party server then.\n\n", "You can use a signed Java applet, they can use the Java security mechanism to enable access to any site.\nThis tutorial explains exactly what you have to do: http://www-personal.umich.edu/~lsiden/tutorials/signed-applet/signed-applet.html\nThe same might be possible from a Flash applet. Javascript is also restricted to the published site and doesn't allow being signed or security exceptions like this, AFAIK.\n", "This depends on the form of \"scraping\" you intend to do:\n\nYou might run into problems running an AJAX call to a third-party site. Please see Screen scraping through AJAX and javascript.\nAn alternative would be to do it server-side, but to cache the results so that you don't hit the third-party server unnecessarily.\n\nCheck out diggstripper on google code.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0002763274_python_urllib_urllib2.txt
Q: Is there a neater way to get the first occurrence of something? I have a list which contains a number of things: lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar'] I'd like to get the first item in the list that fulfils a predicate, say len(item) > 2. Is there a neater way to do it than itertools' dropwhile and next? first = next(itertools.dropwhile(lambda x: len(x) <= 2, lista)) I did use [item for item in lista if len(item)>2][0] at first, but that requires python to generate the entire list first. A: >>> lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar'] >>> next(i for i in lista if len(i) > 2) 'foo'
Is there a neater way to get the first occurrence of something?
I have a list which contains a number of things: lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar'] I'd like to get the first item in the list that fulfils a predicate, say len(item) > 2. Is there a neater way to do it than itertools' dropwhile and next? first = next(itertools.dropwhile(lambda x: len(x) <= 2, lista)) I did use [item for item in lista if len(item)>2][0] at first, but that requires python to generate the entire list first.
[ ">>> lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']\n>>> next(i for i in lista if len(i) > 2)\n'foo'\n\n" ]
[ 6 ]
[]
[]
[ "iterator", "python", "python_itertools" ]
stackoverflow_0002764328_iterator_python_python_itertools.txt
Q: How can I handle dynamic calculated attributes in a model in Django? In Django I calculate the breadcrumb (a list of fathers) for an geographical object. Since it is not going to change very often, I am thinking of pre calculating it once the object is saved or initialized. 1.) What would be better? Which solution would have a better performance? To calculate it at ____init____ or to calculate it when the object is saved (the object takes about 500-2000 characters in the DB)? 2.) I tried to overwrite the ____init____ or save() methods but I don't know how to use attributes of the just saved object. Accessing *args, **kwargs did not work. How can I access them? Do I have to save, access the father and then save again? 3.) If I decide to save the breadcrumb. Whats the best way to do it? I used http://www.djangosnippets.org/snippets/1694/ and have crumb = PickledObjectField(). The model: class GeoObject(models.Model): name = models.CharField('Name',max_length=30) father = models.ForeignKey('self', related_name = 'geo_objects') crumb = PickledObjectField() # more attributes... Thats the method to calculate the attribute crumb() def _breadcrumb(self): breadcrumb = [ ] x = self while True: x = x.father try: if hasattr(x, 'country'): breadcrumb.append(x.country) elif hasattr(x, 'region'): breadcrumb.append(x.region) elif hasattr(x, 'city'): breadcrumb.append(x.city) else: break except: break breadcrumb.reverse() return breadcrumb Thats my save-Method: def save(self,*args, **kwargs): # how can I access the father ob the object? father = self.father # does obviously not work father = kwargs['father'] # does not work either # the breadcrumb gets calculated here self.crumb = self._breadcrumb(father) super(GeoObject, self).save(*args,**kwargs) Please help me out. I am working on this for days now. Thank you. A: By calling both the _breadcrumb method with x.father and assigning x = x.father in the beginning of the while loop you jump over one father. Try exchanging self.crumb = self._breadcrumb(father) with self.crumb = self._breadcrumb(self) By defining _breadcrumb within the model class you can clean it up like this: class GeoObject(models.Model): name = models.CharField('Name',max_length=30) father = models.ForeignKey('self', related_name = 'geo_objects') crumb = PickledObjectField() # more attributes... def _breadcrumb(self): ... return breadcrumb def save(self,*args, **kwargs): self.crumb = self._breadcrumb() super(GeoObject, self).save(*args,**kwargs) For more complex hierachies I recomend django-treebeard
How can I handle dynamic calculated attributes in a model in Django?
In Django I calculate the breadcrumb (a list of fathers) for an geographical object. Since it is not going to change very often, I am thinking of pre calculating it once the object is saved or initialized. 1.) What would be better? Which solution would have a better performance? To calculate it at ____init____ or to calculate it when the object is saved (the object takes about 500-2000 characters in the DB)? 2.) I tried to overwrite the ____init____ or save() methods but I don't know how to use attributes of the just saved object. Accessing *args, **kwargs did not work. How can I access them? Do I have to save, access the father and then save again? 3.) If I decide to save the breadcrumb. Whats the best way to do it? I used http://www.djangosnippets.org/snippets/1694/ and have crumb = PickledObjectField(). The model: class GeoObject(models.Model): name = models.CharField('Name',max_length=30) father = models.ForeignKey('self', related_name = 'geo_objects') crumb = PickledObjectField() # more attributes... Thats the method to calculate the attribute crumb() def _breadcrumb(self): breadcrumb = [ ] x = self while True: x = x.father try: if hasattr(x, 'country'): breadcrumb.append(x.country) elif hasattr(x, 'region'): breadcrumb.append(x.region) elif hasattr(x, 'city'): breadcrumb.append(x.city) else: break except: break breadcrumb.reverse() return breadcrumb Thats my save-Method: def save(self,*args, **kwargs): # how can I access the father ob the object? father = self.father # does obviously not work father = kwargs['father'] # does not work either # the breadcrumb gets calculated here self.crumb = self._breadcrumb(father) super(GeoObject, self).save(*args,**kwargs) Please help me out. I am working on this for days now. Thank you.
[ "By calling both the _breadcrumb method with x.father and assigning x = x.father in the beginning of the while loop you jump over one father. Try exchanging \nself.crumb = self._breadcrumb(father) \n\nwith\nself.crumb = self._breadcrumb(self)\n\nBy defining _breadcrumb within the model class you can clean it up like this:\nclass GeoObject(models.Model):\n name = models.CharField('Name',max_length=30)\n father = models.ForeignKey('self', related_name = 'geo_objects')\n crumb = PickledObjectField()\n # more attributes...\n\n def _breadcrumb(self):\n ...\n return breadcrumb\n\n def save(self,*args, **kwargs):\n self.crumb = self._breadcrumb()\n super(GeoObject, self).save(*args,**kwargs)\n\nFor more complex hierachies I recomend django-treebeard \n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_signals", "oop", "python" ]
stackoverflow_0002763623_django_django_models_django_signals_oop_python.txt
Q: Not enough arguments for format string I have such code in Python: def send_start(self, player): for p in self.players: player["socket"].send_cmd('<player id="%s" name="%s" you="%s" avatar="*.png" bank="%s" />'%(self.players.index(p)+1, p['name'], int(player["pid"]==p["pid"]), 0)) player["socket"].send_cmd('<game playerid="%s" />'%(self.turnnow)) player["socket"].send_cmd("<start />") And the error is in the title of this post. What's wrong? A: Your code would fail if self.turnnow is an empty tuple: >>> var = () >>> print "%s" % (var) Traceback (most recent call last): File "<stdin>", line 2, in <module> TypeError: not enough arguments for format string >>> print "%s" % (var,) () This is because a parenthesized expression in Python does not automatically become a tuple if the tuple would have only one element. (expr) is equivalent to expr. (expr, ) is equivalent to a one-element tuple holding expr as the first element. So, try adding a comma after self.turnnow in the second print statement. A: EDIT: Disregard this answer, it cannot be the problem. Keeping for the comments. Try if replacing (self.turnnow) with (self.turnnow,) helps (i.e. adding a trailing comma). The way it is now that's not a tuple and parens are merely decorative. Might not be the case since you didn't provide line number — have to guess.
Not enough arguments for format string
I have such code in Python: def send_start(self, player): for p in self.players: player["socket"].send_cmd('<player id="%s" name="%s" you="%s" avatar="*.png" bank="%s" />'%(self.players.index(p)+1, p['name'], int(player["pid"]==p["pid"]), 0)) player["socket"].send_cmd('<game playerid="%s" />'%(self.turnnow)) player["socket"].send_cmd("<start />") And the error is in the title of this post. What's wrong?
[ "Your code would fail if self.turnnow is an empty tuple:\n>>> var = ()\n>>> print \"%s\" % (var)\nTraceback (most recent call last):\n File \"<stdin>\", line 2, in <module>\nTypeError: not enough arguments for format string\n>>> print \"%s\" % (var,)\n()\n\nThis is because a parenthesized expression in Python does not automatically become a tuple if the tuple would have only one element. (expr) is equivalent to expr. (expr, ) is equivalent to a one-element tuple holding expr as the first element. So, try adding a comma after self.turnnow in the second print statement.\n", "EDIT: Disregard this answer, it cannot be the problem. Keeping for the comments.\nTry if replacing\n(self.turnnow)\n\nwith\n(self.turnnow,)\n\nhelps (i.e. adding a trailing comma). The way it is now that's not a tuple and parens are merely decorative. Might not be the case since you didn't provide line number — have to guess.\n" ]
[ 18, 4 ]
[]
[]
[ "format", "python" ]
stackoverflow_0002764520_format_python.txt
Q: how to traverse a file in python and c++ in backward way? And also store data in backward (bottom to top) way? Suppose i want to store 3 lines in a file both in python and C++ . I want to store it like this aaa bbb ccc .. But i am giving ccc input first then bbb then aaa. How will I traverse the file from bottom to top and also store from bottom to top/? A: It isn't obvious from the title and question whether you want to store to a file, load from a file, or both, so I'll cover both cases: Reading If it's OK to load it all into memory at once (in Python): list(reversed(list(open('foo.txt')))) Otherwise, it gets a lot more difficult. Processing a file backwards requires that you read blocks of data a time from the end, scanning backwards through each block for newline marker, and stitching things back together at block boundaries. Writing If the data all fit in memory at once, put the numbers into a list (in Python): open('foo.txt', 'w').writelines(reversed(data)) If data is an iterable, replace it with list(data). If the data doesn't fit in memory (e.g., you have some generator that spits out a ton of data), the problem will be much harder. The simplest solution that comes to mind is to just push the data into a sqlite database and then copy it into the file. Or you might just find it easier to use the data directly from sqlite. A: You might want to use a collections.deque. Afaik those things are optimised for insertion at one of their endpoints, so you could read your file as it is and fill the lines into a deque object with its appendleft method ... just a thought. No idea how efficient that would be. :) A: Insert the lines to be generated at the beginning of your linear structure (list, vector<string>) each time, then iterate your structure from beginning to end.
how to traverse a file in python and c++ in backward way? And also store data in backward (bottom to top) way?
Suppose i want to store 3 lines in a file both in python and C++ . I want to store it like this aaa bbb ccc .. But i am giving ccc input first then bbb then aaa. How will I traverse the file from bottom to top and also store from bottom to top/?
[ "It isn't obvious from the title and question whether you want to store to a file, load from a file, or both, so I'll cover both cases:\nReading\nIf it's OK to load it all into memory at once (in Python):\nlist(reversed(list(open('foo.txt'))))\n\nOtherwise, it gets a lot more difficult. Processing a file backwards requires that you read blocks of data a time from the end, scanning backwards through each block for newline marker, and stitching things back together at block boundaries.\nWriting\nIf the data all fit in memory at once, put the numbers into a list (in Python):\nopen('foo.txt', 'w').writelines(reversed(data))\n\nIf data is an iterable, replace it with list(data).\nIf the data doesn't fit in memory (e.g., you have some generator that spits out a ton of data), the problem will be much harder. The simplest solution that comes to mind is to just push the data into a sqlite database and then copy it into the file. Or you might just find it easier to use the data directly from sqlite.\n", "You might want to use a collections.deque. Afaik those things are optimised for insertion at one of their endpoints, so you could read your file as it is and fill the lines into a deque object with its appendleft method ... just a thought. No idea how efficient that would be. :)\n", "Insert the lines to be generated at the beginning of your linear structure (list, vector<string>) each time, then iterate your structure from beginning to end.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0002764607_c++_python.txt
Q: what is the correct way to close a socket in python 2.6? i have a simple server/client. and i am using the netcat as the client to test the server. if i stop the server before the client exit, i will not be able to start the server again for a while and i go this error: " [Errno 98] Address already in use " but if i close the client first, then the server stops, i will not have this issue. my server socket works like this: try: s=socket s.bind(..) s.listen(1) conn,addr=s.accept() finally: conn.close() s.close() it feels to me that the server did not close the socket properly. but i do not know how to fix this. A: You're closing the socket just fine. However, the socket continues to use resources for a few minutes after the socket closes, so that if the remote end missed a packet the packet can be re-sent. You should be able to work around it by calling the following before you call bind: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) That will tell the operating system that you want to allow multiple bindings of the socket.
what is the correct way to close a socket in python 2.6?
i have a simple server/client. and i am using the netcat as the client to test the server. if i stop the server before the client exit, i will not be able to start the server again for a while and i go this error: " [Errno 98] Address already in use " but if i close the client first, then the server stops, i will not have this issue. my server socket works like this: try: s=socket s.bind(..) s.listen(1) conn,addr=s.accept() finally: conn.close() s.close() it feels to me that the server did not close the socket properly. but i do not know how to fix this.
[ "You're closing the socket just fine. However, the socket continues to use resources for a few minutes after the socket closes, so that if the remote end missed a packet the packet can be re-sent.\nYou should be able to work around it by calling the following before you call bind:\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\nThat will tell the operating system that you want to allow multiple bindings of the socket.\n" ]
[ 9 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002765152_python_sockets.txt
Q: Add windows commands in python Can anyone tell me how to add the shutdown.exe to python and how . i also want to set and variables like shutdown.exe -f -s -t 60 A: The subprocess module allows you to run external programs from inside python. In particular subprocess.call is a really convenient way to run programs where you don't care about anything other than the return code: import subprocess subprocess.call(["shutdown.exe", "-f", "-s", "-t", "60"]) Update: You can pass anything you want as part of the list so you could create a shutdown() function like this: import subprocess def shutdown(how_long): subprocess.call(["shutdown.exe", "-f", "-s", "-t", how_long]) So if we wanted to get user input directly from the console, we could do this: dt = raw_input("shutdown> ") dt = int(dt) #make sure dt is actually a number dt = str(dt) #back into a string 'cause that's what subprocess.call expects shutdown(dt)
Add windows commands in python
Can anyone tell me how to add the shutdown.exe to python and how . i also want to set and variables like shutdown.exe -f -s -t 60
[ "The subprocess module allows you to run external programs from inside python. In particular subprocess.call is a really convenient way to run programs where you don't care about anything other than the return code:\nimport subprocess\nsubprocess.call([\"shutdown.exe\", \"-f\", \"-s\", \"-t\", \"60\"])\n\nUpdate:\nYou can pass anything you want as part of the list so you could create a shutdown() function like this:\nimport subprocess\n\ndef shutdown(how_long):\n subprocess.call([\"shutdown.exe\", \"-f\", \"-s\", \"-t\", how_long])\n\nSo if we wanted to get user input directly from the console, we could do this:\ndt = raw_input(\"shutdown> \")\ndt = int(dt) #make sure dt is actually a number\ndt = str(dt) #back into a string 'cause that's what subprocess.call expects\nshutdown(dt)\n\n" ]
[ 8 ]
[]
[]
[ "python", "shutdown" ]
stackoverflow_0002765405_python_shutdown.txt
Q: google app engine db.Model in python only display user-defined fields I'm a python newbie so I apologize in advance if this question has been asked before. I am building out an application in GAE and need to generate a report that contains the values for a user-defined subset of fields. For example, in my db model, CrashReport, I have the following fields: entry_type entry_date instance_id build_id crash_text machine_info I present a user with the above list as a checkbox group from which they select. Whichever fields the user selects, I then create a report showing all the values in the datastore, but only for the fields that they selected. For example, if from the above list, the user selects the build_id and crash_text fields, the output might look like this: build_id  crash_text 0.8.2      blown gasket 0.8.2      flat tire 0.8.1      crack ... So the question is, how exactly do I only access the values for the fields which the user has defined? A: Given a model instance mi and an attribute name an, getattr(mi, an) will fetch the value of attribute an for object mi. It will raise AttributeError if object mi has no attribute by that name; if you want to avoid this, try e.g. getattr(mi, an, None). So if you have a list of attribute names la, [getattr(mi, x, None) for x in la] gives you a list of the values of the various attributes whose names are in la for a given instance mi. If you also have a list of instances li, and want a list of lists (one outer list per instance, each with all the attribute values), [[getattr(mi, x, None) for x in la] for mi in li] And so forth. These are all general Python concepts and operations and they apply to instances of models that you have fetched from the datastore, no less (and no more) than to any other Python objects.
google app engine db.Model in python only display user-defined fields
I'm a python newbie so I apologize in advance if this question has been asked before. I am building out an application in GAE and need to generate a report that contains the values for a user-defined subset of fields. For example, in my db model, CrashReport, I have the following fields: entry_type entry_date instance_id build_id crash_text machine_info I present a user with the above list as a checkbox group from which they select. Whichever fields the user selects, I then create a report showing all the values in the datastore, but only for the fields that they selected. For example, if from the above list, the user selects the build_id and crash_text fields, the output might look like this: build_id  crash_text 0.8.2      blown gasket 0.8.2      flat tire 0.8.1      crack ... So the question is, how exactly do I only access the values for the fields which the user has defined?
[ "Given a model instance mi and an attribute name an, getattr(mi, an) will fetch the value of attribute an for object mi. It will raise AttributeError if object mi has no attribute by that name; if you want to avoid this, try e.g. getattr(mi, an, None).\nSo if you have a list of attribute names la,\n[getattr(mi, x, None) for x in la]\n\ngives you a list of the values of the various attributes whose names are in la for a given instance mi.\nIf you also have a list of instances li, and want a list of lists (one outer list per instance, each with all the attribute values),\n[[getattr(mi, x, None) for x in la] for mi in li]\n\nAnd so forth. These are all general Python concepts and operations and they apply to instances of models that you have fetched from the datastore, no less (and no more) than to any other Python objects.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002765955_google_app_engine_google_cloud_datastore_python.txt
Q: error in writing data into file in python a='aa' >>> f=open("key.txt","w") >>> s=str(a) >>> f.write(s) and still the key.txt file remains blank .. why? A: Use f.flush() to flush the write to disk. Or, if you are done using f, you could use f.close() to flush and close the file. A: This issue can be avoided completely by making use of the with statement: with open("key.txt","w") as f: s=str(a) f.write(s) The file will be automatically closed when the block completes. Using the with statement you need not worry about this sort of bug creeping into your code.
error in writing data into file in python
a='aa' >>> f=open("key.txt","w") >>> s=str(a) >>> f.write(s) and still the key.txt file remains blank .. why?
[ "Use \nf.flush()\n\nto flush the write to disk. Or, if you are done using f, you could use\nf.close()\n\nto flush and close the file.\n", "This issue can be avoided completely by making use of the with statement:\nwith open(\"key.txt\",\"w\") as f:\n s=str(a)\n f.write(s)\n\nThe file will be automatically closed when the block completes. Using the with statement you need not worry about this sort of bug creeping into your code.\n" ]
[ 10, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002765617_file_io_python.txt
Q: Possible to use pyplot without DISPLAY? I'm working remotely on a machine that's pretty restrictive. I can't install any software, and it won't accept my X11 session, so I have no display. The machine currently has pylab installed, and I'd like to use it to plot something and then save it for viewing on another computer. However, it seems there's no way to even create a plot without a display. Am I missing something? A: Use another backend, for example Agg or SVG: import matplotlib matplotlib.use('Agg') ... matplotlib.savefig('out.png')
Possible to use pyplot without DISPLAY?
I'm working remotely on a machine that's pretty restrictive. I can't install any software, and it won't accept my X11 session, so I have no display. The machine currently has pylab installed, and I'd like to use it to plot something and then save it for viewing on another computer. However, it seems there's no way to even create a plot without a display. Am I missing something?
[ "Use another backend, for example Agg or SVG:\nimport matplotlib\nmatplotlib.use('Agg')\n...\nmatplotlib.savefig('out.png')\n\n" ]
[ 25 ]
[ "Yes, after creating the plots etc., instead of calling\npylab.show()\n\ncall\npylab.savefig('filename.XXX')\n\nwhere XXX is one of the common image extensions (png, jpg...)\n" ]
[ -1 ]
[ "matplotlib", "python", "x11" ]
stackoverflow_0002766149_matplotlib_python_x11.txt
Q: I need to authenticate against one db with python and openfire. How do I do this? How would one go about authenticating against a single db using Python and openfire? Is there a simple module that will do this? A: Openfire uses a SQL database. So talking to the database from python is probably the easiest way. You could also try to connect/authenticate via XMPP - there's probably an xmpp library for python somewhere.
I need to authenticate against one db with python and openfire. How do I do this?
How would one go about authenticating against a single db using Python and openfire? Is there a simple module that will do this?
[ "Openfire uses a SQL database. So talking to the database from python is probably the easiest way.\nYou could also try to connect/authenticate via XMPP - there's probably an xmpp library for python somewhere.\n" ]
[ 0 ]
[]
[]
[ "database", "openfire", "python" ]
stackoverflow_0002752047_database_openfire_python.txt
Q: Pass in a value into Python Class through command line I have got some code to pass in a variable into a script from the command line. I can pass any value into function for the var arg. The problem is that when I put function into a class the variable doesn't get read into function. The script is: import sys, os def function(var): print var class function_call(object): def __init__(self, sysArgs): try: self.function = None self.args = [] self.modulePath = sysArgs[0] self.moduleDir, tail = os.path.split(self.modulePath) self.moduleName, ext = os.path.splitext(tail) __import__(self.moduleName) self.module = sys.modules[self.moduleName] if len(sysArgs) > 1: self.functionName = sysArgs[1] self.function = self.module.__dict__[self.functionName] self.args = sysArgs[2:] except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e)) def execute(self): try: if self.function: self.function(*self.args) except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#execute", e)) if __name__=="__main__": function_call(sys.argv).execute() This works by entering ./function <function> <arg1 arg2 ....>. The problem is that I want to to select the function I want that is in a class rather than just a function by itself. The code I have tried is the same except that function(var): is in a class. I was hoping for some ideas on how to modify my function_call class to accept this. If i want to pass in the value Hello I run the script like so -- python function_call.py function Hello. This then prints the var variable as Hello. By entering the variable into the command lines I can then use this variable throughout the code. If the script was a bunch of functions I could just select the function using this code but I would like to select the functions inside a particular class. Instead of python function.py function hello I could enter the class in as well eg. python function.py A function hello. Also I have encounter that I have problem's saving the value for use outside the function. If anyone could solve this I would appreciate it very much. _________________________________________________________________________________ Amended code. This is the code that work's for me now. class A: def __init__(self): self.project = sys.argv[2] def run(self, *sysArgs): pass def funct(self): print self.project class function_call(object): def __init__(self, sysArgs): try: self.function = None self.args = [] self.modulePath = sysArgs[0] self.moduleDir, tail = os.path.split(self.modulePath) self.moduleName, ext = os.path.splitext(tail) __import__(self.moduleName) self.module = sys.modules[self.moduleName] if len(sysArgs) > 1: self.functionName = sysArgs[1] self.function = getattr(A(), sysArgs[1])(*sysArgs[2:]) self.args = sysArgs[2:] except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e)) def execute(self): try: if self.function: self.function(*self.args) except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#execute", e)) if __name__=="__main__": function_call(sys.argv).execute() inst_A = A() inst_A.funct() Thanks for all the help. A: you might find getattr useful: >>> argv = ['function.py', 'run', 'Hello'] >>> class A: def run(self, *args): print(*args) >>> getattr(A(), argv[1])(*argv[2:]) Hello A: It sounds like rather than: self.function = self.module.__dict__[self.functionName] you want to do something like (as @SilentGhost mentioned): self.function = getattr(some_class, self.functionName) The tricky thing with retrieving a method on a class (not an object instance) is that you are going to get back an unbound method. You will need to pass an instance of some_class as the first argument when you call self.function. Alternately, if you are defining the class in question, you can use classmethod or staticmethod to make sure that some_class.function_you_want_to_pick will return a bound function.
Pass in a value into Python Class through command line
I have got some code to pass in a variable into a script from the command line. I can pass any value into function for the var arg. The problem is that when I put function into a class the variable doesn't get read into function. The script is: import sys, os def function(var): print var class function_call(object): def __init__(self, sysArgs): try: self.function = None self.args = [] self.modulePath = sysArgs[0] self.moduleDir, tail = os.path.split(self.modulePath) self.moduleName, ext = os.path.splitext(tail) __import__(self.moduleName) self.module = sys.modules[self.moduleName] if len(sysArgs) > 1: self.functionName = sysArgs[1] self.function = self.module.__dict__[self.functionName] self.args = sysArgs[2:] except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e)) def execute(self): try: if self.function: self.function(*self.args) except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#execute", e)) if __name__=="__main__": function_call(sys.argv).execute() This works by entering ./function <function> <arg1 arg2 ....>. The problem is that I want to to select the function I want that is in a class rather than just a function by itself. The code I have tried is the same except that function(var): is in a class. I was hoping for some ideas on how to modify my function_call class to accept this. If i want to pass in the value Hello I run the script like so -- python function_call.py function Hello. This then prints the var variable as Hello. By entering the variable into the command lines I can then use this variable throughout the code. If the script was a bunch of functions I could just select the function using this code but I would like to select the functions inside a particular class. Instead of python function.py function hello I could enter the class in as well eg. python function.py A function hello. Also I have encounter that I have problem's saving the value for use outside the function. If anyone could solve this I would appreciate it very much. _________________________________________________________________________________ Amended code. This is the code that work's for me now. class A: def __init__(self): self.project = sys.argv[2] def run(self, *sysArgs): pass def funct(self): print self.project class function_call(object): def __init__(self, sysArgs): try: self.function = None self.args = [] self.modulePath = sysArgs[0] self.moduleDir, tail = os.path.split(self.modulePath) self.moduleName, ext = os.path.splitext(tail) __import__(self.moduleName) self.module = sys.modules[self.moduleName] if len(sysArgs) > 1: self.functionName = sysArgs[1] self.function = getattr(A(), sysArgs[1])(*sysArgs[2:]) self.args = sysArgs[2:] except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e)) def execute(self): try: if self.function: self.function(*self.args) except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#execute", e)) if __name__=="__main__": function_call(sys.argv).execute() inst_A = A() inst_A.funct() Thanks for all the help.
[ "you might find getattr useful:\n>>> argv = ['function.py', 'run', 'Hello']\n>>> class A:\n def run(self, *args):\n print(*args)\n\n\n>>> getattr(A(), argv[1])(*argv[2:])\nHello\n\n", "It sounds like rather than:\nself.function = self.module.__dict__[self.functionName]\n\nyou want to do something like (as @SilentGhost mentioned):\nself.function = getattr(some_class, self.functionName)\n\nThe tricky thing with retrieving a method on a class (not an object instance) is that you are going to get back an unbound method. You will need to pass an instance of some_class as the first argument when you call self.function.\nAlternately, if you are defining the class in question, you can use classmethod or staticmethod to make sure that some_class.function_you_want_to_pick will return a bound function.\n" ]
[ 4, 1 ]
[]
[]
[ "class", "command_line_arguments", "python" ]
stackoverflow_0002765664_class_command_line_arguments_python.txt
Q: Google App Engine (GAE) cron url: url?keyword=abc I would like to run cron job on GAE and using python In the cron.yaml, how do i insert the "url" field if consist of some "get" info The: description: whatever url: url?keyword=a schedule: every day 15:00 give me error when deploy A: I have tried the following cron.yaml and it worked fine. At least on the dev_appserver: cron: - description: url test url: /tasks?keyword=test schedule: every day 15:00
Google App Engine (GAE) cron url: url?keyword=abc
I would like to run cron job on GAE and using python In the cron.yaml, how do i insert the "url" field if consist of some "get" info The: description: whatever url: url?keyword=a schedule: every day 15:00 give me error when deploy
[ "I have tried the following cron.yaml and it worked fine. At least on the dev_appserver:\ncron:\n- description: url test\n url: /tasks?keyword=test\n schedule: every day 15:00\n\n" ]
[ 1 ]
[]
[]
[ "cron", "google_app_engine", "python" ]
stackoverflow_0002763960_cron_google_app_engine_python.txt
Q: Jythonc missing I just installed Jython 2.5.1. I want to convert my Python file into Java class file and it is instructed on the website to use the jythonc command-line tool but I can't find it. Does anyone know where I could find it? Basically what i was trying to accomplish is to get my Python code running client-side in a browser and the best way seemed to be by creating an applet using Jython. I don't want to create a desktop application and using Silverlight/IronPython is out of the question. Any other ideas are welcomed. Cheers! A: You can still compile your python-code to class-files: import compileall; compileall.compile_dir('Lib'); # to compile yor Lib-Dir should work with 2.5 jython i use it to create class-files to put in jars :-) A: Jythonc was removed in Jython 2.2 and is no longer supported. The official way to embed Jython code in Java is to create an instance of the interpreter to run the Jython code directly. There is an article on this here. Personally I preferred the jythonc method and hope it will be reinstated in a future version of Jython, even though it had a number of issues.
Jythonc missing
I just installed Jython 2.5.1. I want to convert my Python file into Java class file and it is instructed on the website to use the jythonc command-line tool but I can't find it. Does anyone know where I could find it? Basically what i was trying to accomplish is to get my Python code running client-side in a browser and the best way seemed to be by creating an applet using Jython. I don't want to create a desktop application and using Silverlight/IronPython is out of the question. Any other ideas are welcomed. Cheers!
[ "You can still compile your python-code to class-files:\nimport compileall; \ncompileall.compile_dir('Lib'); # to compile yor Lib-Dir \n\nshould work with 2.5 jython\ni use it to create class-files to put in jars :-)\n", "Jythonc was removed in Jython 2.2 and is no longer supported. The official way to embed Jython code in Java is to create an instance of the interpreter to run the Jython code directly. There is an article on this here.\nPersonally I preferred the jythonc method and hope it will be reinstated in a future version of Jython, even though it had a number of issues.\n" ]
[ 26, 9 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0002763129_jython_python.txt
Q: How to pass a variable from a function to a class python I am trying to pass a variable from a function to a class. Example code is below: def hello(var): return var class test(): def __init__(self): pass def value(self): print var hello(var) test = test() test.value() I would like to pass var into the class test(). Thanks for any help. A: You need to modify your class like this: class test(): def __init__(self, var): self.var = var def value(self): print self.var test_inst = test(var) test_inst.value() Also, you cannot use the same exact name to refer to both class instance and a class itself. A: class test(): def __init__(self, var): self._var = var def value(self): print self._var A: Add the statement: global var to your code: >>> global var >>> def hello(): print var >>> class test(): def __init__(self): pass def value(self): print var >>> var = 15 >>> hello() 15 >>> test().value() 15 Cue standard disclaimer regarding global variables are bad... but this is how you do it. A: I think you can call hello function in class's function. def hello (var): return var class test(): def __init__(self): pass def value(self): var = hello(5) print var test = test() test.value()
How to pass a variable from a function to a class python
I am trying to pass a variable from a function to a class. Example code is below: def hello(var): return var class test(): def __init__(self): pass def value(self): print var hello(var) test = test() test.value() I would like to pass var into the class test(). Thanks for any help.
[ "You need to modify your class like this:\nclass test():\n def __init__(self, var):\n self.var = var\n\n def value(self):\n print self.var\n\ntest_inst = test(var)\ntest_inst.value()\n\nAlso, you cannot use the same exact name to refer to both class instance and a class itself.\n", "class test():\n def __init__(self, var):\n self._var = var\n\n def value(self):\n print self._var\n\n", "Add the statement:\nglobal var\n\nto your code:\n>>> global var\n>>> def hello():\n print var\n\n>>> class test():\n def __init__(self):\n pass\n\n def value(self):\n print var\n\n>>> var = 15\n>>> hello()\n15\n>>> test().value()\n15\n\nCue standard disclaimer regarding global variables are bad... but this is how you do it.\n", "I think you can call hello function in class's function.\ndef hello (var):\n return var\n\nclass test():\n def __init__(self):\n pass\n\n def value(self):\n var = hello(5)\n print var\n\ntest = test()\ntest.value()\n\n" ]
[ 7, 0, 0, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002766239_class_python.txt
Q: is a there md5 decrypt function in python? Possible Duplicate: Is it possible to decrypt md5 hashes? i used md5.new(); md5.update("aaa"), md5.digest() to form a md5 hash of the data "aaa" . How to get back the data using python? A: You cannot decode an md5 hash, as hashing is a process that is best thought of as one-way encoding (that is to say what is hashed cannot be de-hashed; one can only determine what was hashed, either by examining a list of known hashes, or by hashing a set of inputs and matching the resulting hashes with the hash you are trying to "decode"). Quoting Wikipedia, the key features of such a hashing algorithm are: it is infeasible to find a message that has a given hash, it is infeasible to modify a message without changing its hash, it is infeasible to find two different messages with the same hash. The most common uses of such algorithms today are: Storing passwords Verifying the contents of files. If you want to two-way encrypt the data, you need to look at other cryptographic libraries for Python (As usual, Stackoverflow has a recommendation). A: You can't. That's the point - a hash is one-way, it's not the same as an encryption. A: I don't know about Python - but hash function are irreversible. First of all, note that hash functions provide a constant length output - meaning that information will be thrown away (you can hash a file of 3 MB and still only get a result of less than 1 kB). Additionally, hash functions are made for the fact that they aren't reversible, if you need encryption, don't use hashing but encryption - a major application of hashing is when the database info has leaked (which contained hashes) that the passwords have not been compromised (there are more examples, but this is the most obvious one) A: If you want to break a hash, such as a password hash. Then you need a very large lookup table. John the Ripper is commonly used to break passwords using a dictionary, this is a very good method espeically if its a salted password hash. Another approch is using a Rainbow Table, however these take long time to generate. There are free rainbow tables accessible online. Here is a python script to perform an md5() brute force attack. A: To add to everyone else's point, MD5 is a one-way hash. The common usage is to hash two input values and if the hashed values match, then the input should be the same. Going from an MD5 hashed value to the hash input is nonsensical. What you are probably after is a symmetric encryption algorithm - see two-way keyed encryption/hash algorithm for a good discussion on the subject. A: In general, the answers from BlueRaja and Sean are correct. MD5 (and other hash functions) are one-way, you can't reverse the process. However, if you have a small size of data, you can try to search for a hash collision (another, or the same, piece of data) having the same hash. A: Hashes map a bunch of data to a finite (albeit large) set of numeric values/strings. It is a many-to-one mapping, so that decoding a hash is not only "difficult" in the cryptographic sense, but also conceptually impossible in that even if you could, you would get an infinite set of possible input strings.
is a there md5 decrypt function in python?
Possible Duplicate: Is it possible to decrypt md5 hashes? i used md5.new(); md5.update("aaa"), md5.digest() to form a md5 hash of the data "aaa" . How to get back the data using python?
[ "You cannot decode an md5 hash, as hashing is a process that is best thought of as one-way encoding (that is to say what is hashed cannot be de-hashed; one can only determine what was hashed, either by examining a list of known hashes, or by hashing a set of inputs and matching the resulting hashes with the hash you are trying to \"decode\").\nQuoting Wikipedia, the key features of such a hashing algorithm are:\n\nit is infeasible to find a message\nthat has a given hash,\nit is\ninfeasible to modify a message without\nchanging its hash,\nit is infeasible to\nfind two different messages with the\nsame hash.\n\nThe most common uses of such algorithms today are:\n\nStoring passwords\nVerifying the contents of files.\n\nIf you want to two-way encrypt the data, you need to look at other cryptographic libraries for Python (As usual, Stackoverflow has a recommendation).\n", "You can't. That's the point - a hash is one-way, it's not the same as an encryption.\n", "I don't know about Python - but hash function are irreversible.\nFirst of all, note that hash functions provide a constant length output - meaning that information will be thrown away (you can hash a file of 3 MB and still only get a result of less than 1 kB).\nAdditionally, hash functions are made for the fact that they aren't reversible, if you need encryption, don't use hashing but encryption - a major application of hashing is when the database info has leaked (which contained hashes) that the passwords have not been compromised (there are more examples, but this is the most obvious one)\n", "If you want to break a hash, such as a password hash. Then you need a very large lookup table. John the Ripper is commonly used to break passwords using a dictionary, this is a very good method espeically if its a salted password hash. \nAnother approch is using a Rainbow Table, however these take long time to generate. There are free rainbow tables accessible online. \nHere is a python script to perform an md5() brute force attack. \n", "To add to everyone else's point, MD5 is a one-way hash. The common usage is to hash two input values and if the hashed values match, then the input should be the same. Going from an MD5 hashed value to the hash input is nonsensical. What you are probably after is a symmetric encryption algorithm - see two-way keyed encryption/hash algorithm for a good discussion on the subject.\n", "In general, the answers from BlueRaja and Sean are correct. MD5 (and other hash functions) are one-way, you can't reverse the process.\nHowever, if you have a small size of data, you can try to search for a hash collision (another, or the same, piece of data) having the same hash.\n", "Hashes map a bunch of data to a finite (albeit large) set of numeric values/strings.\nIt is a many-to-one mapping, so that decoding a hash is not only \"difficult\" in the cryptographic sense, but also conceptually impossible in that even if you could, you would get an infinite set of possible input strings.\n" ]
[ 22, 14, 3, 3, 1, 0, 0 ]
[]
[]
[ "md5", "python" ]
stackoverflow_0002760911_md5_python.txt
Q: Template strings python 2.5 error #!/usr/bin/python from string import Template s = Template('$x, go home $x') s.substitute(x='lee') print s error i get is <string.Template object at 0x81abdcc> desired results i am looking for is : lee, go home lee A: You need to look at the return value of substitute. It gives you the string with substitutions performed. print s.substitute(x='lee') The template object itself (s) is not changed. This gives you the ability to perform multiple substitutions with the same template object. A: You're not getting an error: you're getting exactly what you're asking for -- the template itself. To achieve your desired result, print s.substitute(x='lee') Templates, like strings, are not mutable objects: any method you call on a template (or string) can never alter that template -- it can only produce a separate result which you can use. This, of course, applies to the .substitute method. You're calling it, but ignoring the result, and then printing the template -- no doubt you expect the template itself to be somehow altered, but that's just not how it works. A: print s.substitute(x='lee')
Template strings python 2.5 error
#!/usr/bin/python from string import Template s = Template('$x, go home $x') s.substitute(x='lee') print s error i get is <string.Template object at 0x81abdcc> desired results i am looking for is : lee, go home lee
[ "You need to look at the return value of substitute. It gives you the string with substitutions performed.\nprint s.substitute(x='lee')\n\nThe template object itself (s) is not changed. This gives you the ability to perform multiple substitutions with the same template object.\n", "You're not getting an error: you're getting exactly what you're asking for -- the template itself. To achieve your desired result,\nprint s.substitute(x='lee')\n\nTemplates, like strings, are not mutable objects: any method you call on a template (or string) can never alter that template -- it can only produce a separate result which you can use. This, of course, applies to the .substitute method. You're calling it, but ignoring the result, and then printing the template -- no doubt you expect the template itself to be somehow altered, but that's just not how it works.\n", "print s.substitute(x='lee')\n\n" ]
[ 7, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002766872_python.txt
Q: When to use "property" builtin: auxiliary functions and generators I recently discovered Python's property built-in, which disguises class method getters and setters as a class's property. I'm now being tempted to use it in ways that I'm pretty sure are inappropriate. Using the property keyword is clearly the right thing to do if class A has a property _x whose allowable values you want to restrict; i.e., it would replace the getX() and setX() construction one might write in C++. But where else is it appropriate to make a function a property? For example, if you have class Vertex(object): def __init__(self): self.x = 0.0 self.y = 1.0 class Polygon(object): def __init__(self, list_of_vertices): self.vertices = list_of_vertices def get_vertex_positions(self): return zip( *( (v.x,v.y) for v in self.vertices ) ) is it appropriate to add vertex_positions = property( get_vertex_positions ) ? Is it ever ok to make a generator look like a property? Imagine if a change in our code meant that we no longer stored Polygon.vertices the same way. Would it then be ok to add this to Polygon? @property def vertices(self): for v in self._new_v_thing: yield v.calculate_equivalent_vertex() A: When you have a normal attribute and getting and/or setting it makes sense for a class's user, expose the attribute directly. One big reason that public members are anathema in some languages is that if you need to do something more complex later you would need an API change; in Python you can just define a property. If you are using something you should abstract as attribute access, use property. If you want to make external state (your plot or website or something) aware of the change or if you are wrapping some library that uses members directly, properties might be the way to go. If something isn't attribute-y, don't make it a property. There's no harm in making a method, and it can be advantageous: what it does is more obvious, you can pass around some bound method if you need, you can add keyword arguments without an API change. It's hard to imagine a situation where I would use a generator function as a property. The only way to have a normal attribute that would behave at all similarly would require quite a lot of complexity, so that case isn't very reminiscent of attribute access. You point out you can use property for restricting access to some internal attribute _x. This can be true, but keep in mind If you are going to do things like sanitize input for security or something important, explicit is better than implicit. You don't want to feel like code just-works when it comes to such things, because then you'll run into code that doesn't. Sometimes people use property to implement read-only attributes. It's usually better just to have a normal attribute and realize you can't stop a user from doing something dumb and unsupported. Nitpicking you might find interesting: property isn't a keyword; it's a normal name you can rebind. This is sort of interesting since property isn't a syntax thing or anything: it's a normal class you could implement yourself in pure Python. It uses the same mechanism that makes methods work in Python—descriptors. You describe what property does as "disguises class method getters and setters", which isn't quite the case. The things that property take are just normal functions, and needn't actually be defined in your class at all; property will pass self for you. Functions don't actually become methods until you look them up, when Python creates method objects on-the-fly. During the class definition, they are just functions. When you have a normal method it's called an "instance method"; in Python "class method" refers to another special thing sort of like properties that changes what happens when an attribute is looked up. A: There is an obvious limitation in the use of properties: it does not accept any argument, and it will never do. So you must be sure that the function you are transforming into a property will never be refactored into a function with, for example, extra default arguments.
When to use "property" builtin: auxiliary functions and generators
I recently discovered Python's property built-in, which disguises class method getters and setters as a class's property. I'm now being tempted to use it in ways that I'm pretty sure are inappropriate. Using the property keyword is clearly the right thing to do if class A has a property _x whose allowable values you want to restrict; i.e., it would replace the getX() and setX() construction one might write in C++. But where else is it appropriate to make a function a property? For example, if you have class Vertex(object): def __init__(self): self.x = 0.0 self.y = 1.0 class Polygon(object): def __init__(self, list_of_vertices): self.vertices = list_of_vertices def get_vertex_positions(self): return zip( *( (v.x,v.y) for v in self.vertices ) ) is it appropriate to add vertex_positions = property( get_vertex_positions ) ? Is it ever ok to make a generator look like a property? Imagine if a change in our code meant that we no longer stored Polygon.vertices the same way. Would it then be ok to add this to Polygon? @property def vertices(self): for v in self._new_v_thing: yield v.calculate_equivalent_vertex()
[ "\nWhen you have a normal attribute and getting and/or setting it makes sense for a class's user, expose the attribute directly. One big reason that public members are anathema in some languages is that if you need to do something more complex later you would need an API change; in Python you can just define a property.\nIf you are using something you should abstract as attribute access, use property. If you want to make external state (your plot or website or something) aware of the change or if you are wrapping some library that uses members directly, properties might be the way to go.\nIf something isn't attribute-y, don't make it a property. There's no harm in making a method, and it can be advantageous: what it does is more obvious, you can pass around some bound method if you need, you can add keyword arguments without an API change. \nIt's hard to imagine a situation where I would use a generator function as a property. The only way to have a normal attribute that would behave at all similarly would require quite a lot of complexity, so that case isn't very reminiscent of attribute access.\nYou point out you can use property for restricting access to some internal attribute _x. This can be true, but keep in mind\n\nIf you are going to do things like sanitize input for security or something important, explicit is better than implicit. You don't want to feel like code just-works when it comes to such things, because then you'll run into code that doesn't.\nSometimes people use property to implement read-only attributes. It's usually better just to have a normal attribute and realize you can't stop a user from doing something dumb and unsupported.\n\nNitpicking you might find interesting:\n\nproperty isn't a keyword; it's a normal name you can rebind. This is sort of \ninteresting since property isn't a syntax thing or anything: it's a normal class you could implement yourself in pure Python. It uses the same mechanism that makes methods work in Python—descriptors.\nYou describe what property does as \"disguises class method getters and setters\", which isn't quite the case. The things that property take are just normal functions, and needn't actually be defined in your class at all; property will pass self for you. Functions don't actually become methods until you look them up, when Python creates method objects on-the-fly. During the class definition, they are just functions. When you have a normal method it's called an \"instance method\"; in Python \"class method\" refers to another special thing sort of like properties that changes what happens when an attribute is looked up. \n\n\n", "There is an obvious limitation in the use of properties: it does not accept any argument, and it will never do.\nSo you must be sure that the function you are transforming into a property will never be refactored into a function with, for example, extra default arguments.\n" ]
[ 16, 3 ]
[]
[]
[ "properties", "python" ]
stackoverflow_0002766601_properties_python.txt
Q: giving garbage value while trying to store a md5 hash in a file in python m=md5.new() a=10111011 >>> m.update(str(a)) >>> k=m.digest() >>> k '\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M' >>> f.write(str(k)) >>> f.flush() the file f is filled with garbage value which i cant use to read again for further use of the hash . Why does it give the garbage value when on the python terminal it gives proper output?And the worst part is file goes corrupt .. A: If you want further clues where your "garbage" (your digest!) is coming from, try print k versus print repr(k)! You have a raw byte string. I think you want to insert a hexdigest instead? Either use k = m.hexdigest() or k = repr(m.digest()) and write that to your file. Basically, you can choose your representation, choose what you write to your file. Which of these do you want to see? >>> print k �1���Y�6���M >>> print repr(k) '\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M' >>> print k.encode("hex") ec9d31896508a1c259f6bf36fee4e24d Pass exactly the same to f.write(..) as you do to print. As you can see, in the original version you used 'k' ('str(k)' is the same as just 'k') A: One possibility is that you're on Windows and haven't properly opened the file in binary mode, i.e., as 'wb'. We can't tell, since you don't show us how you opened f. Another possibility might be that you're on Python 3 (where str means unicode), but I think in that case you'd see a leading b when you show k (and there's no md5 module in Python 3's standard library). Opening the file the right way, with Python 2.6.4 on a Mac, I see the digest as '\x82s\xf9\xa4\x83\x04\x87\xd0\xfdg\xee\xfa\x1f\x05B>' both as k and as the file's contents. I don't know why you're seeing something that different, by the way; I get the same result with Python 2.4 and 2.5.
giving garbage value while trying to store a md5 hash in a file in python
m=md5.new() a=10111011 >>> m.update(str(a)) >>> k=m.digest() >>> k '\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M' >>> f.write(str(k)) >>> f.flush() the file f is filled with garbage value which i cant use to read again for further use of the hash . Why does it give the garbage value when on the python terminal it gives proper output?And the worst part is file goes corrupt ..
[ "If you want further clues where your \"garbage\" (your digest!) is coming from, try print k versus print repr(k)!\nYou have a raw byte string. I think you want to insert a hexdigest instead? Either use k = m.hexdigest() or k = repr(m.digest()) and write that to your file.\nBasically, you can choose your representation, choose what you write to your file. Which of these do you want to see?\n>>> print k\n�1���Y�6���M\n>>> print repr(k)\n'\\xec\\x9d1\\x89e\\x08\\xa1\\xc2Y\\xf6\\xbf6\\xfe\\xe4\\xe2M'\n>>> print k.encode(\"hex\")\nec9d31896508a1c259f6bf36fee4e24d\n\nPass exactly the same to f.write(..) as you do to print. As you can see, in the original version you used 'k' ('str(k)' is the same as just 'k')\n", "One possibility is that you're on Windows and haven't properly opened the file in binary mode, i.e., as 'wb'. We can't tell, since you don't show us how you opened f.\nAnother possibility might be that you're on Python 3 (where str means unicode), but I think in that case you'd see a leading b when you show k (and there's no md5 module in Python 3's standard library).\nOpening the file the right way, with Python 2.6.4 on a Mac, I see the digest as\n'\\x82s\\xf9\\xa4\\x83\\x04\\x87\\xd0\\xfdg\\xee\\xfa\\x1f\\x05B>'\n\nboth as k and as the file's contents. I don't know why you're seeing something that different, by the way; I get the same result with Python 2.4 and 2.5.\n" ]
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002766961_python.txt
Q: Implicitly invoking parent class initializer class A(object): def __init__(self, a, b, c): #super(A, self).__init__() super(self.__class__, self).__init__() class B(A): def __init__(self, b, c): print super(B, self) print super(self.__class__, self) #super(B, self).__init__(1, b, c) super(self.__class__, self).__init__(1, b, c) class C(B): def __init__(self, c): #super(C, self).__init__(2, c) super(self.__class__, self).__init__(2, c) C(3) In the above code, the commented out __init__ calls appear to the be the commonly accepted "smart" way to do super class initialization. However in the event that the class hierarchy is likely to change, I have been using the uncommented form, until recently. It appears that in the call to the super constructor for B in the above hierarchy, that B.__init__ is called again, self.__class__ is actually C, not B as I had always assumed. Is there some way in Python-2.x that I can maintain proper MRO (with respect to initializing all parent classes in the correct order) when calling super constructors while not naming the current class (the B in in super(B, self).__init__(1, b, c))? A: Short answer: no, there's no way to implicitly invoke the right __init__ with the right arguments of the right parent class in Python 2.x. Incidentally, the code as shown here is incorrect: if you use super().__init__, then all classes in your hierarchy must have the same signature in their __init__ methods. Otherwise your code can stop working if you introduce a new subclass that uses multiple inheritance. See http://fuhm.net/super-harmful/ for a longer description of the issue (with pictures). A: Perhaps what you are looking for is metaclasses? class metawrap(type): def __new__(mcs,name, bases, dict): dict['bases'] = bases return type.__new__(mcs,name,bases,dict) class A(object): def __init__(self): pass def test(self): print "I am class A" class B(A): __metaclass__ = metawrap def __init__(self): pass def test(self): par = super(self.bases[0],self) par.__thisclass__.test(self) foo = B() foo.test() Prints "I am class A" What the metaclass does is overriding the initial creation of the B class (not the object) and makes sure that the builtin dictionary for each B object now contains a bases array where you can find all the baseclasses for B A: Your code has nothing to do with method resolution order. Method resolution comes in the case of multiple inheritance which is not the case of your example. Your code is simply wrong because you assume that self.__class__ is actually the same class of the one where the method is defined and this is wrong: >>> class A(object): ... def __init__(self): ... print self.__class__ ... >>> >>> class B(A): ... def __init__(self): ... A.__init__(self) ... >>> B() <class '__main__.B'> <__main__.B object at 0x1bcfed0> >>> A() <class '__main__.A'> <__main__.A object at 0x1bcff90> >>> so when you should call: super(B, self).__init__(1, b, c) you are indeed calling: # super(self.__class__, self).__init__(1, b, c) super(C, self).__init__(1, b, c) EDIT: trying to better answer the question. class A(object): def __init__(self, a): for cls in self.__class__.mro(): if cls is not object: cls._init(self, a) def _init(self, a): print 'A._init' self.a = a class B(A): def _init(self, a): print 'B._init' class C(A): def _init(self, a): print 'C._init' class D(B, C): def _init(self, a): print 'D._init' d = D(3) print d.a prints: D._init B._init C._init A._init 3 (A modified version of template pattern). Now parents' methods are really called implicitly, but i have to agree with python zen where explicit is better than implicit because the code is lesser readable and the gain is poor. But beware that all _init methods have the same parameters, you cannot completely forget about parents and I don't suggest to do so. For single inheritance, a better approach is explicitly calling parent's method, without invoking super. Doing so you don't have to name the current class, but still you must care about who is the parent's class. Good reads are: how-does-pythons-super-do-the-right-thing and the links suggested in that question and in particularity Python's Super is nifty, but you can't use it If hierarchy is likely to change is symptoms of bad design and has consequences in all the parts who are using that code and should not be encouraged. EDIT 2 Another example comes me in mind, but which uses metaclasses. Urwid library uses metaclass to store an attribute, __super, in class so that you need just to access to that attribute. Ex: >>> class MetaSuper(type): ... """adding .__super""" ... def __init__(cls, name, bases, d): ... super(MetaSuper, cls).__init__(name, bases, d) ... if hasattr(cls, "_%s__super" % name): ... raise AttributeError, "Class has same name as one of its super classes" ... setattr(cls, "_%s__super" % name, super(cls)) ... >>> class A: ... __metaclass__ = MetaSuper ... def __init__(self, a): ... self.a = a ... print 'A.__init__' ... >>> class B(A): ... def __init__(self, a): ... print 'B.__init__' ... self.__super.__init__(a) ... >>> b = B(42) B.__init__ A.__init__ >>> b.a 42 >>> A: To my knowledge, the following isn't commonly done. But it does seem to work. Methods in a given class definition always mangle double-underscore attributes to include the name of the class they're defined in. So, if you stash a reference to the class in name-mangled form where the instances can see it, you can use that in the call to super. An example stashing the references on the object itself, by implementing __new__ on the baseclass: def mangle(cls, name): if not name.startswith('__'): raise ValueError('name must start with double underscore') return '_%s%s' % (cls.__name__, name) class ClassStasher(object): def __new__(cls, *args, **kwargs): obj = object.__new__(cls) for c in cls.mro(): setattr(obj, mangle(c, '__class'), c) return obj class A(ClassStasher): def __init__(self): print 'init in A', self.__class super(self.__class, self).__init__() class B(A): def __init__(self): print 'init in B', self.__class super(self.__class, self).__init__() class C(A): def __init__(self): print 'init in C', self.__class super(self.__class, self).__init__() class D(B, C): def __init__(self): print 'init in D', self.__class super(self.__class, self).__init__() d = D() print d And, doing a similar thing, but using a meta-class and stashing the __class references on the class objects themselves: class ClassStasherType(type): def __init__(cls, name, bases, attributes): setattr(cls, mangle(cls, '__class'), cls) class ClassStasher(object): __metaclass__ = ClassStasherType class A_meta(ClassStasher): def __init__(self): print 'init in A_meta', self.__class super(self.__class, self).__init__() class B_meta(A_meta): def __init__(self): print 'init in B_meta', self.__class super(self.__class, self).__init__() class C_meta(A_meta): def __init__(self): print 'init in C_meta', self.__class super(self.__class, self).__init__() class D_meta(B_meta, C_meta): def __init__(self): print 'init in D_meta', self.__class super(self.__class, self).__init__() d = D_meta() print d Running this all together, as one source file: % python /tmp/junk.py init in D <class '__main__.D'> init in B <class '__main__.B'> init in C <class '__main__.C'> init in A <class '__main__.A'> <__main__.D object at 0x1004a4a50> init in D_meta <class '__main__.D_meta'> init in B_meta <class '__main__.B_meta'> init in C_meta <class '__main__.C_meta'> init in A_meta <class '__main__.A_meta'> <__main__.D_meta object at 0x1004a4bd0>
Implicitly invoking parent class initializer
class A(object): def __init__(self, a, b, c): #super(A, self).__init__() super(self.__class__, self).__init__() class B(A): def __init__(self, b, c): print super(B, self) print super(self.__class__, self) #super(B, self).__init__(1, b, c) super(self.__class__, self).__init__(1, b, c) class C(B): def __init__(self, c): #super(C, self).__init__(2, c) super(self.__class__, self).__init__(2, c) C(3) In the above code, the commented out __init__ calls appear to the be the commonly accepted "smart" way to do super class initialization. However in the event that the class hierarchy is likely to change, I have been using the uncommented form, until recently. It appears that in the call to the super constructor for B in the above hierarchy, that B.__init__ is called again, self.__class__ is actually C, not B as I had always assumed. Is there some way in Python-2.x that I can maintain proper MRO (with respect to initializing all parent classes in the correct order) when calling super constructors while not naming the current class (the B in in super(B, self).__init__(1, b, c))?
[ "Short answer: no, there's no way to implicitly invoke the right __init__ with the right arguments of the right parent class in Python 2.x.\nIncidentally, the code as shown here is incorrect: if you use super().__init__, then all classes in your hierarchy must have the same signature in their __init__ methods. Otherwise your code can stop working if you introduce a new subclass that uses multiple inheritance.\nSee http://fuhm.net/super-harmful/ for a longer description of the issue (with pictures).\n", "Perhaps what you are looking for is metaclasses?\nclass metawrap(type):\n def __new__(mcs,name, bases, dict):\n dict['bases'] = bases\n return type.__new__(mcs,name,bases,dict)\n\nclass A(object):\n def __init__(self):\n pass\n def test(self):\n print \"I am class A\"\n\nclass B(A):\n __metaclass__ = metawrap\n def __init__(self):\n pass\n def test(self):\n par = super(self.bases[0],self)\n par.__thisclass__.test(self)\nfoo = B()\nfoo.test()\n\nPrints \"I am class A\"\nWhat the metaclass does is overriding the initial creation of the B class (not the object) and makes sure that the builtin dictionary for each B object now contains a bases array where you can find all the baseclasses for B\n", "Your code has nothing to do with method resolution order. Method resolution comes in the case of multiple inheritance which is not the case of your example. Your code is simply wrong because you assume that self.__class__ is actually the same class of the one where the method is defined and this is wrong:\n>>> class A(object):\n... def __init__(self):\n... print self.__class__\n... \n>>> \n>>> class B(A):\n... def __init__(self):\n... A.__init__(self)\n... \n>>> B()\n<class '__main__.B'>\n<__main__.B object at 0x1bcfed0>\n>>> A()\n<class '__main__.A'>\n<__main__.A object at 0x1bcff90>\n>>> \n\nso when you should call:\nsuper(B, self).__init__(1, b, c)\n\nyou are indeed calling:\n# super(self.__class__, self).__init__(1, b, c)\nsuper(C, self).__init__(1, b, c)\n\nEDIT: trying to better answer the question.\nclass A(object):\n def __init__(self, a):\n for cls in self.__class__.mro():\n if cls is not object:\n cls._init(self, a)\n def _init(self, a):\n print 'A._init'\n self.a = a\n\nclass B(A):\n def _init(self, a):\n print 'B._init'\n\nclass C(A):\n def _init(self, a):\n print 'C._init'\n\nclass D(B, C):\n def _init(self, a):\n print 'D._init'\n\n\nd = D(3)\nprint d.a\n\nprints:\nD._init\nB._init\nC._init\nA._init\n3\n\n(A modified version of template pattern).\nNow parents' methods are really called implicitly, but i have to agree with python zen where explicit is better than implicit because the code is lesser readable and the gain is poor. But beware that all _init methods have the same parameters, you cannot completely forget about parents and I don't suggest to do so.\nFor single inheritance, a better approach is explicitly calling parent's method, without invoking super. Doing so you don't have to name the current class, but still you must care about who is the parent's class.\nGood reads are: how-does-pythons-super-do-the-right-thing and the links suggested in that question and in particularity Python's Super is nifty, but you can't use it\nIf hierarchy is likely to change is symptoms of bad design and has consequences in all the parts who are using that code and should not be encouraged.\nEDIT 2\nAnother example comes me in mind, but which uses metaclasses. Urwid library uses metaclass to store an attribute, __super, in class so that you need just to access to that attribute.\nEx:\n>>> class MetaSuper(type):\n... \"\"\"adding .__super\"\"\"\n... def __init__(cls, name, bases, d):\n... super(MetaSuper, cls).__init__(name, bases, d)\n... if hasattr(cls, \"_%s__super\" % name):\n... raise AttributeError, \"Class has same name as one of its super classes\"\n... setattr(cls, \"_%s__super\" % name, super(cls))\n... \n>>> class A:\n... __metaclass__ = MetaSuper\n... def __init__(self, a):\n... self.a = a\n... print 'A.__init__'\n... \n>>> class B(A):\n... def __init__(self, a):\n... print 'B.__init__'\n... self.__super.__init__(a)\n... \n>>> b = B(42)\nB.__init__\nA.__init__\n>>> b.a\n42\n>>> \n\n", "To my knowledge, the following isn't commonly done. But it does seem to work.\nMethods in a given class definition always mangle double-underscore attributes to include the name of the class they're defined in. So, if you stash a reference to the class in name-mangled form where the instances can see it, you can use that in the call to super.\nAn example stashing the references on the object itself, by implementing __new__ on the baseclass:\ndef mangle(cls, name):\n if not name.startswith('__'):\n raise ValueError('name must start with double underscore')\n return '_%s%s' % (cls.__name__, name)\n\nclass ClassStasher(object):\n def __new__(cls, *args, **kwargs):\n obj = object.__new__(cls)\n for c in cls.mro():\n setattr(obj, mangle(c, '__class'), c)\n return obj\n\nclass A(ClassStasher):\n def __init__(self):\n print 'init in A', self.__class\n super(self.__class, self).__init__()\n\nclass B(A):\n def __init__(self):\n print 'init in B', self.__class\n super(self.__class, self).__init__()\n\nclass C(A):\n def __init__(self):\n print 'init in C', self.__class\n super(self.__class, self).__init__()\n\nclass D(B, C):\n def __init__(self):\n print 'init in D', self.__class\n super(self.__class, self).__init__()\n\n\nd = D() \nprint d\n\nAnd, doing a similar thing, but using a meta-class and stashing the __class references on the class objects themselves:\nclass ClassStasherType(type):\n def __init__(cls, name, bases, attributes):\n setattr(cls, mangle(cls, '__class'), cls)\n\nclass ClassStasher(object):\n __metaclass__ = ClassStasherType\n\nclass A_meta(ClassStasher):\n def __init__(self):\n print 'init in A_meta', self.__class\n super(self.__class, self).__init__()\n\nclass B_meta(A_meta):\n def __init__(self):\n print 'init in B_meta', self.__class\n super(self.__class, self).__init__()\n\nclass C_meta(A_meta):\n def __init__(self):\n print 'init in C_meta', self.__class\n super(self.__class, self).__init__()\n\nclass D_meta(B_meta, C_meta):\n def __init__(self):\n print 'init in D_meta', self.__class\n super(self.__class, self).__init__()\n\n\nd = D_meta() \nprint d\n\nRunning this all together, as one source file:\n% python /tmp/junk.py\ninit in D <class '__main__.D'>\ninit in B <class '__main__.B'>\ninit in C <class '__main__.C'>\ninit in A <class '__main__.A'>\n<__main__.D object at 0x1004a4a50>\ninit in D_meta <class '__main__.D_meta'>\ninit in B_meta <class '__main__.B_meta'>\ninit in C_meta <class '__main__.C_meta'>\ninit in A_meta <class '__main__.A_meta'>\n<__main__.D_meta object at 0x1004a4bd0>\n\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "constructor", "method_resolution_order", "python", "python_2.x", "super" ]
stackoverflow_0002354769_constructor_method_resolution_order_python_python_2.x_super.txt
Q: When deploying python, what web server options do we have? is the process inefficient at all? I think in the past python scripts would run off CGI, which would create a new thread for each process. I am a newbie so I'm not really sure, what options do we have? Is the web server pipeline that python works under any more/less effecient than say php? A: You can still use CGI if you want, but the normal approach these days is using WSGI on the Python side, e.g. through mod_wsgi on Apache or via bridges to FastCGI on other web servers. At least with mod_wsgi, I know of no inefficiencies with this approach. BTW, your description of CGI ("create a new thread for each process") is inaccurate: what it does is create a new process for each query's service (and that process typically needs to open a database connection, import all needed modules, etc etc, which is what may make it slow even on platforms where forking a process, per se, is pretty fast, such as all Unix variants). A: I would suggest Django http://www.djangoproject.com. It is very convenient to use, has everything you need for making web services. The most efficient way to use it is to run it as via Apache's mod_wsgi, and make Apache itself serve the static files. This generally has better performance than solutions such as CGI and mod-python, as the Python process running the web service runs separate from the main web server, so it can cache stuff and easily re-use resources (like DB handles). Also, you can then tweak the number of worker threads for Apache and your web application separately, resulting in better scalability. A: I suggest cherrypy (http://www.cherrypy.org/). It is very convenient to use, has everything you need for making web services, but still quite simple (no mega-framework). The most efficient way to use it is to run it as self-contained server on localhost and put it behind Apache via a Proxy statement, and make apache itself serve the static files. This generally has better performance than solutions such as CGI and mod-python, as the Python process running the web service runs separate from the main web server, so it can cache stuff and easily re-use resources (like DB handles). Also, you can then tweak the number of worker threads for Apache and your web application separately, resulting in better scalability.
When deploying python, what web server options do we have? is the process inefficient at all?
I think in the past python scripts would run off CGI, which would create a new thread for each process. I am a newbie so I'm not really sure, what options do we have? Is the web server pipeline that python works under any more/less effecient than say php?
[ "You can still use CGI if you want, but the normal approach these days is using WSGI on the Python side, e.g. through mod_wsgi on Apache or via bridges to FastCGI on other web servers. At least with mod_wsgi, I know of no inefficiencies with this approach.\nBTW, your description of CGI (\"create a new thread for each process\") is inaccurate: what it does is create a new process for each query's service (and that process typically needs to open a database connection, import all needed modules, etc etc, which is what may make it slow even on platforms where forking a process, per se, is pretty fast, such as all Unix variants).\n", "I would suggest Django http://www.djangoproject.com. It is very convenient to use, has everything you need for making web services. The most efficient way to use it is to run it as via Apache's mod_wsgi, and make Apache itself serve the static files.\nThis generally has better performance than solutions such as CGI and mod-python, as the Python process running the web service runs separate from the main web server, so it can cache stuff and easily re-use resources (like DB handles).\nAlso, you can then tweak the number of worker threads for Apache and your web application separately, resulting in better scalability.\n", "I suggest cherrypy (http://www.cherrypy.org/). It is very convenient to use, has everything you need for making web services, but still quite simple (no mega-framework). The most efficient way to use it is to run it as self-contained server on localhost and put it behind Apache via a Proxy statement, and make apache itself serve the static files.\nThis generally has better performance than solutions such as CGI and mod-python, as the Python process running the web service runs separate from the main web server, so it can cache stuff and easily re-use resources (like DB handles).\nAlso, you can then tweak the number of worker threads for Apache and your web application separately, resulting in better scalability. \n" ]
[ 6, 2, 1 ]
[]
[]
[ "python", "webserver" ]
stackoverflow_0002767013_python_webserver.txt