content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: What is needed to add an paperprint-like effect to photos in python? I want to transform photos in python to look like this: taken from doctype.com I will use it in django, PIL is installed. How can I achieve this? A: This is a combination of several subtle effects. It starts by a nonlinear deformation, and then a tasteful drop shadow is added. There's also a small border. I'd start by drawing one straight, vertical line on the above picture, and then seeing how you would transform to that from the original picture. Then, apply that transformation to the whole photo, add some drop shadow, and figure out what else is left... A: I've had a bit better luck with ImageMagick when it comes to more complex transformations. You would have to install it separately and though there is a python library it doesn't appear well documented so I've just used command line calls. Here is a good tutorial on warping image: And another tutorial on general use The drop shadow is probably just a second image which is composited with the first image.
What is needed to add an paperprint-like effect to photos in python?
I want to transform photos in python to look like this: taken from doctype.com I will use it in django, PIL is installed. How can I achieve this?
[ "This is a combination of several subtle effects. It starts by a nonlinear deformation, and then a tasteful drop shadow is added. There's also a small border. I'd start by drawing one straight, vertical line on the above picture, and then seeing how you would transform to that from the original picture. Then, apply that transformation to the whole photo, add some drop shadow, and figure out what else is left...\n", "I've had a bit better luck with ImageMagick when it comes to more complex transformations. You would have to install it separately and though there is a python library it doesn't appear well documented so I've just used command line calls.\nHere is a good tutorial on warping image: \nAnd another tutorial on general use\nThe drop shadow is probably just a second image which is composited with the first image.\n" ]
[ 3, 2 ]
[]
[]
[ "django", "image", "python", "python_imaging_library" ]
stackoverflow_0001546205_django_image_python_python_imaging_library.txt
Q: how to force python httplib library to use only A requests The problem is that urllib using httplib is querying for AAAA records. I would like to avoid that. Is there a nice way to do that? >>> import socket >>> socket.gethostbyname('www.python.org') '82.94.164.162' 21:52:37.302028 IP 192.168.0.9.44992 > 192.168.0.1.53: 27463+ A? www.python.org. (32) 21:52:37.312031 IP 192.168.0.1.53 > 192.168.0.9.44992: 27463 1/0/0 A 82.94.164.162 (48) python /usr/lib/python2.6/urllib.py -t http://www.python.org >/dev/null 2>&1 21:53:44.118314 IP 192.168.0.9.40669 > 192.168.0.1.53: 32354+ A? www.python.org. (32) 21:53:44.118647 IP 192.168.0.9.40669 > 192.168.0.1.53: 50414+ AAAA? www.python.org. (32) 21:53:44.122547 IP 192.168.0.1.53 > 192.168.0.9.40669: 32354 1/0/0 A 82.94.164.162 (48) 21:53:44.135215 IP 192.168.0.1.53 > 192.168.0.9.40669: 50414 1/0/0 AAAA[|domain] A: The correct answer is: http://docs.python.org/library/socket.html The Python socket library is using the following: socket.socket([family[, type[, proto]]]) Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6 or AF_UNIX. The socket type should be SOCK_STREAM (the default), SOCK_DGRAM or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted in that case. /* Supported address families. */ #define AF_UNSPEC 0 #define AF_INET 2 /* Internet IP Protocol */ #define AF_INET6 10 /* IP version 6 */ By default it is using 0 and if you call it with 2 it will query only for A records. Remember caching the resolv results in your app IS A REALLY BAD IDEA. Never do it! A: Look here: how-do-i-resolve-an-srv-record-in-python Once you resolved the correct A ip, use it in your request, instead of the dns.
how to force python httplib library to use only A requests
The problem is that urllib using httplib is querying for AAAA records. I would like to avoid that. Is there a nice way to do that? >>> import socket >>> socket.gethostbyname('www.python.org') '82.94.164.162' 21:52:37.302028 IP 192.168.0.9.44992 > 192.168.0.1.53: 27463+ A? www.python.org. (32) 21:52:37.312031 IP 192.168.0.1.53 > 192.168.0.9.44992: 27463 1/0/0 A 82.94.164.162 (48) python /usr/lib/python2.6/urllib.py -t http://www.python.org >/dev/null 2>&1 21:53:44.118314 IP 192.168.0.9.40669 > 192.168.0.1.53: 32354+ A? www.python.org. (32) 21:53:44.118647 IP 192.168.0.9.40669 > 192.168.0.1.53: 50414+ AAAA? www.python.org. (32) 21:53:44.122547 IP 192.168.0.1.53 > 192.168.0.9.40669: 32354 1/0/0 A 82.94.164.162 (48) 21:53:44.135215 IP 192.168.0.1.53 > 192.168.0.9.40669: 50414 1/0/0 AAAA[|domain]
[ "The correct answer is:\nhttp://docs.python.org/library/socket.html\nThe Python socket library is using the following:\nsocket.socket([family[, type[, proto]]])\nCreate a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6 or AF_UNIX. The socket type should be SOCK_STREAM (the default), SOCK_DGRAM or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted in that case.\n/* Supported address families. */\n#define AF_UNSPEC 0\n#define AF_INET 2 /* Internet IP Protocol */\n#define AF_INET6 10 /* IP version 6 */\n\nBy default it is using 0 and if you call it with 2 it will query only for A records.\nRemember caching the resolv results in your app IS A REALLY BAD IDEA. Never do it!\n", "Look here: how-do-i-resolve-an-srv-record-in-python\nOnce you resolved the correct A ip, use it in your request, instead of the dns.\n" ]
[ 6, 0 ]
[]
[]
[ "dns", "ipv4", "ipv6", "python" ]
stackoverflow_0001540749_dns_ipv4_ipv6_python.txt
Q: Deploying Django: How do you do it? I have tried following guides like this one but it just didnt work for me. So my question is this: What is a good guide for deploying Django, and how do you deploy your Django. I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not. A: mod_wsgi in combination with a virtualenv for all the dependencies, a mercurial checkout into the virtualenv and a fabric recipe to check out the changes on the server. I wrote an article about my usual workflow: Deploying Python Web Applications. Hope that helps. A: I have had success with mod_wsgi A: In my previous work we had real genius guy on deployment duties, he deployed application (Python, SQL, Perl and Java code) as set of deb files built for Ubuntu. Unfortunately now, I have no such support. We are deploying apps manually to virtualenv-ed environments with separate nginx configs for FastCGI. We use paver to deploy to remote servers. It's painful, but it works. A: This looks like a good place to start: http://www.unessa.net/en/hoyci/2007/06/using-capistrano-deploy-django-apps/ A: I use mod_python, and have every site in a git repository with the following subdirs: mysite template media I have mysite/settings.py in .gitignore, and work like this: do development on my local machine create remote repository on webserver push my changes to webserver repo set up apache vhost config file, tweak live server settings.py run git checkout && git reset --hard && sudo /etc/init.d/apache2 restart on webserver repo to get up-to-date version to its working copy and restart apache repeat steps 1, 3 and 5 whenever change request comes
Deploying Django: How do you do it?
I have tried following guides like this one but it just didnt work for me. So my question is this: What is a good guide for deploying Django, and how do you deploy your Django. I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.
[ "mod_wsgi in combination with a virtualenv for all the dependencies, a mercurial checkout into the virtualenv and a fabric recipe to check out the changes on the server.\nI wrote an article about my usual workflow: Deploying Python Web Applications. Hope that helps.\n", "I have had success with mod_wsgi\n", "In my previous work we had real genius guy on deployment duties, he deployed application (Python, SQL, Perl and Java code) as set of deb files built for Ubuntu. Unfortunately now, I have no such support. We are deploying apps manually to virtualenv-ed environments with separate nginx configs for FastCGI. We use paver to deploy to remote servers. It's painful, but it works.\n", "This looks like a good place to start: http://www.unessa.net/en/hoyci/2007/06/using-capistrano-deploy-django-apps/\n", "I use mod_python, and have every site in a git repository with the following subdirs:\n\nmysite\ntemplate\nmedia\n\nI have mysite/settings.py in .gitignore, and work like this:\n\ndo development on my local machine\ncreate remote repository on webserver\npush my changes to webserver repo\nset up apache vhost config file, tweak live server settings.py\nrun git checkout && git reset --hard && sudo /etc/init.d/apache2 restart on webserver repo to get up-to-date version to its working copy and restart apache\nrepeat steps 1, 3 and 5 whenever change request comes\n\n" ]
[ 7, 1, 1, 0, 0 ]
[ "The easiest way would be to use one of the sites on http://djangofriendly.com/hosts/ that will provide the hosting and set up for you, but even if you're wanting to roll your own it will allow you to see what set up other sites are using.\n" ]
[ -2 ]
[ "django_deployment", "python" ]
stackoverflow_0000114112_django_deployment_python.txt
Q: Using enums in ctypes.Structure I have a struct I'm accessing via ctypes: struct attrl { char *name; char *resource; char *value; struct attrl *next; enum batch_op op; }; So far I have Python code like: # struct attropl class attropl(Structure): pass attrl._fields_ = [ ("next", POINTER(attropl)), ("name", c_char_p), ("resource", c_char_p), ("value", c_char_p), But I'm not sure what to use for the batch_op enum. Should I just map it to a c_int or ? A: At least for GCC enum is just a simple numeric type. It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as signed or unsigned. I guess it cannot exceed long long int, but practically you should check the range of your enums and choose something like c_uint. Here is an example. The C program: enum batch_op { OP1 = 2, OP2 = 3, OP3 = -1, }; struct attrl { char *name; struct attrl *next; enum batch_op op; }; void f(struct attrl *x) { x->op = OP3; } and the Python one: from ctypes import (Structure, c_char_p, c_uint, c_int, POINTER, CDLL) class AttrList(Structure): pass AttrList._fields_ = [ ('name', c_char_p), ('next', POINTER(AttrList)), ('op', c_int), ] (OP1, OP2, OP3) = (2, 3, -1) enum = CDLL('./libenum.so') enum.f.argtypes = [POINTER(AttrList)] enum.f.restype = None a = AttrList(name=None, next=None, op=OP2) assert a.op == OP2 enum.f(a) assert a.op == OP3 A: Using c_int or c_uint would be fine. Alternatively, there is a recipe in the cookbook for an Enumeration class.
Using enums in ctypes.Structure
I have a struct I'm accessing via ctypes: struct attrl { char *name; char *resource; char *value; struct attrl *next; enum batch_op op; }; So far I have Python code like: # struct attropl class attropl(Structure): pass attrl._fields_ = [ ("next", POINTER(attropl)), ("name", c_char_p), ("resource", c_char_p), ("value", c_char_p), But I'm not sure what to use for the batch_op enum. Should I just map it to a c_int or ?
[ "At least for GCC enum is just a simple numeric type. It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as signed or unsigned. I guess it cannot exceed long long int, but practically you should check the range of your enums and choose something like c_uint.\nHere is an example. The C program:\nenum batch_op {\n OP1 = 2,\n OP2 = 3,\n OP3 = -1,\n};\n\nstruct attrl {\n char *name;\n struct attrl *next;\n enum batch_op op;\n};\n\nvoid f(struct attrl *x) {\n x->op = OP3;\n}\n\nand the Python one:\nfrom ctypes import (Structure, c_char_p, c_uint, c_int,\n POINTER, CDLL)\n\nclass AttrList(Structure): pass\nAttrList._fields_ = [\n ('name', c_char_p),\n ('next', POINTER(AttrList)),\n ('op', c_int),\n]\n\n(OP1, OP2, OP3) = (2, 3, -1)\n\nenum = CDLL('./libenum.so')\nenum.f.argtypes = [POINTER(AttrList)]\nenum.f.restype = None\n\na = AttrList(name=None, next=None, op=OP2)\nassert a.op == OP2\nenum.f(a)\nassert a.op == OP3\n\n", "Using c_int or c_uint would be fine. Alternatively, there is a recipe in the cookbook for an Enumeration class.\n" ]
[ 13, 5 ]
[]
[]
[ "ctypes", "enums", "python" ]
stackoverflow_0001546355_ctypes_enums_python.txt
Q: Str in Python's map and sum Why do you need to use the function 'str' in the following code? I am trying to count the sum of digits in a number. My code for i in number: sum(map(int, str(i)) where number is the following array [7,79,9] I read my code as follows loop though the array such that count sum of the integer digits by getting given digits in a number by map increasingly such that each object (given number) is converted to String // This does not make sense Manual says this for str Type: type Base Class: <type 'type'> String Form: <type 'str'> Namespace: Python builtin Docstring: str(object) -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. A: Given 79 you need to get [7, 9] in order to sum up this list. What does it mean to split a number into digits? It means to represent the number in a numerical system with some base (base 10 in this case). E. g. 79 is 7 * 10**1 + 9 * 10**0. And what is the simplest (well, at least in this context) way to get such a representation of a number? To convert it to a string of decimals! Your code does exactly that: >>> str(79) '79' # Another way to say this is [int(c) for c in str(79)] >>> map(int, str(79)) [7, 9] >>> sum(map(int, str(79))) 16 A: What happens when you try that code without using str()? The str() is used to convert the integer into a sequence of characters, so that map() can iterate over the sequence. The key point here is that a "string" can be treated as a "sequence of characters". A: Why do you need to use the function 'str' in the following code? Because map takes an iterable, like a list or a tuple or a string. The code in question adds upp all the numbers in an integer. And it does it by a little clever hack. It converts the number into a sequence of numbers by doing map(int, str(i)) This will convert the integer 2009 to the list [2, 0, 0, 9]. The sum() then adds all this integers up, and you get 11. A less hacky version would be: >>> number = [7,79,9] >>> for i in number: ... result = 0 ... while i: ... i, n = divmod(i, 10) ... result +=n ... print result ... 7 16 9 But your version is admittedly more clever.
Str in Python's map and sum
Why do you need to use the function 'str' in the following code? I am trying to count the sum of digits in a number. My code for i in number: sum(map(int, str(i)) where number is the following array [7,79,9] I read my code as follows loop though the array such that count sum of the integer digits by getting given digits in a number by map increasingly such that each object (given number) is converted to String // This does not make sense Manual says this for str Type: type Base Class: <type 'type'> String Form: <type 'str'> Namespace: Python builtin Docstring: str(object) -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object.
[ "Given 79 you need to get [7, 9] in order to sum up this list.\nWhat does it mean to split a number into digits? It means to represent the number in a numerical system with some base (base 10 in this case). E. g. 79 is 7 * 10**1 + 9 * 10**0.\nAnd what is the simplest (well, at least in this context) way to get such a representation of a number? To convert it to a string of decimals!\nYour code does exactly that:\n>>> str(79)\n'79'\n\n# Another way to say this is [int(c) for c in str(79)]\n>>> map(int, str(79))\n[7, 9]\n\n>>> sum(map(int, str(79)))\n16\n\n", "What happens when you try that code without using str()?\nThe str() is used to convert the integer into a sequence of characters, so that map() can iterate over the sequence. The key point here is that a \"string\" can be treated as a \"sequence of characters\".\n", "Why do you need to use the function 'str' in the following code?\nBecause map takes an iterable, like a list or a tuple or a string.\nThe code in question adds upp all the numbers in an integer. And it does it by a little clever hack. It converts the number into a sequence of numbers by doing\nmap(int, str(i))\n\nThis will convert the integer 2009 to the list [2, 0, 0, 9]. The sum() then adds all this integers up, and you get 11.\nA less hacky version would be:\n>>> number = [7,79,9]\n>>> for i in number:\n... result = 0\n... while i:\n... i, n = divmod(i, 10)\n... result +=n\n... print result\n... \n7\n16\n9\n\nBut your version is admittedly more clever.\n" ]
[ 8, 2, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001546846_python_string.txt
Q: Prevent decorator from being used twice on the same function in python I have a decorator: from functools import wraps def d(f): @wraps(f) def wrapper(*args,**kwargs): print 'Calling func' return f(*args,**kwargs) return wrapper And I want to prevent it from decorating the same function twice, e.g prevent things such as: @d @d def f(): print 2 Only possible solution I could think of is using a dict to store the functions the decorator has already decorated and raising an exception if asked to decorate a function that exists in the dict. Do tell if you have a better idea... A: I'd store the information in the function itself. There is a risk of a conflict if multiple decorators decide to use the same variable, but if it's only your own code, you should be able to avoid it. def d(f): if getattr(f, '_decorated_with_d', False): raise SomeException('Already decorated') @wraps(f) def wrapper(*args,**kwargs): print 'Calling func' return f(*args,**kwargs) wrapper._decorated_with_d = True return wrapper Another option can be this: def d(f): decorated_with = getattr(f, '_decorated_with', set()) if d in decorated_with: raise SomeException('Already decorated') @wraps(f) def wrapper(*args,**kwargs): print 'Calling func' return f(*args,**kwargs) decorated_with.add(d) wrapper._decorated_with = decorated_with return wrapper This assumes that you control all the decorators used. If there is a decorator that doesn't copy the _decorated_with attribute, you will not know what is it decorated with. A: I'll also propose my solution: first, create another decorator: class DecorateOnce(object): def __init__(self,f): self.__f=f self.__called={} #save all functions that have been decorated def __call__(self,toDecorate): #get the distinct func name funcName=toDecorate.__module__+toDecorate.func_name if funcName in self.__called: raise Exception('function already decorated by this decorator') self.__called[funcName]=1 print funcName return self.__f(toDecorate) Now every decorator you decorate with this decorator, will restrict itself to decorate a func only once: @DecorateOnce def decorate(f): def wrapper... A: Noam, The property of func_code to use is co_name. See below, all that is changed is two lines at top of d()'s def def d(f): if f.func_code.co_name == 'wrapper': return f #ignore it (or can throw exception instead...) @wraps(f) def wrapper(*args, **kwargs): print 'calling func' return f(*args, **kwargs) return wrapper Also, see for Lukáš Lalinský's approach which uses a explicitly defined property attached to the function object. This may be preferable as the "wrapper" name may be used elsewhere...
Prevent decorator from being used twice on the same function in python
I have a decorator: from functools import wraps def d(f): @wraps(f) def wrapper(*args,**kwargs): print 'Calling func' return f(*args,**kwargs) return wrapper And I want to prevent it from decorating the same function twice, e.g prevent things such as: @d @d def f(): print 2 Only possible solution I could think of is using a dict to store the functions the decorator has already decorated and raising an exception if asked to decorate a function that exists in the dict. Do tell if you have a better idea...
[ "I'd store the information in the function itself. There is a risk of a conflict if multiple decorators decide to use the same variable, but if it's only your own code, you should be able to avoid it.\ndef d(f):\n if getattr(f, '_decorated_with_d', False):\n raise SomeException('Already decorated')\n @wraps(f)\n def wrapper(*args,**kwargs):\n print 'Calling func'\n return f(*args,**kwargs)\n wrapper._decorated_with_d = True\n return wrapper\n\nAnother option can be this:\ndef d(f):\n decorated_with = getattr(f, '_decorated_with', set())\n if d in decorated_with:\n raise SomeException('Already decorated')\n @wraps(f)\n def wrapper(*args,**kwargs):\n print 'Calling func'\n return f(*args,**kwargs)\n decorated_with.add(d)\n wrapper._decorated_with = decorated_with\n return wrapper\n\nThis assumes that you control all the decorators used. If there is a decorator that doesn't copy the _decorated_with attribute, you will not know what is it decorated with.\n", "I'll also propose my solution:\nfirst, create another decorator:\nclass DecorateOnce(object):\n def __init__(self,f):\n self.__f=f\n self.__called={} #save all functions that have been decorated \n def __call__(self,toDecorate):\n #get the distinct func name\n funcName=toDecorate.__module__+toDecorate.func_name\n if funcName in self.__called:\n raise Exception('function already decorated by this decorator')\n self.__called[funcName]=1\n print funcName\n return self.__f(toDecorate)\n\nNow every decorator you decorate with this decorator, will restrict itself to decorate a func only once:\n@DecorateOnce\ndef decorate(f):\n def wrapper...\n\n", "Noam, The property of func_code to use is co_name. See below, all that is changed is two lines at top of d()'s def\ndef d(f):\n if f.func_code.co_name == 'wrapper':\n return f #ignore it (or can throw exception instead...)\n @wraps(f)\n def wrapper(*args, **kwargs):\n print 'calling func'\n return f(*args, **kwargs)\n return wrapper\n\nAlso, see for Lukáš Lalinský's approach which uses a explicitly defined property attached to the function object. This may be preferable as the \"wrapper\" name may be used elsewhere...\n" ]
[ 3, 2, 0 ]
[ "Look at f.func_code, it can tell you if f is a function or a wrapper.\n" ]
[ -1 ]
[ "decorator", "python" ]
stackoverflow_0001547222_decorator_python.txt
Q: Trace/BPT trap with Python threading module The following code dies with Trace/BPT trap: from tvdb_api import Tvdb from threading import Thread class GrabStuff(Thread): def run(self): t = Tvdb() def main(): threads = [GrabStuff() for x in range(1)] [x.start() for x in threads] [x.join() for x in threads] if __name__ == '__main__': main() The error occurs due to the Tvdb(), but I have no idea why. I ran the code with python -m pdb thescript.py and stepped through the code, and it dies at after the following lines: > .../threading.py(468)start() -> _active_limbo_lock.acquire() (Pdb) > .../threading.py(469)start() -> _limbo[self] = self (Pdb) > .../threading.py(470)start() -> _active_limbo_lock.release() (Pdb) > .../threading.py(471)start() -> _start_new_thread(self.__bootstrap, ()) (Pdb) > .../threading.py(472)start() -> self.__started.wait() (Pdb) Trace/BPT trap (I replaced the full path to threading.py with ...) The same problem occurs with 2.6.1 and 2.5.4. The machine is running on OS X 10.6.1 Snow Leopard. The tvdb_api code can be found on github.com/dbr/tvdb_api A: Bad things can happen when importing modules for the first time in a thread on OS X 10.6. See, for instance, this issue. As a workaround, try looking through Tvdb and add its complete chain of imports to the main module.
Trace/BPT trap with Python threading module
The following code dies with Trace/BPT trap: from tvdb_api import Tvdb from threading import Thread class GrabStuff(Thread): def run(self): t = Tvdb() def main(): threads = [GrabStuff() for x in range(1)] [x.start() for x in threads] [x.join() for x in threads] if __name__ == '__main__': main() The error occurs due to the Tvdb(), but I have no idea why. I ran the code with python -m pdb thescript.py and stepped through the code, and it dies at after the following lines: > .../threading.py(468)start() -> _active_limbo_lock.acquire() (Pdb) > .../threading.py(469)start() -> _limbo[self] = self (Pdb) > .../threading.py(470)start() -> _active_limbo_lock.release() (Pdb) > .../threading.py(471)start() -> _start_new_thread(self.__bootstrap, ()) (Pdb) > .../threading.py(472)start() -> self.__started.wait() (Pdb) Trace/BPT trap (I replaced the full path to threading.py with ...) The same problem occurs with 2.6.1 and 2.5.4. The machine is running on OS X 10.6.1 Snow Leopard. The tvdb_api code can be found on github.com/dbr/tvdb_api
[ "Bad things can happen when importing modules for the first time in a thread on OS X 10.6. See, for instance, this issue. As a workaround, try looking through Tvdb and add its complete chain of imports to the main module.\n" ]
[ 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001540835_multithreading_python.txt
Q: Forms in Django--cannot get past "cleaned_data" I have a form that allows users to upload text AND a file. However, I'd like to make it valid even if the user doesn't upload the file (file is optional). However, in Django, it is not allowing me to get past "clean(self)". I just want it simple--if text box, pass. If no text , return error. class PieceForm(forms.Form): text = forms.CharField(max_length=600) file = forms.FileField() def clean(self): cleaned_data = self.cleaned_data text = cleaned_data.get('text') file = cleaned_data.get('file') return cleaned_data In my views... form = PieceForm(request.POST, request.FILES) if form.is_valid(): print 'It's valid!' ........this only prints if there is a file! A: You must set required=False for the fields which are optional as noted in the documentation In your case, the following line should do the trick: file = forms.FileField(required=False)
Forms in Django--cannot get past "cleaned_data"
I have a form that allows users to upload text AND a file. However, I'd like to make it valid even if the user doesn't upload the file (file is optional). However, in Django, it is not allowing me to get past "clean(self)". I just want it simple--if text box, pass. If no text , return error. class PieceForm(forms.Form): text = forms.CharField(max_length=600) file = forms.FileField() def clean(self): cleaned_data = self.cleaned_data text = cleaned_data.get('text') file = cleaned_data.get('file') return cleaned_data In my views... form = PieceForm(request.POST, request.FILES) if form.is_valid(): print 'It's valid!' ........this only prints if there is a file!
[ "You must set required=False for the fields which are optional as noted in the documentation\nIn your case, the following line should do the trick:\n file = forms.FileField(required=False)\n\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001547412_django_python.txt
Q: Parallel Python: How do I supply arguments to 'submit'? This is only the second question with the parallel-python tag. After looking through the documentation and googling for the subject, I've come here as it's where I've had the best luck with answers and suggestions. The following is the API (I think it's called) that submits all pertinent info to pp. def submit(self, func, args=(), depfuncs=(), modules=(), callback=None, callbackargs=(), group='default', globals=None): """Submits function to the execution queue func - function to be executed args - tuple with arguments of the 'func' depfuncs - tuple with functions which might be called from 'func' modules - tuple with module names to import callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function group - job group, is used when wait(group) is called to wait for jobs in a given group to finish globals - dictionary from which all modules, functions and classes will be imported, for instance: globals=globals() """ Here is my submit statement with its arguments: job_server.submit(reify, (pop1, pop2, 1000), depfuncs = (key_seq, Chromosome, Params, Node, Tree), modules = ("math",), callback = sum.add, globals = globals()) All the capitalized names in depfuncs are the names of classes. I wasn't sure where to put the classes or even if I would need to include them as they are in the globals() dictionary. But when I ran it with the depfuncs() empty, it would raise an error such as "Tree not defined" (for example). Now, key_seq is a generator, so I have to work with an instance of it in order to be able to use .next(): def key_seq(): a = 0 while True: yield a a = a + 1 ks = key_seq() ks is defined in globals(). When I didn't include it anywhere else, I got an error saying 'ks is not defined'. When I include ks in depfuncs, this is the error: Traceback (most recent call last): File "C:\Python26\Code\gppp.py", line 459, in <module> job_server.submit(reify, (pop1, pop2, 1000), depfuncs = (key_seq, ks, Chromosome, Params, Node, Tree), modules = ("math",), callback = sum.add, globals = globals()) File "C:\Python26\lib\site-packages\pp.py", line 449, in submit sfunc = self.__dumpsfunc((func, ) + depfuncs, modules) File "C:\Python26\lib\site-packages\pp.py", line 634, in __dumpsfunc sources = [self.__get_source(func) for func in funcs] File "C:\Python26\lib\site-packages\pp.py", line 713, in __get_source sourcelines = inspect.getsourcelines(func)[0] File "C:\Python26\lib\inspect.py", line 678, in getsourcelines lines, lnum = findsource(object) File "C:\Python26\lib\inspect.py", line 519, in findsource file = getsourcefile(object) or getfile(object) File "C:\Python26\lib\inspect.py", line 441, in getsourcefile filename = getfile(object) File "C:\Python26\lib\inspect.py", line 418, in getfile raise TypeError('arg is not a module, class, method, ' TypeError: arg is not a module, class, method, function, traceback, frame, or code object I'm pretty sure arg is referring to ks. So, where do I tell .submit() about ks? I don't understand what's supposed to go where. Thanks. A: interesting - are you doing genetics simulations? i ask because i see 'Chromosome' in there, and I once developed a population genetics simulation using parallel python. your approach looks really complicated. in my parallel python program, i used the following call: job = jobServer.submit( doRun, (param,)) how did i get away with this? the trick is that the doRun function doesn't run in the same context as the context in which you call sumbit. For instance (contrived example): import os, pp def doRun(param): print "your name is %s!" % os.getlogin() jobServer = pp.Server() jobServer.submit( doRun, (param,)) this code will fail. this is because the os module doesn't exist in doRun - doRun is not running in the same context as submit. sure, you can pass os in the module parameter of submit, but isn't it easier just to call import os in doRun ? parallel python tries to avoid python's GIL by running your function in a totally separate process. it tries to make this easier to swallow by letting you quote-"pass" parameters and namespaces to your function, but it does this using hacks. for instance, your classes will be serialized using some variant of pickle and then unserialized in the new process. But instead of relying on submit's hacks, just accept the reality that your function is going to need to do all the work of setting up it's run context. you really have two main functions - one that sets up the call to submit, and one, which you call via submit, which actually sets up the work you need to do. if you need the next value from your generator to be available for a pp run, also pass it as a parameter! this avoids lambda functions and generator references, and leaves you with passing a simple variable! my code is not maintained anymore, but if you're curious check it out here: http://pps-spud.uchicago.edu/viewvc/fps/trunk/python/fps.py?view=markup A: I think you should be passing in lambda:ks.next() instead of plain old ks
Parallel Python: How do I supply arguments to 'submit'?
This is only the second question with the parallel-python tag. After looking through the documentation and googling for the subject, I've come here as it's where I've had the best luck with answers and suggestions. The following is the API (I think it's called) that submits all pertinent info to pp. def submit(self, func, args=(), depfuncs=(), modules=(), callback=None, callbackargs=(), group='default', globals=None): """Submits function to the execution queue func - function to be executed args - tuple with arguments of the 'func' depfuncs - tuple with functions which might be called from 'func' modules - tuple with module names to import callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function group - job group, is used when wait(group) is called to wait for jobs in a given group to finish globals - dictionary from which all modules, functions and classes will be imported, for instance: globals=globals() """ Here is my submit statement with its arguments: job_server.submit(reify, (pop1, pop2, 1000), depfuncs = (key_seq, Chromosome, Params, Node, Tree), modules = ("math",), callback = sum.add, globals = globals()) All the capitalized names in depfuncs are the names of classes. I wasn't sure where to put the classes or even if I would need to include them as they are in the globals() dictionary. But when I ran it with the depfuncs() empty, it would raise an error such as "Tree not defined" (for example). Now, key_seq is a generator, so I have to work with an instance of it in order to be able to use .next(): def key_seq(): a = 0 while True: yield a a = a + 1 ks = key_seq() ks is defined in globals(). When I didn't include it anywhere else, I got an error saying 'ks is not defined'. When I include ks in depfuncs, this is the error: Traceback (most recent call last): File "C:\Python26\Code\gppp.py", line 459, in <module> job_server.submit(reify, (pop1, pop2, 1000), depfuncs = (key_seq, ks, Chromosome, Params, Node, Tree), modules = ("math",), callback = sum.add, globals = globals()) File "C:\Python26\lib\site-packages\pp.py", line 449, in submit sfunc = self.__dumpsfunc((func, ) + depfuncs, modules) File "C:\Python26\lib\site-packages\pp.py", line 634, in __dumpsfunc sources = [self.__get_source(func) for func in funcs] File "C:\Python26\lib\site-packages\pp.py", line 713, in __get_source sourcelines = inspect.getsourcelines(func)[0] File "C:\Python26\lib\inspect.py", line 678, in getsourcelines lines, lnum = findsource(object) File "C:\Python26\lib\inspect.py", line 519, in findsource file = getsourcefile(object) or getfile(object) File "C:\Python26\lib\inspect.py", line 441, in getsourcefile filename = getfile(object) File "C:\Python26\lib\inspect.py", line 418, in getfile raise TypeError('arg is not a module, class, method, ' TypeError: arg is not a module, class, method, function, traceback, frame, or code object I'm pretty sure arg is referring to ks. So, where do I tell .submit() about ks? I don't understand what's supposed to go where. Thanks.
[ "interesting - are you doing genetics simulations? i ask because i see 'Chromosome' in there, and I once developed a population genetics simulation using parallel python.\nyour approach looks really complicated. in my parallel python program, i used the following call:\njob = jobServer.submit( doRun, (param,))\n\nhow did i get away with this? the trick is that the doRun function doesn't run in the same context as the context in which you call sumbit. For instance (contrived example):\nimport os, pp\n\ndef doRun(param):\n print \"your name is %s!\" % os.getlogin()\n\njobServer = pp.Server()\njobServer.submit( doRun, (param,))\n\nthis code will fail. this is because the os module doesn't exist in doRun - doRun is not running in the same context as submit. sure, you can pass os in the module parameter of submit, but isn't it easier just to call import os in doRun ?\nparallel python tries to avoid python's GIL by running your function in a totally separate process. it tries to make this easier to swallow by letting you quote-\"pass\" parameters and namespaces to your function, but it does this using hacks. for instance, your classes will be serialized using some variant of pickle and then unserialized in the new process.\nBut instead of relying on submit's hacks, just accept the reality that your function is going to need to do all the work of setting up it's run context. you really have two main functions - one that sets up the call to submit, and one, which you call via submit, which actually sets up the work you need to do. \nif you need the next value from your generator to be available for a pp run, also pass it as a parameter! this avoids lambda functions and generator references, and leaves you with passing a simple variable!\nmy code is not maintained anymore, but if you're curious check it out here:\nhttp://pps-spud.uchicago.edu/viewvc/fps/trunk/python/fps.py?view=markup\n", "I think you should be passing in lambda:ks.next() instead of plain old ks\n" ]
[ 5, 0 ]
[]
[]
[ "parallel_python", "python" ]
stackoverflow_0001546429_parallel_python_python.txt
Q: A minimalist, non-enterprisey approach for a SOAP server in Python I need to implement a small test utility which consumes extremely simple SOAP XML (HTTP POST) messages. This is a protocol which I have to support, and it's not my design decision to use SOAP (just trying to prevent those "why do you use protocol X?" answers) I'd like to use stuff that's already in the basic python 2.6.x installation. What's the easiest way to do that? The sole SOAP message is really simple, I'd rather not use any enterprisey tools like WSDL class generation if possible. I already implemented the same functionality earlier in Ruby with just plain HTTPServlet::AbstractServlet and REXML parser. Worked fine. I thought I could a similar solution in Python with BaseHTTPServer, BaseHTTPRequestHandler and the elementree parser, but it's not obvious to me how I can read the contents of my incoming SOAP POST message. The documentation is not that great IMHO. A: You could write a WSGI function (see wsgiref) and parse inside it an HTTP request body using the xml.etree.ElementTree module. SOAP is basically very simple, I'm not sure that it deserves a special module. Just use a standard XML processing library you like. A: I wrote something like this in Boo, using a .Net HTTPListener, because I too had to implement someone else's defined WSDL. The WSDL I was given used document/literal form (you'll need to make some adjustments to this information if your WSDL uses rpc/encoded). I wrapped the HTTPListener in a class that allowed client code to register callbacks by SOAP action, and then gave that class a Start method that would kick off the HTTPListener. You should be able to do something very similar in Python, with a getPOST() method on BaseHTTPServer to: extract the SOAP action from the HTTP headers use elementtree to extract the SOAP header and SOAP body from the POST'ed HTTP call the defined callback for the SOAP action, sending these extracted values return the response text given by the callback in a corresponding SOAP envelope; if the callback raises an exception, catch it and re-wrap it as a SOAP fault Then you just implement a callback per SOAP action, which gets the XML content passed to it, parses this with elementtree, performs the desired action (or mock action if this is tester), and constructs the necessary response XML (I was not too proud to just create this explicitly using string interpolation, but you could use elementtree to create this by serializing a Python response object). It will help if you can get some real SOAP sample messages in order to help you not tear out your hair, especially in the part where you create the necessary response XML.
A minimalist, non-enterprisey approach for a SOAP server in Python
I need to implement a small test utility which consumes extremely simple SOAP XML (HTTP POST) messages. This is a protocol which I have to support, and it's not my design decision to use SOAP (just trying to prevent those "why do you use protocol X?" answers) I'd like to use stuff that's already in the basic python 2.6.x installation. What's the easiest way to do that? The sole SOAP message is really simple, I'd rather not use any enterprisey tools like WSDL class generation if possible. I already implemented the same functionality earlier in Ruby with just plain HTTPServlet::AbstractServlet and REXML parser. Worked fine. I thought I could a similar solution in Python with BaseHTTPServer, BaseHTTPRequestHandler and the elementree parser, but it's not obvious to me how I can read the contents of my incoming SOAP POST message. The documentation is not that great IMHO.
[ "You could write a WSGI function (see wsgiref) and parse inside it an HTTP request body using the xml.etree.ElementTree module.\nSOAP is basically very simple, I'm not sure that it deserves a special module. Just use a standard XML processing library you like.\n", "I wrote something like this in Boo, using a .Net HTTPListener, because I too had to implement someone else's defined WSDL.\nThe WSDL I was given used document/literal form (you'll need to make some adjustments to this information if your WSDL uses rpc/encoded). I wrapped the HTTPListener in a class that allowed client code to register callbacks by SOAP action, and then gave that class a Start method that would kick off the HTTPListener. You should be able to do something very similar in Python, with a getPOST() method on BaseHTTPServer to:\n\nextract the SOAP action from the HTTP\nheaders\nuse elementtree to extract the SOAP\nheader and SOAP body from the POST'ed\nHTTP\ncall the defined callback for the\nSOAP action, sending these extracted values\nreturn the response text given by the\ncallback in a corresponding SOAP\nenvelope; if the callback raises an\nexception, catch it and re-wrap it as\na SOAP fault\n\nThen you just implement a callback per SOAP action, which gets the XML content passed to it, parses this with elementtree, performs the desired action (or mock action if this is tester), and constructs the necessary response XML (I was not too proud to just create this explicitly using string interpolation, but you could use elementtree to create this by serializing a Python response object).\nIt will help if you can get some real SOAP sample messages in order to help you not tear out your hair, especially in the part where you create the necessary response XML. \n" ]
[ 3, 1 ]
[]
[]
[ "http", "python", "soap" ]
stackoverflow_0001547520_http_python_soap.txt
Q: General printing raster and/or vector images I'm looking for some API for printing. Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.). What I think that would be minimum API is: printer devices list printer buffer where I could send my in-memory pixmap (ex. like winXP printer tasks folder) some API which would translate SI dimensions onto printer resolution, or according to previous - in memory pixmap (ex. 450x250) onto paper in appropriate resolution. What I was considering is postScript, but I've some old LPT drived laserjet which probably doesn't support *PS. Currently I'm trying to find something interesting in Qt - QGraphicsView. http://doc.trolltech.com/4.2/qgraphicsview.html A: You might want to investigate wx python for printing. Learning the framework might be a bit of an overhead for you though! I've had success with that in the past, both on windows and linux. I've also used reportlab to make PDFs which are pretty easy to print using the minimum of OS interaction. A: I would use PIL to create a BMP file, and then just use the standard OS services to print that file. PIL will accept data in either raster or vector form. A: Well you got close, look at Printing in Qt. There is the QPrinter class that implements some of what you are looking for. It is implmenetent as a QPaintDevice. This means that any widget that can render itself on the screen can be printed. This also mean you don't need to render to a bitmap to print, you can use Qt widgets or drawing functions for printing On a side note, check the version number of the Qt documentation, the last release of Qt is 4.5, 4.6 is in beta.
General printing raster and/or vector images
I'm looking for some API for printing. Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.). What I think that would be minimum API is: printer devices list printer buffer where I could send my in-memory pixmap (ex. like winXP printer tasks folder) some API which would translate SI dimensions onto printer resolution, or according to previous - in memory pixmap (ex. 450x250) onto paper in appropriate resolution. What I was considering is postScript, but I've some old LPT drived laserjet which probably doesn't support *PS. Currently I'm trying to find something interesting in Qt - QGraphicsView. http://doc.trolltech.com/4.2/qgraphicsview.html
[ "You might want to investigate wx python for printing. Learning the framework might be a bit of an overhead for you though! I've had success with that in the past, both on windows and linux.\nI've also used reportlab to make PDFs which are pretty easy to print using the minimum of OS interaction.\n", "I would use PIL to create a BMP file, and then just use the standard OS services to print that file. PIL will accept data in either raster or vector form.\n", "Well you got close, look at Printing in Qt. There is the QPrinter class that implements some of what you are looking for. It is implmenetent as a QPaintDevice. This means that any widget that can render itself on the screen can be printed. This also mean you don't need to render to a bitmap to print, you can use Qt widgets or drawing functions for printing\nOn a side note, check the version number of the Qt documentation, the last release of Qt is 4.5, 4.6 is in beta. \n" ]
[ 0, 0, 0 ]
[]
[]
[ "c", "c++", "python" ]
stackoverflow_0001547621_c_c++_python.txt
Q: How to sort this list in Python? [ {'time':33}, {'time':11}, {'time':66} ] How to sort by the "time" element, DESC. A: Like this: from operator import itemgetter l = sorted(l, key=itemgetter('time'), reverse=True) Or: l = sorted(l, key=lambda a: a['time'], reverse=True) output: [{'time': 66}, {'time': 33}, {'time': 11}] If you don't want to keep the original order you can use your_list.sort which modifies the original list instead of creating a copy like sorted(your_list) l.sort(key=lambda a: a['time'], reverse=True)
How to sort this list in Python?
[ {'time':33}, {'time':11}, {'time':66} ] How to sort by the "time" element, DESC.
[ "Like this:\nfrom operator import itemgetter\nl = sorted(l, key=itemgetter('time'), reverse=True)\n\nOr:\nl = sorted(l, key=lambda a: a['time'], reverse=True)\n\noutput: \n[{'time': 66}, {'time': 33}, {'time': 11}]\n\nIf you don't want to keep the original order you can use your_list.sort which modifies the original list instead of creating a copy like sorted(your_list)\nl.sort(key=lambda a: a['time'], reverse=True)\n\n" ]
[ 27 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001547733_list_python.txt
Q: Crazy python behaviour I have a little piece of python code in the server script for my website which looks a little bit like this: console.append([str(x) for x in data]) console.append(str(max(data))) quite simple, you might think, however the result it's outputting is this: ['3', '12', '3'] 3 for some reason python thinks 3 is the max of [3,12,3]! So am I doing something wrong? Or this is misbehaviour on the part of python? A: Because the character '3' is higher in the ASCII table than '1'. You are comparing strings, not numbers. If you want to compare the numerically, you need to convert them to numbers. One way is max(data, key=int), but you might want to actually store numbers in the list. A: I know very little Python, but you are taking the max of strings, which means that '3..' is greater than '1..'.
Crazy python behaviour
I have a little piece of python code in the server script for my website which looks a little bit like this: console.append([str(x) for x in data]) console.append(str(max(data))) quite simple, you might think, however the result it's outputting is this: ['3', '12', '3'] 3 for some reason python thinks 3 is the max of [3,12,3]! So am I doing something wrong? Or this is misbehaviour on the part of python?
[ "Because the character '3' is higher in the ASCII table than '1'. You are comparing strings, not numbers. If you want to compare the numerically, you need to convert them to numbers. One way is max(data, key=int), but you might want to actually store numbers in the list.\n", "I know very little Python, but you are taking the max of strings, which means that '3..' is greater than '1..'.\n" ]
[ 8, 1 ]
[]
[]
[ "max", "python" ]
stackoverflow_0001547856_max_python.txt
Q: How do I parse indents and dedents with pyparsing? Here is a subset of the Python grammar: single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE small_stmt: pass_stmt pass_stmt: 'pass' compound_stmt: if_stmt if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT (You can read the full grammar in the Python SVN repository: http://svn.python.org/.../Grammar) I am trying to use this grammar to generate a parser for Python, in Python. What I am having trouble with is how to express the INDENT and DEDENT tokens as pyparsing objects. Here is how I have implemented the other terminals: import pyparsing as p string_start = (p.Literal('"""') | "'''" | '"' | "'") string_token = ('\\' + p.CharsNotIn("",exact=1) | p.CharsNotIn('\\',exact=1)) string_end = p.matchPreviousExpr(string_start) terminals = { 'NEWLINE': p.Literal('\n').setWhitespaceChars(' \t') .setName('NEWLINE').setParseAction(terminal_action('NEWLINE')), 'ENDMARKER': p.stringEnd.copy().setWhitespaceChars(' \t') .setName('ENDMARKER').setParseAction(terminal_action('ENDMARKER')), 'NAME': (p.Word(p.alphas + "_", p.alphanums + "_", asKeyword=True)) .setName('NAME').setParseAction(terminal_action('NAME')), 'NUMBER': p.Combine( p.Word(p.nums) + p.CaselessLiteral("l") | (p.Word(p.nums) + p.Optional("." + p.Optional(p.Word(p.nums))) | "." + p.Word(p.nums)) + p.Optional(p.CaselessLiteral("e") + p.Optional(p.Literal("+") | "-") + p.Word(p.nums)) + p.Optional(p.CaselessLiteral("j")) ).setName('NUMBER').setParseAction(terminal_action('NUMBER')), 'STRING': p.Combine( p.Optional(p.CaselessLiteral('u')) + p.Optional(p.CaselessLiteral('r')) + string_start + p.ZeroOrMore(~string_end + string_token) + string_end ).setName('STRING').setParseAction(terminal_action('STRING')), # I can't find a good way of parsing indents/dedents. # The Grammar just has the tokens NEWLINE, INDENT and DEDENT scattered accross the rules. # A single NEWLINE would be translated to NEWLINE + PEER (from pyparsing.indentedBlock()), unless followed by INDENT or DEDENT # That NEWLINE and IN/DEDENT could be spit across rule boundaries. (see the 'suite' rule) 'INDENT': (p.LineStart() + p.Optional(p.Word(' '))).setName('INDENT'), 'DEDENT': (p.LineStart() + p.Optional(p.Word(' '))).setName('DEDENT') } terminal_action is a function that returns the corresponding parsing action, depending on its arguments. I am aware of the pyparsing.indentedBlock helper function, but I am can't figure out how to adopt that to a grammar without the PEER token. (Look at the pyparsing souce code to see what I am talking about) You can see my full source code here: http://pastebin.ca/1609860 A: There are a couple of examples on the pyparsing wiki Examples page that could give you some insights: pythonGrammarParser.py indentedGrammarExample.py To use pyparsing's indentedBlock, I think you would define suite as: indentstack = [1] suite = indentedBlock(stmt, indentstack, True) Note that indentedGrammarExample.py pre-dates the inclusion of indentedBlock in pyparsing, so does its own implemention of indent parsing.
How do I parse indents and dedents with pyparsing?
Here is a subset of the Python grammar: single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE small_stmt: pass_stmt pass_stmt: 'pass' compound_stmt: if_stmt if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT (You can read the full grammar in the Python SVN repository: http://svn.python.org/.../Grammar) I am trying to use this grammar to generate a parser for Python, in Python. What I am having trouble with is how to express the INDENT and DEDENT tokens as pyparsing objects. Here is how I have implemented the other terminals: import pyparsing as p string_start = (p.Literal('"""') | "'''" | '"' | "'") string_token = ('\\' + p.CharsNotIn("",exact=1) | p.CharsNotIn('\\',exact=1)) string_end = p.matchPreviousExpr(string_start) terminals = { 'NEWLINE': p.Literal('\n').setWhitespaceChars(' \t') .setName('NEWLINE').setParseAction(terminal_action('NEWLINE')), 'ENDMARKER': p.stringEnd.copy().setWhitespaceChars(' \t') .setName('ENDMARKER').setParseAction(terminal_action('ENDMARKER')), 'NAME': (p.Word(p.alphas + "_", p.alphanums + "_", asKeyword=True)) .setName('NAME').setParseAction(terminal_action('NAME')), 'NUMBER': p.Combine( p.Word(p.nums) + p.CaselessLiteral("l") | (p.Word(p.nums) + p.Optional("." + p.Optional(p.Word(p.nums))) | "." + p.Word(p.nums)) + p.Optional(p.CaselessLiteral("e") + p.Optional(p.Literal("+") | "-") + p.Word(p.nums)) + p.Optional(p.CaselessLiteral("j")) ).setName('NUMBER').setParseAction(terminal_action('NUMBER')), 'STRING': p.Combine( p.Optional(p.CaselessLiteral('u')) + p.Optional(p.CaselessLiteral('r')) + string_start + p.ZeroOrMore(~string_end + string_token) + string_end ).setName('STRING').setParseAction(terminal_action('STRING')), # I can't find a good way of parsing indents/dedents. # The Grammar just has the tokens NEWLINE, INDENT and DEDENT scattered accross the rules. # A single NEWLINE would be translated to NEWLINE + PEER (from pyparsing.indentedBlock()), unless followed by INDENT or DEDENT # That NEWLINE and IN/DEDENT could be spit across rule boundaries. (see the 'suite' rule) 'INDENT': (p.LineStart() + p.Optional(p.Word(' '))).setName('INDENT'), 'DEDENT': (p.LineStart() + p.Optional(p.Word(' '))).setName('DEDENT') } terminal_action is a function that returns the corresponding parsing action, depending on its arguments. I am aware of the pyparsing.indentedBlock helper function, but I am can't figure out how to adopt that to a grammar without the PEER token. (Look at the pyparsing souce code to see what I am talking about) You can see my full source code here: http://pastebin.ca/1609860
[ "There are a couple of examples on the pyparsing wiki Examples page that could give you some insights:\n\npythonGrammarParser.py\nindentedGrammarExample.py\n\nTo use pyparsing's indentedBlock, I think you would define suite as:\nindentstack = [1]\nsuite = indentedBlock(stmt, indentstack, True)\n\nNote that indentedGrammarExample.py pre-dates the inclusion of indentedBlock in pyparsing, so does its own implemention of indent parsing.\n" ]
[ 11 ]
[]
[]
[ "indentation", "parser_generator", "pyparsing", "python" ]
stackoverflow_0001547944_indentation_parser_generator_pyparsing_python.txt
Q: Python library for syntax highlighting Which Python library for syntax highlighting is the best one? I'm interested in things like supported languages, ease of use, pythonic design, dependencies, development status, etc. A: I think pygments is the greatest choice. It supports a large number of languages and it's very mature.
Python library for syntax highlighting
Which Python library for syntax highlighting is the best one? I'm interested in things like supported languages, ease of use, pythonic design, dependencies, development status, etc.
[ "I think pygments is the greatest choice. It supports a large number of languages and it's very mature.\n" ]
[ 9 ]
[]
[]
[ "pygments", "python", "syntax_highlighting" ]
stackoverflow_0001548276_pygments_python_syntax_highlighting.txt
Q: Python way to do crc32b As i posted as title, there is a way to use the crc32b hash on python natively or through a library (i.e. chilkat)? My intention is to "translate" a program from php to python, so output should be same as in php: $hashedData= hash('crc32b',$data); -> Edit: in a win32 system Thanks to all ;) A: python-mhash supplies many hashing functions including crc32b.
Python way to do crc32b
As i posted as title, there is a way to use the crc32b hash on python natively or through a library (i.e. chilkat)? My intention is to "translate" a program from php to python, so output should be same as in php: $hashedData= hash('crc32b',$data); -> Edit: in a win32 system Thanks to all ;)
[ "python-mhash supplies many hashing functions including crc32b.\n" ]
[ 2 ]
[]
[]
[ "crc", "hash", "python" ]
stackoverflow_0001548366_crc_hash_python.txt
Q: Self contained classes with Qt I've been trying to make my classes completely self contained, but I'm having some problems, which are probably coming from my missing something that everybody else knew first off... Anyway, take this example: class Main_Window (QtGui.QMainWindow): def __init__ (self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_bookingSystemMain() self.ui.setupUi(self) # Connect slots QtCore.QObject.connect(self.ui.submitRecord, QtCore.SIGNAL("clicked()"), self.__clickSubmitRecord) QtCore.QObject.connect(self.ui.btnListBookings, QtCore.SIGNAL("clicked()"), self.__show_list) def __clickSubmitRecord (self): global bookings name = self.ui.edtName.text() event = str(self.ui.comEvent.currentText()) amount = self.ui.spinBox.value() if name == '': QtGui.QMessageBox.warning(self, "Error", "Please enter a name!") elif amount == 0: QtGui.QMessageBox.warning(self, "Error", "You can't reserve 0 tickets!") elif event == '': QtGui.QMessageBox.warning(self, "Error", "Please choose an event!") else: bookings.append(Booking(name, event, amount)) QtGui.QMessageBox.information(self, "Booking added", "Your booking for " + str(amount) + " ticket(s) to see " + event + " in the name of " + name + " was sucessful.") self.__clear_widgets() def __clear_widgets (self): self.ui.edtName.clear() self.ui.comEvent.setCurrentIndex(-1) self.ui.spinBox.setValue(0) def __show_list (self): listdialog = List_Window(self) listdialog.show() Which implements a UI described in another module. The clickSubmitRecord() method uses the global 'booking' list and adds to it - now surely this class shouldn't have anything to do with anything other than that UI? How would I implement this in a good ood way? As I said I'm probably missing some kind of technique or obvious design feature... Thanks! A: I don't know Python so I can't give a good example here, but what I would probably do with Qt in C++ is define a signal of "bookingAdded" to your window object, and have one of your external objects (probably whichever invokes the UI) connect a slot to this signal, and then in your clickSubmitRecord you fire this signal and the new booking data is passed with the signal to your external object. Then your UI object doesn't need to know about anything external, and all your external objects need to know about the UI is the signal that it exposes. This can also help with thread safety if you use a queued connection to the signal.
Self contained classes with Qt
I've been trying to make my classes completely self contained, but I'm having some problems, which are probably coming from my missing something that everybody else knew first off... Anyway, take this example: class Main_Window (QtGui.QMainWindow): def __init__ (self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_bookingSystemMain() self.ui.setupUi(self) # Connect slots QtCore.QObject.connect(self.ui.submitRecord, QtCore.SIGNAL("clicked()"), self.__clickSubmitRecord) QtCore.QObject.connect(self.ui.btnListBookings, QtCore.SIGNAL("clicked()"), self.__show_list) def __clickSubmitRecord (self): global bookings name = self.ui.edtName.text() event = str(self.ui.comEvent.currentText()) amount = self.ui.spinBox.value() if name == '': QtGui.QMessageBox.warning(self, "Error", "Please enter a name!") elif amount == 0: QtGui.QMessageBox.warning(self, "Error", "You can't reserve 0 tickets!") elif event == '': QtGui.QMessageBox.warning(self, "Error", "Please choose an event!") else: bookings.append(Booking(name, event, amount)) QtGui.QMessageBox.information(self, "Booking added", "Your booking for " + str(amount) + " ticket(s) to see " + event + " in the name of " + name + " was sucessful.") self.__clear_widgets() def __clear_widgets (self): self.ui.edtName.clear() self.ui.comEvent.setCurrentIndex(-1) self.ui.spinBox.setValue(0) def __show_list (self): listdialog = List_Window(self) listdialog.show() Which implements a UI described in another module. The clickSubmitRecord() method uses the global 'booking' list and adds to it - now surely this class shouldn't have anything to do with anything other than that UI? How would I implement this in a good ood way? As I said I'm probably missing some kind of technique or obvious design feature... Thanks!
[ "I don't know Python so I can't give a good example here, but what I would probably do with Qt in C++ is define a signal of \"bookingAdded\" to your window object, and have one of your external objects (probably whichever invokes the UI) connect a slot to this signal, and then in your clickSubmitRecord you fire this signal and the new booking data is passed with the signal to your external object. \nThen your UI object doesn't need to know about anything external, and all your external objects need to know about the UI is the signal that it exposes.\nThis can also help with thread safety if you use a queued connection to the signal.\n" ]
[ 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001548370_oop_python.txt
Q: Cart item management in python Turbogears 2.0 I'm new to python an I decided to give it a try with TG2 by developing a small store. So far I've been loving it, but I'm guessing that my coding parading is still very attached to java's Like for example, the add to cart method in my CartController. def add(self, **kw): pid=kw['pid'] product = model.Product.by_id(pid) cart = self.get_cart() # check if that product is already on the cart isInCart = False for item in cart.items: if item.product == product: # if it is, increment quantity cart.items.remove(item) isInCart = True item.quantity += 1 cart.items.append(item) break if not isInCart: item = model.CartItem(cart, product, 1, product.normalPrice) cart.items.append(item) DBSession.add(item) DBSession.flush() # updating values for fast retrieval showing # how many items are in the cart self.update_session(cart) return u'Item added to cart, %d items in session' % session['cartitems'] This is certainly not the best way to achieve this, but so far it works as expected. In java I would just have to update the Item object, but here I have to remove it from the list then updated, then added again, is this correct? A: Since you are modifying the item object, I don't see any reason why you would have to remove, then append that item to the list. Why do you think you have to? As for making this more pythonic, you might consider something like this: items_by_pid = dict([(item.product.pid, item) for item in cart.items]) item = items_by_pid.get(pid, None) if item is None: item = model.CartItem(cart, product, 0, product.normalPrice) cart.items.append(item) item.quantity += 1
Cart item management in python Turbogears 2.0
I'm new to python an I decided to give it a try with TG2 by developing a small store. So far I've been loving it, but I'm guessing that my coding parading is still very attached to java's Like for example, the add to cart method in my CartController. def add(self, **kw): pid=kw['pid'] product = model.Product.by_id(pid) cart = self.get_cart() # check if that product is already on the cart isInCart = False for item in cart.items: if item.product == product: # if it is, increment quantity cart.items.remove(item) isInCart = True item.quantity += 1 cart.items.append(item) break if not isInCart: item = model.CartItem(cart, product, 1, product.normalPrice) cart.items.append(item) DBSession.add(item) DBSession.flush() # updating values for fast retrieval showing # how many items are in the cart self.update_session(cart) return u'Item added to cart, %d items in session' % session['cartitems'] This is certainly not the best way to achieve this, but so far it works as expected. In java I would just have to update the Item object, but here I have to remove it from the list then updated, then added again, is this correct?
[ "Since you are modifying the item object, I don't see any reason why you would have to remove, then append that item to the list. Why do you think you have to?\nAs for making this more pythonic, you might consider something like this:\nitems_by_pid = dict([(item.product.pid, item) for item in cart.items])\nitem = items_by_pid.get(pid, None)\nif item is None:\n item = model.CartItem(cart, product, 0, product.normalPrice)\n cart.items.append(item)\nitem.quantity += 1\n\n" ]
[ 3 ]
[]
[]
[ "python", "turbogears2" ]
stackoverflow_0001545913_python_turbogears2.txt
Q: Why leading zero not possible in Python's Map and Str What is the reason that you cannot use zero at the beginning of a number when converting the number to a sequence? Code example map(int,str(08978789787)) which gives Syntax error. I would like to convert numbers which leading digit is zero to a sequence. How can you convert such a number to a sequence? A: This happens because the leading zero means you are writing an octal number and you can't have 9 or 8 in an octal number. See: >>> a = 0123 >>> a 83 >>> a = 010 >>> a 8 You can just do: >>> map(int, '08978789787') [0, 8, 9, 7, 8, 7, 8, 9, 7, 8, 7] A: The "leading 0 in an integer means it's in octal notation" meme is a peculiar one which originated in C and spread all over the place -- Python (1.* and 2.*), Perl, Ruby, Java... Python 3 has eliminated it by making a leading 0 illegal in all integers (except in the constructs 0x, 0b, 0o to indicate hex, binary and octal notations). Nevertheless, even in a hypothetical sensible language where a leading 0 in an int had its normal arithmetical meaning, that is, no meaning whatsoever, you still would not obtain your desired result: 011 would then be exactly identical to 11, so calling str on either of them would have to produce identical results -- a string of length two, '11'. In arithmetic, the integer denoted by decimal notation 011 is identical, exactly the same entity as, indistinguishable from, one and the same with, the integer denoted by decimal notation 11. No hypothetical sensible language would completely alter the rules of arithmetic, as would be needed to allow you to obtain the result you appear to desire. So, like everybody else said, just use a string directly -- why not, after all?! A: Python: Invalid Token Use: map(int,"08978789787") A: "How can you convert such a number to a sequence?" There is no "such a number". The number 1 does not start with a 0. Numbers do not start with zeros in general (if they did, you would need to write an infinite amount of zeros every time you write a number, and that would obviously be impossible). So the question boils down to why you are writing str(08978789787)? If you want the string '08978789787', you should reasonably just write the string '08978789787'. Writing it as a number and the converting it to a string is completely pointless.
Why leading zero not possible in Python's Map and Str
What is the reason that you cannot use zero at the beginning of a number when converting the number to a sequence? Code example map(int,str(08978789787)) which gives Syntax error. I would like to convert numbers which leading digit is zero to a sequence. How can you convert such a number to a sequence?
[ "This happens because the leading zero means you are writing an octal number and you can't have 9 or 8 in an octal number. See:\n>>> a = 0123\n>>> a\n83\n>>> a = 010\n>>> a\n8\n\nYou can just do:\n>>> map(int, '08978789787')\n[0, 8, 9, 7, 8, 7, 8, 9, 7, 8, 7]\n\n", "The \"leading 0 in an integer means it's in octal notation\" meme is a peculiar one which originated in C and spread all over the place -- Python (1.* and 2.*), Perl, Ruby, Java... Python 3 has eliminated it by making a leading 0 illegal in all integers (except in the constructs 0x, 0b, 0o to indicate hex, binary and octal notations).\nNevertheless, even in a hypothetical sensible language where a leading 0 in an int had its normal arithmetical meaning, that is, no meaning whatsoever, you still would not obtain your desired result: 011 would then be exactly identical to 11, so calling str on either of them would have to produce identical results -- a string of length two, '11'.\nIn arithmetic, the integer denoted by decimal notation 011 is identical, exactly the same entity as, indistinguishable from, one and the same with, the integer denoted by decimal notation 11. No hypothetical sensible language would completely alter the rules of arithmetic, as would be needed to allow you to obtain the result you appear to desire.\nSo, like everybody else said, just use a string directly -- why not, after all?!\n", "Python: Invalid Token\nUse:\nmap(int,\"08978789787\")\n\n", "\"How can you convert such a number to a sequence?\"\nThere is no \"such a number\". The number 1 does not start with a 0. Numbers do not start with zeros in general (if they did, you would need to write an infinite amount of zeros every time you write a number, and that would obviously be impossible).\nSo the question boils down to why you are writing str(08978789787)? If you want the string '08978789787', you should reasonably just write the string '08978789787'. Writing it as a number and the converting it to a string is completely pointless.\n" ]
[ 14, 9, 4, 2 ]
[]
[]
[ "python", "sequence", "string" ]
stackoverflow_0001548419_python_sequence_string.txt
Q: Workflow for maintaining different versions of codebase for different versions of Python I'm developing an open source application called GarlicSim. Up to now I've been developing it only for Python 2.6. It seems not to work on any other version. I decided it's important to produce versions of it that will support other versions of Python. I'm thinking I'll make a version for 2.5, 3.1 and maybe 2.4. So I have several questions: What would be a good way to organize the folder structure of my repo to include these different versions? What would be a good way to 'merge' changes I do in one version of the code to other versions? I know how to do merges in my SCM (which is git), but these are folders that are all in the same repo, and I want to do a merge between them. There is of course the option of having a repo for each version, but I think it's not a good idea. Does anyone have any suggestions? A: You need separate branches for separate versions only in the rarest of cases. You mention context managers, and they are great, and it would suck not to use them, and you are right. But for Python 2.4 you will have to not use them. So that will suck. So therefore, if you want to support Python 2.4 you'll have to write a version without context managers. But that one will work under Python 2.6 too, so there is no point in having separate versions there. As for Python 3, having a separate branch there is a solution, but generally not the best one. For Python 3 support there is something called 2to3 which will convert your Python 2 code to Python 3 code. It's not perfect, so quite often you will have to modify the Python 2 code to generate nice Python 3 code, but the Python 2 code has a tendency to become better as a result anyway. With Distribute (a maintained fork of setuptools) you can make this conversation automatically during install. That way you don't have to have a separate branch even for Python 3. See http://bitbucket.org/tarek/distribute/src/tip/docs/python3.txt for the docs on that. As Paul McGuire writes it is even possible to support Python 3 and Python 2 with the same code without using 2to3, but I would not recommend it if you want to support anything else than 2.6 and 3.x. You get too much of this ugly special hacks. With 2.6 there is enough forwards compatibility with Python 3 to make it possible to write decent looking code and support both Python 2.6 and 3.x, but not Python 2.5 and 3.x. A: I would try to maintain one branch to cover all the python 2.4-2.6 The differences are not so great, after all if you have to write a bunch of extra code for 2.4 to do something that is easy in 2.6, it will be less work for you in the long run to use the 2.4 version for 2.5 and 2.6. Python 3 should have a different branch, you should still try to keep as much code in common as you can. A: If your code is not overly dependent on the run-time performance in exception handlers, you might even get away without having a separate branch for Py3. I've managed to keep one version of pyparsing for all of my Py2.x versions, although I've had to stick with a "lowest common denominator" approach, meaning that I have to forego using some constructs like generator expressions, and to your point, context managers. I use dicts in place of sets, and all my generator expressions get wrapped as list comprehensions, so they will still work going back to Python 2.3. I have a block at the top of my code that takes care of a number of 2vs3 issues (contributed by pyparsing user Robert A Clark): _PY3K = sys.version_info[0] > 2 if _PY3K: _MAX_INT = sys.maxsize basestring = str unichr = chr unicode = str _str2dict = set alphas = string.ascii_lowercase + string.ascii_uppercase else: _MAX_INT = sys.maxint range = xrange def _str2dict(strg): return dict( [(c,0) for c in strg] ) alphas = string.lowercase + string.uppercase The biggest difficulty I've had has been with the incompatible syntax for catching exceptions, that was introduced in Py3, changing from except exceptiontype,varname: to except exceptionType as varname: Of course, if you don't really need the exception variable, you can just write: except exceptionType: and this will work on Py2 or Py3. But if you need to access the exception, you can still come up with a cross-version compatible syntax as: except exceptionType: exceptionvar = sys.exc_info()[1] This has a minor run-time penalty, which makes this unusable in some places in pyparsing, so I still have to maintain separate Py2 and Py3 versions. For source merging, I use the utility WinMerge, which I find very good for keeping directories of source code in synch. So even though I keep two versions of my code, some of these unification techniques help me to keep the differences down to the absolute incompatible minimum. A: I eventually decided to have 4 different forks for my project, for 2.4, 2.5, 2.6 and 3.1. My main priority is 2.6 and I don't want to compromise the elegance of that code for the sake of 2.4. So the ugly compatibility hacks will be on the lower versions, not the higher versions.
Workflow for maintaining different versions of codebase for different versions of Python
I'm developing an open source application called GarlicSim. Up to now I've been developing it only for Python 2.6. It seems not to work on any other version. I decided it's important to produce versions of it that will support other versions of Python. I'm thinking I'll make a version for 2.5, 3.1 and maybe 2.4. So I have several questions: What would be a good way to organize the folder structure of my repo to include these different versions? What would be a good way to 'merge' changes I do in one version of the code to other versions? I know how to do merges in my SCM (which is git), but these are folders that are all in the same repo, and I want to do a merge between them. There is of course the option of having a repo for each version, but I think it's not a good idea. Does anyone have any suggestions?
[ "You need separate branches for separate versions only in the rarest of cases. You mention context managers, and they are great, and it would suck not to use them, and you are right. But for Python 2.4 you will have to not use them. So that will suck. So therefore, if you want to support Python 2.4 you'll have to write a version without context managers. But that one will work under Python 2.6 too, so there is no point in having separate versions there.\nAs for Python 3, having a separate branch there is a solution, but generally not the best one.\nFor Python 3 support there is something called 2to3 which will convert your Python 2 code to Python 3 code. It's not perfect, so quite often you will have to modify the Python 2 code to generate nice Python 3 code, but the Python 2 code has a tendency to become better as a result anyway.\nWith Distribute (a maintained fork of setuptools) you can make this conversation automatically during install. That way you don't have to have a separate branch even for Python 3. See http://bitbucket.org/tarek/distribute/src/tip/docs/python3.txt for the docs on that.\nAs Paul McGuire writes it is even possible to support Python 3 and Python 2 with the same code without using 2to3, but I would not recommend it if you want to support anything else than 2.6 and 3.x. You get too much of this ugly special hacks. With 2.6 there is enough forwards compatibility with Python 3 to make it possible to write decent looking code and support both Python 2.6 and 3.x, but not Python 2.5 and 3.x.\n", "I would try to maintain one branch to cover all the python 2.4-2.6\nThe differences are not so great, after all if you have to write a bunch of extra code for 2.4 to do something that is easy in 2.6, it will be less work for you in the long run to use the 2.4 version for 2.5 and 2.6.\nPython 3 should have a different branch, you should still try to keep as much code in common as you can.\n", "If your code is not overly dependent on the run-time performance in exception handlers, you might even get away without having a separate branch for Py3. I've managed to keep one version of pyparsing for all of my Py2.x versions, although I've had to stick with a \"lowest common denominator\" approach, meaning that I have to forego using some constructs like generator expressions, and to your point, context managers. I use dicts in place of sets, and all my generator expressions get wrapped as list comprehensions, so they will still work going back to Python 2.3. I have a block at the top of my code that takes care of a number of 2vs3 issues (contributed by pyparsing user Robert A Clark):\n_PY3K = sys.version_info[0] > 2\nif _PY3K:\n _MAX_INT = sys.maxsize\n basestring = str\n unichr = chr\n unicode = str\n _str2dict = set\n alphas = string.ascii_lowercase + string.ascii_uppercase\nelse:\n _MAX_INT = sys.maxint\n range = xrange\n def _str2dict(strg):\n return dict( [(c,0) for c in strg] )\n alphas = string.lowercase + string.uppercase\n\nThe biggest difficulty I've had has been with the incompatible syntax for catching exceptions, that was introduced in Py3, changing from \nexcept exceptiontype,varname:\n\nto\nexcept exceptionType as varname:\n\nOf course, if you don't really need the exception variable, you can just write:\nexcept exceptionType:\n\nand this will work on Py2 or Py3. But if you need to access the exception, you can still come up with a cross-version compatible syntax as:\nexcept exceptionType:\n exceptionvar = sys.exc_info()[1]\n\nThis has a minor run-time penalty, which makes this unusable in some places in pyparsing, so I still have to maintain separate Py2 and Py3 versions. For source merging, I use the utility WinMerge, which I find very good for keeping directories of source code in synch.\nSo even though I keep two versions of my code, some of these unification techniques help me to keep the differences down to the absolute incompatible minimum.\n", "I eventually decided to have 4 different forks for my project, for 2.4, 2.5, 2.6 and 3.1. My main priority is 2.6 and I don't want to compromise the elegance of that code for the sake of 2.4. So the ugly compatibility hacks will be on the lower versions, not the higher versions.\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "git", "merge", "organization", "python", "version" ]
stackoverflow_0001546917_git_merge_organization_python_version.txt
Q: Python for C++ or Java Programmer I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python. OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept. Thanks to all A: When you run a script through the Python interpreter (or import that script from another script), it actually executes all the code from beginning to end -- in that sense, there is no "entry point" to a Python script. So to work around this, Python automatically creates a __name__ variable and fills it with the value "__main__" when you are running a script by itself (as opposed to something else importing that script). That's why you'll see many scripts like: def foo(): print "Hello!" if __name__ == "__main__": foo() where all the function/class definitions are at the top, and there is a similar if-statement as the last thing in the script. You are guaranteed that Python will start executing the script from top-to-bottom, so it will read all of your definitions there. If you wanted, you could intermingle actual functional code inside all the function definitions. If this script was named bar.py, you could do python bar.py at the command line and you would see the script print out "Hello!". On the other hand, if you did import bar from another Python script, nothing would print out until you did bar.foo(), because __name__ was no longer "__main__" and the if-statement failed, thus foo was never executed. A: Excellent answer, but none points out what I think is one key insight for programmers coming to Python with background in other languages such as Java or C++: import, def and class are not "instructions to the compiler", "declarations", or other kind of magical incantations: they're executable statements like any other. For example, the def statement: def f(x): return x + 23 is almost exactly equivalent to the assignment statement: f = lambda x: x + 23 (stylistically the def is preferable as it makes f.__name__ meaningful -- that's the "almost" part; lambda is rather limited and should only ever be used when you're really keen to make an anonymous function rather than a normal named one). Similarly, class X(object): zap = 23 is equivalent to the assignment: X = type('X', (), {'zap': 23}) (again, stylistically, class is preferable, afford more generality, like def it allows decoration, etc, etc; the point I'm making is that there is semantic equivalence here). So, when you run a .py file, or import it for the first time in a program's run, Python executes its top-level statements one after the other -- in normal good Python style, most will be assignments, def, class, or import, but at least one will be a call (normally to a function) to execute that function's body of code (def, like lambda, just compiles that code; the compiled code object only executes when the function or lambda is called). Other answers have already suggested practical considerations such as testing __name__ in order to make a module that can either be run directly or imported, etc. Finally, it's best to have all "significant" code in functions (or methods in classes), not just stylistically, but because code in a function executes significantly faster (since the Python compiler can then automatically optimize all accesses to local variables). For example, consider...: import time lotsotimes = range(1000*1000) start = time.time() for x in lotsotimes: x = x + x stend = time.time() print 'in module toplev: %.6f' % (stend - start) def fun(): start = time.time() for x in lotsotimes: x = x + x stend = time.time() print 'in function body: %.6f' % (stend - start) fun() On my laptop, with Python 2.6, this emits: in module toplev: 0.405440 in function body: 0.123296 So, for code that does a lot of variable accesses and little else, running it in a function as opposed to running it as module top-level code could speed it up by more than 3 times. The detailed explanation: at module-level, all variables are inevitably kept in a dictionary, so each variable access is a dict-access; local variables of a function get optimized into a special array, so access is faster (the difference is even more extreme than the 20% or so speed-up you'd see by accessing an item in a Python list vs one in a Python dict, since the local-variable optimization also saves hashing & other ancillary costs). A: Dive into Python is a good start. I wouldn't recommend to someone with no programming experience, but if you have coded in another language before, it will help you learn python idioms quickly. A: If you are quite familiar with several languages like C++ and Java, you may find it easy to follow the official Python Tutorial. It is written in a classical language description bottom-up style from the lexical structure and syntax to more advanced concepts. The already mentioned Dive Into Python takes a top-down approach in learning languages starting from a complete program that is obscure for a beginner and diving into its details. A: I started Python over a year ago too, also C++ background. I've learned that everything is simpler in Python, you don't need to worry so much if you're doing it right, you probably are. Most of the things came natural. I can't say I've read a book or anything, I usually pested the guys in #python on freenode a lot and looked at lots of other great code out there. Good luck :) A: I second Dive in to Python as a resource. As for the main function, there isn't one. The "main" function is what you write in the script you run. So a helloworld.py looks like this: print "Hello World" and you run it with python helloworld.py That's it! A: The pithiest comment I guess is that the entry point is the 1st line of your script that is not a function or a class. You don't necessarily need to use the if hack unless you want to and your script is meant to be imported.
Python for C++ or Java Programmer
I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python. OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept. Thanks to all
[ "When you run a script through the Python interpreter (or import that script from another script), it actually executes all the code from beginning to end -- in that sense, there is no \"entry point\" to a Python script.\nSo to work around this, Python automatically creates a __name__ variable and fills it with the value \"__main__\" when you are running a script by itself (as opposed to something else importing that script). That's why you'll see many scripts like:\ndef foo():\n print \"Hello!\"\n\nif __name__ == \"__main__\":\n foo()\n\nwhere all the function/class definitions are at the top, and there is a similar if-statement as the last thing in the script. You are guaranteed that Python will start executing the script from top-to-bottom, so it will read all of your definitions there. If you wanted, you could intermingle actual functional code inside all the function definitions.\nIf this script was named bar.py, you could do python bar.py at the command line and you would see the script print out \"Hello!\".\nOn the other hand, if you did import bar from another Python script, nothing would print out until you did bar.foo(), because __name__ was no longer \"__main__\" and the if-statement failed, thus foo was never executed.\n", "Excellent answer, but none points out what I think is one key insight for programmers coming to Python with background in other languages such as Java or C++: import, def and class are not \"instructions to the compiler\", \"declarations\", or other kind of magical incantations: they're executable statements like any other. For example, the def statement:\ndef f(x): return x + 23\n\nis almost exactly equivalent to the assignment statement:\nf = lambda x: x + 23\n\n(stylistically the def is preferable as it makes f.__name__ meaningful -- that's the \"almost\" part; lambda is rather limited and should only ever be used when you're really keen to make an anonymous function rather than a normal named one). Similarly,\nclass X(object): zap = 23\n\nis equivalent to the assignment:\nX = type('X', (), {'zap': 23})\n\n(again, stylistically, class is preferable, afford more generality, like def it allows decoration, etc, etc; the point I'm making is that there is semantic equivalence here).\nSo, when you run a .py file, or import it for the first time in a program's run, Python executes its top-level statements one after the other -- in normal good Python style, most will be assignments, def, class, or import, but at least one will be a call (normally to a function) to execute that function's body of code (def, like lambda, just compiles that code; the compiled code object only executes when the function or lambda is called). Other answers have already suggested practical considerations such as testing __name__ in order to make a module that can either be run directly or imported, etc.\nFinally, it's best to have all \"significant\" code in functions (or methods in classes), not just stylistically, but because code in a function executes significantly faster (since the Python compiler can then automatically optimize all accesses to local variables). For example, consider...:\nimport time\n\nlotsotimes = range(1000*1000)\n\nstart = time.time()\nfor x in lotsotimes:\n x = x + x\nstend = time.time()\n\nprint 'in module toplev: %.6f' % (stend - start)\n\ndef fun():\n start = time.time()\n for x in lotsotimes:\n x = x + x\n stend = time.time()\n\n print 'in function body: %.6f' % (stend - start)\n\nfun()\n\nOn my laptop, with Python 2.6, this emits:\nin module toplev: 0.405440\nin function body: 0.123296\n\nSo, for code that does a lot of variable accesses and little else, running it in a function as opposed to running it as module top-level code could speed it up by more than 3 times.\nThe detailed explanation: at module-level, all variables are inevitably kept in a dictionary, so each variable access is a dict-access; local variables of a function get optimized into a special array, so access is faster (the difference is even more extreme than the 20% or so speed-up you'd see by accessing an item in a Python list vs one in a Python dict, since the local-variable optimization also saves hashing & other ancillary costs).\n", "Dive into Python is a good start. I wouldn't recommend to someone with no programming experience, but if you have coded in another language before, it will help you learn python idioms quickly.\n", "If you are quite familiar with several languages like C++ and Java, you may find it easy to follow the official Python Tutorial. It is written in a classical language description bottom-up style from the lexical structure and syntax to more advanced concepts.\nThe already mentioned Dive Into Python takes a top-down approach in learning languages starting from a complete program that is obscure for a beginner and diving into its details.\n", "I started Python over a year ago too, also C++ background. \nI've learned that everything is simpler in Python, you don't need to worry so much if you're doing it right, you probably are. Most of the things came natural.\nI can't say I've read a book or anything, I usually pested the guys in #python on freenode a lot and looked at lots of other great code out there.\nGood luck :)\n", "I second Dive in to Python as a resource. As for the main function, there isn't one. The \"main\" function is what you write in the script you run. \nSo a helloworld.py looks like this:\nprint \"Hello World\"\n\nand you run it with\npython helloworld.py\n\nThat's it!\n", "The pithiest comment I guess is that the entry point is the 1st line of your script that is not a function or a class. You don't necessarily need to use the if hack unless you want to and your script is meant to be imported.\n" ]
[ 11, 7, 5, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001548620_python.txt
Q: Efficient storage of and access to web pages with Python So like many people I want a way to download, index/extract information and store web pages efficiently. My first thought is to use MySQL and simply shove the pages in which would let me use FULLTEXT searches which would let me do ad hoc queries easily (in case I want to see if something exists and extract it/etc.). But of course performance wise I have some concerns especially with large objects/pages and high volumes of data. So that leads me to look at things like CouchDB/search engines/etc. So to summarize, my basic requirements are: It must be Python compatible (libraries/etc.) Store meta data (URL, time retrieved, any GET/POST stuff I sent), response code, etc. of the page I requested. Store a copy of the original web page as sent by the server (might be content, might be 404 search page, etc.). Extract information from the web page and store it in a database. Have the ability to do ad hoc queries on the existing corpus of original web pages (for example a new type of information I want to extract, or to see how many of the pages have the string "fizzbuzz" or whatever in them. And of course it must be open source/Linux compatible, I have no interest in something I can't modify or fiddle with. So I'm thinking several broad options are: Toss everything into MySQL, use FULLTEXT, go nuts, shard the contact if needed. Toss meta data into MySQL, store the data on the file system or something like CouchDB, write some custom search stuff. Toss meta data into MySQL, store the data on a file system with a web server (maybe /YYYY/MM/DD/HH/MM/SS/URL/), make sure there is no default index.html/etc specified (directory index each directory in other words) and use some search engine like Lucene or Sphinx index the content and use that to search. Biggest downside I see here is the inefficiency of repeatedly crawling the site. Other solutions? When answering please include links to any technologies you mention and if possible what programming languages it has libraries for (i.e. if it's Scala only or whatever it's probably not that useful since this is a Python project). If this question has already been asked (I'm sure it must have been) please let me know (I searched, no luck). A: Why do you think solution (3), the Sphinx-based one, requires "repeatedly crawling the site"? Sphinx can accept and index many different data sources, including MySQL and PostgreSQL "natively" (there are contributed add-ons for other DBs such as Firebird) -- you can keep your HTML docs as columns in your DB if you like (modern PostgreSQL versions should have no trouble with that, and I imagine that MySQL's wouldn't either), just use Sphinx superior indexing and full-text search (including stemming &c). Your metadata all comes from headers, after all (plus the HTTP request body if you want to track requests in which you POSTed data, but not the HTTP response body at any rate). One important practical consideration: I would recommend standardizing on UTF-8 -- html will come to you in all sorts of weird encodings, but there's no need to get crazy supporting that at search time -- just transcode every text page to UTF-8 upon arrival (from whatever funky encoding it came in), before storing and indexing it, and live happily ever after. Maybe you could special-case non-textual responses to keep those in files (I can imagine that devoting gigabytes in the DB to storing e.g. videos which can't be body-indexed anyway might not be a good use of resources). And BTW, Sphinx does come with Python bindings, as you request. A: You may be trying to achieve too much with the storage of the html (and supporting files). It seems you wish this repository would both allow to display a particular page as it was in its original site provide indexing for locating pages relevant to a particular search criteria The html underlying a web page once looked a bit akin to a self-standing document, but the pages crawled off the net nowadays are much messier: javascript, ajax snippets, advertisement sections, image blocks etc. This reality may cause you to rethink the one storage for all html approach. (And also the parsing / pre-processing of the material crawled, but that's another story...) On the other hand, the distinction between metadata and the true text content associated with the page doesn't need to be so marked. By "true text content", I mean [possibly partially marked-up] text from the web pages that is otherwise free of all other "Web 2.0 noise") Many search engines, including Solr (since you mentioned Lucene) now allow mixing the two genres, in the form of semi-structured data. For operational purposes (eg to task the crawlers etc.), you may keep a relational store with management related metadata, but the idea is that for search purposes, fielded and free-text info can coexist nicely (at the cost of pre-processing much of the input data). A: It sounds to me like you need a content management system. Check out Plone. If that's not what you want maybe a web framework, like Grok, BFG, Django, Turbogears, or anything on this list. If that isn't good either, then I don't know what you are asking. :-)
Efficient storage of and access to web pages with Python
So like many people I want a way to download, index/extract information and store web pages efficiently. My first thought is to use MySQL and simply shove the pages in which would let me use FULLTEXT searches which would let me do ad hoc queries easily (in case I want to see if something exists and extract it/etc.). But of course performance wise I have some concerns especially with large objects/pages and high volumes of data. So that leads me to look at things like CouchDB/search engines/etc. So to summarize, my basic requirements are: It must be Python compatible (libraries/etc.) Store meta data (URL, time retrieved, any GET/POST stuff I sent), response code, etc. of the page I requested. Store a copy of the original web page as sent by the server (might be content, might be 404 search page, etc.). Extract information from the web page and store it in a database. Have the ability to do ad hoc queries on the existing corpus of original web pages (for example a new type of information I want to extract, or to see how many of the pages have the string "fizzbuzz" or whatever in them. And of course it must be open source/Linux compatible, I have no interest in something I can't modify or fiddle with. So I'm thinking several broad options are: Toss everything into MySQL, use FULLTEXT, go nuts, shard the contact if needed. Toss meta data into MySQL, store the data on the file system or something like CouchDB, write some custom search stuff. Toss meta data into MySQL, store the data on a file system with a web server (maybe /YYYY/MM/DD/HH/MM/SS/URL/), make sure there is no default index.html/etc specified (directory index each directory in other words) and use some search engine like Lucene or Sphinx index the content and use that to search. Biggest downside I see here is the inefficiency of repeatedly crawling the site. Other solutions? When answering please include links to any technologies you mention and if possible what programming languages it has libraries for (i.e. if it's Scala only or whatever it's probably not that useful since this is a Python project). If this question has already been asked (I'm sure it must have been) please let me know (I searched, no luck).
[ "Why do you think solution (3), the Sphinx-based one, requires \"repeatedly crawling the site\"? Sphinx can accept and index many different data sources, including MySQL and PostgreSQL \"natively\" (there are contributed add-ons for other DBs such as Firebird) -- you can keep your HTML docs as columns in your DB if you like (modern PostgreSQL versions should have no trouble with that, and I imagine that MySQL's wouldn't either), just use Sphinx superior indexing and full-text search (including stemming &c). Your metadata all comes from headers, after all (plus the HTTP request body if you want to track requests in which you POSTed data, but not the HTTP response body at any rate).\nOne important practical consideration: I would recommend standardizing on UTF-8 -- html will come to you in all sorts of weird encodings, but there's no need to get crazy supporting that at search time -- just transcode every text page to UTF-8 upon arrival (from whatever funky encoding it came in), before storing and indexing it, and live happily ever after.\nMaybe you could special-case non-textual responses to keep those in files (I can imagine that devoting gigabytes in the DB to storing e.g. videos which can't be body-indexed anyway might not be a good use of resources).\nAnd BTW, Sphinx does come with Python bindings, as you request.\n", "You may be trying to achieve too much with the storage of the html (and supporting files). It seems you wish this repository would both\n\nallow to display a particular page as it was in its original site\nprovide indexing for locating pages relevant to a particular search criteria\n\nThe html underlying a web page once looked a bit akin to a self-standing document, but the pages crawled off the net nowadays are much messier: javascript, ajax snippets, advertisement sections, image blocks etc.\nThis reality may cause you to rethink the one storage for all html approach. (And also the parsing / pre-processing of the material crawled, but that's another story...)\nOn the other hand, the distinction between metadata and the true text content associated with the page doesn't need to be so marked. By \"true text content\", I mean [possibly partially marked-up] text from the web pages that is otherwise free of all other \"Web 2.0 noise\") Many search engines, including Solr (since you mentioned Lucene) now allow mixing the two genres, in the form of semi-structured data. For operational purposes (eg to task the crawlers etc.), you may keep a relational store with management related metadata, but the idea is that for search purposes, fielded and free-text info can coexist nicely (at the cost of pre-processing much of the input data).\n", "It sounds to me like you need a content management system. Check out Plone. If that's not what you want maybe a web framework, like Grok, BFG, Django, Turbogears, or anything on this list. If that isn't good either, then I don't know what you are asking. :-)\n" ]
[ 2, 1, 0 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0001548857_database_mysql_python.txt
Q: How to set an nonexistent field in Python ClientForm? I'm using mechanize (which uses clientform) for some web crawling in python and since it doesn't support JS, I want to set a value of an unexistent input in a form (the input is generated by JS). How can I do this? The error is similar to the one you get if you try to execute from mechanize import Browser br = Browser() page = br.open('http://google.com') br.select_form(nr = 0) br['unexistent'] = 'hello' A: You need to first add the control to the form, and then fixup the form. br.form.new_control('text','unexistent',{'value':''}) br.form.fixup() br['unexistent'] = 'hello' This really isn't very well documented, and in the source under fixup() there is the comment: This method should only be called once, after all controls have been added to the form. However, it doesn't look like it does anything too dangerous. Probably at least add the control first before messing with anything else in the form.
How to set an nonexistent field in Python ClientForm?
I'm using mechanize (which uses clientform) for some web crawling in python and since it doesn't support JS, I want to set a value of an unexistent input in a form (the input is generated by JS). How can I do this? The error is similar to the one you get if you try to execute from mechanize import Browser br = Browser() page = br.open('http://google.com') br.select_form(nr = 0) br['unexistent'] = 'hello'
[ "You need to first add the control to the form, and then fixup the form.\nbr.form.new_control('text','unexistent',{'value':''})\nbr.form.fixup()\nbr['unexistent'] = 'hello'\n\nThis really isn't very well documented, and in the source under fixup() there is the comment:\nThis method should only be called once, after all controls have been\nadded to the form.\n\nHowever, it doesn't look like it does anything too dangerous. Probably at least add the control first before messing with anything else in the form.\n" ]
[ 17 ]
[]
[]
[ "clientform", "mechanize", "python" ]
stackoverflow_0001548996_clientform_mechanize_python.txt
Q: how to define a widget in a model attribute Simply, I write: # forms.py class NoteForm(ModelForm): def __init__(self, *args, **kwargs): super(NoteForm, self).__init__(*args, **kwargs) #add attributes to html-field-tag: self.fields['content'].widget.attrs['rows'] = 3 self.fields['title'].widget.attrs['size'] = 20 class Meta: model = Note fields = ('title','content') To add or modify some attributes to the HTML tag field. But in this time, I will have to do it directly in the Note model in models.py #models.py class Note(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=255) #how to define the fields.widget.attrs here ????? Just FYI: Why? Because is going to work as a NotesFormSet = inlineformset_factory(NoteBook, Note, extra=10) To add many Notes when adding/editing a NoteBook NOTE: It is not django admin If im not giving you sufficient context, comment plz, any hint is apreciated =') A: No, you still do it in a form, but you just pass that form as a parameter to inlineformset_factory. NotesFormSet = inlineformset_factory(NoteBook, Note, extra=10, form=NoteForm)
how to define a widget in a model attribute
Simply, I write: # forms.py class NoteForm(ModelForm): def __init__(self, *args, **kwargs): super(NoteForm, self).__init__(*args, **kwargs) #add attributes to html-field-tag: self.fields['content'].widget.attrs['rows'] = 3 self.fields['title'].widget.attrs['size'] = 20 class Meta: model = Note fields = ('title','content') To add or modify some attributes to the HTML tag field. But in this time, I will have to do it directly in the Note model in models.py #models.py class Note(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=255) #how to define the fields.widget.attrs here ????? Just FYI: Why? Because is going to work as a NotesFormSet = inlineformset_factory(NoteBook, Note, extra=10) To add many Notes when adding/editing a NoteBook NOTE: It is not django admin If im not giving you sufficient context, comment plz, any hint is apreciated =')
[ "No, you still do it in a form, but you just pass that form as a parameter to inlineformset_factory.\nNotesFormSet = inlineformset_factory(NoteBook, Note, extra=10, form=NoteForm)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0001549011_django_django_forms_python.txt
Q: Generate a string representation of a one-hot encoding In Python, I need to generate a dict that maps a letter to a pre-defined "one-hot" representation of that letter. By way of illustration, the dict should look like this: { 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', 'B': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', # ... } There is one bit (represented as a character) per letter of the alphabet. Hence each string will contain 25 zeros and one 1. The position of the 1 is determined by the position of the corresponding letter in the alphabet. I came up with some code that generates this: # Character set is explicitly specified for fine grained control _letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" n = len(_letters) one_hot = [' '.join(['0']*a + ['1'] + ['0']*b) for a, b in zip(range(n), range(n-1, -1, -1))] outputs = dict(zip(_letters, one_hot)) Is there a more efficient/cleaner/more pythonic way to do the same thing? A: I find this to be more readable: from string import ascii_uppercase one_hot = {} for i, l in enumerate(ascii_uppercase): bits = ['0']*26; bits[i] = '1' one_hot[l] = ' '.join(bits) If you need a more general alphabet, just enumerate over a string of the characters, and replace ['0']*26 with ['0']*len(alphabet). A: In Python 2.5 and up you can use the conditional operator: from string import ascii_uppercase one_hot = {} for i, c in enumerate(ascii_uppercase): one_hot[c] = ' '.join('1' if j == i else '0' for j in range(26)) A: one_hot = [' '.join(['0']*a + ['1'] + ['0']*b) for a, b in zip(range(n), range(n-1, -1, -1))] outputs = dict(zip(_letters, one_hot)) In particular, there's a lot of code packed into these two lines. You might try the Introduce Explaining Variable refactoring. Or maybe an extract method. Here's one example: def single_onehot(a, b): return ' '.join(['0']*a + ['1'] + ['0']*b) range_zip = zip(range(n), range(n-1, -1, -1)) one_hot = [ single_onehot(a, b) for a, b in range_zip] outputs = dict(zip(_letters, one_hot)) Although you might disagree with my naming.
Generate a string representation of a one-hot encoding
In Python, I need to generate a dict that maps a letter to a pre-defined "one-hot" representation of that letter. By way of illustration, the dict should look like this: { 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', 'B': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', # ... } There is one bit (represented as a character) per letter of the alphabet. Hence each string will contain 25 zeros and one 1. The position of the 1 is determined by the position of the corresponding letter in the alphabet. I came up with some code that generates this: # Character set is explicitly specified for fine grained control _letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" n = len(_letters) one_hot = [' '.join(['0']*a + ['1'] + ['0']*b) for a, b in zip(range(n), range(n-1, -1, -1))] outputs = dict(zip(_letters, one_hot)) Is there a more efficient/cleaner/more pythonic way to do the same thing?
[ "I find this to be more readable:\nfrom string import ascii_uppercase\n\none_hot = {}\nfor i, l in enumerate(ascii_uppercase):\n bits = ['0']*26; bits[i] = '1'\n one_hot[l] = ' '.join(bits)\n\nIf you need a more general alphabet, just enumerate over a string of the characters, and replace ['0']*26 with ['0']*len(alphabet).\n", "In Python 2.5 and up you can use the conditional operator:\nfrom string import ascii_uppercase\n\none_hot = {}\nfor i, c in enumerate(ascii_uppercase):\n one_hot[c] = ' '.join('1' if j == i else '0' for j in range(26))\n\n", "one_hot = [' '.join(['0']*a + ['1'] + ['0']*b)\n for a, b in zip(range(n), range(n-1, -1, -1))]\noutputs = dict(zip(_letters, one_hot))\n\nIn particular, there's a lot of code packed into these two lines. You might try the Introduce Explaining Variable refactoring. Or maybe an extract method.\nHere's one example:\ndef single_onehot(a, b):\n return ' '.join(['0']*a + ['1'] + ['0']*b)\n\nrange_zip = zip(range(n), range(n-1, -1, -1))\none_hot = [ single_onehot(a, b) for a, b in range_zip]\noutputs = dict(zip(_letters, one_hot))\n\nAlthough you might disagree with my naming.\n" ]
[ 7, 2, 1 ]
[ "That seems pretty clear, concise, and Pythonic to me.\n" ]
[ -1 ]
[ "data_generation", "python" ]
stackoverflow_0001548984_data_generation_python.txt
Q: Help with JSON format I'm using a JSON example off the web, as seen below. { "menu": "File", "commands": [ { "title": "New", "action":"CreateDoc" }, { "title": "Open", "action": "OpenDoc" }, { "title": "Close", "action": "CloseDoc" } ] } I've tried loading this in two different parsers, one in C++ and in Python. Here's Python's traceback. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/json/__init__.py", line 267, in load parse_constant=parse_constant, **kw) File "/usr/lib/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.6/json/decoder.py", line 338, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded And here's what jsoncpp reports. * Line 1, Column 1 Syntax error: value, object or array expected. Any clue what I'm doing wrong? Edit: Ok, here's some code. For some reason now Python's working. I didn't do anything but go to the store. That must be a Python feature -- goto the store, random errors go away. Those Python devs are geniuses. But to the point. Here's the C++ code. bool CFG::CFG_Init( const char* path ) { bool r = reader.parse( path, root ); if( r ) { return true; } else { std::cout << reader.getFormatedErrorMessages() << std::endl; return false; } } I've tried this where 'path' was a std::string as well -- same thing. I'm calling the method like this: if( !CFG_Init("test.json") ) { error("Couldn't load configuration."); } And here's the class. class CFG: virtual Evaluator { Json::Reader reader; public: Json::Value root; bool CFG_Init( const char* path); Json::Value CFG_Fetch_Raw(Json::Value section, std::string key, Json::Value defval); Json::Value CFG_Fetch(Json::Value section, std::string key, Json::Value defval ); }; A: Ok, after looking at jsoncpp's code, I realize my error. It wants the document as a string, not a file name. A: It's your parser apparently. I can import correctly the file with simplejson parser in django >>> from django.utils import simplejson as sj >>> f=file("x.json") >>> sj.load(f) {u'menu': u'File', u'commands': [{u'action': u'CreateDoc', u'title': u'New'}, {u'action': u'OpenDoc', u'title': u'Open'}, {u'action': u'CloseDoc', u'title': u'Close'}]} >>> A: That JSON looks perfectly fine. I would check the code that you are using to load it, to make sure that you are loading that file correctly, and using the right encoding for reading the file from disk. Make sure you don't have any problems like trying to read a UTF-16 file as UTF-8, or trying to read CRLF terminated lines in something expecting linefeeds, or reading a file that begins with a BOM with code that doesn't know how to skip it, or anything of the sort. Take a look at the file in a hex editor to check for any invisible characters that might be throwing things off.
Help with JSON format
I'm using a JSON example off the web, as seen below. { "menu": "File", "commands": [ { "title": "New", "action":"CreateDoc" }, { "title": "Open", "action": "OpenDoc" }, { "title": "Close", "action": "CloseDoc" } ] } I've tried loading this in two different parsers, one in C++ and in Python. Here's Python's traceback. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/json/__init__.py", line 267, in load parse_constant=parse_constant, **kw) File "/usr/lib/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.6/json/decoder.py", line 338, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded And here's what jsoncpp reports. * Line 1, Column 1 Syntax error: value, object or array expected. Any clue what I'm doing wrong? Edit: Ok, here's some code. For some reason now Python's working. I didn't do anything but go to the store. That must be a Python feature -- goto the store, random errors go away. Those Python devs are geniuses. But to the point. Here's the C++ code. bool CFG::CFG_Init( const char* path ) { bool r = reader.parse( path, root ); if( r ) { return true; } else { std::cout << reader.getFormatedErrorMessages() << std::endl; return false; } } I've tried this where 'path' was a std::string as well -- same thing. I'm calling the method like this: if( !CFG_Init("test.json") ) { error("Couldn't load configuration."); } And here's the class. class CFG: virtual Evaluator { Json::Reader reader; public: Json::Value root; bool CFG_Init( const char* path); Json::Value CFG_Fetch_Raw(Json::Value section, std::string key, Json::Value defval); Json::Value CFG_Fetch(Json::Value section, std::string key, Json::Value defval ); };
[ "Ok, after looking at jsoncpp's code, I realize my error. It wants the document as a string, not a file name.\n", "It's your parser apparently. I can import correctly the file with simplejson parser in django\n>>> from django.utils import simplejson as sj\n>>> f=file(\"x.json\")\n>>> sj.load(f)\n{u'menu': u'File', u'commands': [{u'action': u'CreateDoc', u'title': u'New'}, {u'action': u'OpenDoc', u'title': u'Open'}, {u'action': u'CloseDoc', u'title': u'Close'}]}\n>>> \n\n", "That JSON looks perfectly fine. I would check the code that you are using to load it, to make sure that you are loading that file correctly, and using the right encoding for reading the file from disk. Make sure you don't have any problems like trying to read a UTF-16 file as UTF-8, or trying to read CRLF terminated lines in something expecting linefeeds, or reading a file that begins with a BOM with code that doesn't know how to skip it, or anything of the sort. Take a look at the file in a hex editor to check for any invisible characters that might be throwing things off.\n" ]
[ 11, 1, 1 ]
[]
[]
[ "c++", "json", "python" ]
stackoverflow_0001549292_c++_json_python.txt
Q: Project Euler # 255 Project euler problem #255 is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work for 10^13 and 10^14? def ceil(a, b): return (a + b - 1) / b; def func(a, b): return (b + ceil(a, b)) / 2; def calculate(a): ctr = 1; y = 200; while 1: z = func(a, y); if z == y: return ctr; y = z; ctr += 1; result = sum(map(calculate, xrange(10000, 100000))) / 9e4; print "%.10f" % result; This gives 3.2102888889. A: Don't use map. It generates a big list in memory. Don't use xrange. It is limited to short integers. Use generators instead. # No changes on `ceil()`, `func()` and `calculate()` def generate_sequence(start, stop): while start < stop: yield start start += 1 result = sum(calculate(n) for n in generate_sequence(10**13, 10**14)) print "%.10f" % result; That will run. But it will take a long time to sum 10**14 - 10**13 = 90,000,000,000,000 results. Maybe there's something else you can do to optimize (hint, hint) A: Even a very fast calculation for each number will take too long. To satisfy the 1 minute rule you'd need to solve/add 1.5 Trillion numbers per second. I think there must be a way to compute the result more directly. A: 90,000,000,000,000 is a lot of numbers to check, I tried checking every millionth number and thought the average would be close enough, but to no avail. A: 3.6.3 XRange Type : "3.6.3 XRange Type The xrange type is an immutable sequence which is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages. XRange objects have very little behavior: they only support indexing, iteration, and the len() function." maybe ... optimize your floor and ceiling functions? :P
Project Euler # 255
Project euler problem #255 is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work for 10^13 and 10^14? def ceil(a, b): return (a + b - 1) / b; def func(a, b): return (b + ceil(a, b)) / 2; def calculate(a): ctr = 1; y = 200; while 1: z = func(a, y); if z == y: return ctr; y = z; ctr += 1; result = sum(map(calculate, xrange(10000, 100000))) / 9e4; print "%.10f" % result; This gives 3.2102888889.
[ "Don't use map. It generates a big list in memory.\nDon't use xrange. It is limited to short integers.\nUse generators instead.\n# No changes on `ceil()`, `func()` and `calculate()`\n\ndef generate_sequence(start, stop):\n while start < stop:\n yield start\n start += 1\n\nresult = sum(calculate(n) for n in generate_sequence(10**13, 10**14))\nprint \"%.10f\" % result;\n\nThat will run. But it will take a long time to sum 10**14 - 10**13 = 90,000,000,000,000 results. Maybe there's something else you can do to optimize (hint, hint)\n", "Even a very fast calculation for each number will take too long. To satisfy the 1 minute rule you'd need to solve/add 1.5 Trillion numbers per second.\nI think there must be a way to compute the result more directly.\n", "90,000,000,000,000 is a lot of numbers to check, I tried checking every millionth number and thought the average would be close enough, but to no avail.\n", "3.6.3 XRange Type :\n\n\"3.6.3 XRange Type\nThe xrange type is an immutable\n sequence which is commonly used for\n looping. The advantage of the xrange\n type is that an xrange object will\n always take the same amount of memory,\n no matter the size of the range it\n represents. There are no consistent\n performance advantages.\nXRange objects have very little\n behavior: they only support indexing,\n iteration, and the len() function.\"\n\nmaybe ... optimize your floor and ceiling functions? :P\n" ]
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001427040_python.txt
Q: How to create a specific if condition templatetag with Django? My problem is a if condition. I would like somethings like that but cannot figure out how to do it. {% if restaurant.is_favorite_of(user) %} <img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" /> {% else %} <img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" /> {% endif %} In the Favorite manager, I created : def is_favorite(self, user, content_object): """ This method returns : - True if content_object is favorite of user - False if not >>> user = User.objects.get(username="alice") >>> fav_user = User.objects.get(username="bob") >>> fav1 = Favorite.create_favorite(user, fav_user) >>> Favorite.objects.is_favorite(user, fav_user) True >>> Favorite.objects.is_favorite(user, user) False >>> Favorite.objects.all().delete() Above if we test if bob is favorite of alice it is true. But alice is not favorite of alice. """ ct = ContentType.objects.get_for_model(type(content_object)) try: self.filter(user=user).filter(content_type = ct).get(object_id = content_object.id) return True except Favorite.DoesNotExist: return False Because in Django templates there is no way of doing it likes this, I could do a templatetag that act like that : {% is_favorite user resto %} <img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" /> {% else %} <img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" /> {% endif %} But how to do it ? Do you have a better idea ? A: Easiest way is to create a filter. @register.filter def is_favourite_of(object, user): return Favourite.objects.is_favourite(user, object) and in the template: {% if restaurant|is_favourite_of:user %} A: Maybe I could use the inclusion tag. Create a tag like that : {% show_favorite_img user restaurant %} templatetags/user_extra.py : @register.inclusion_tag('users/favorites.html') def show_favorite_img(user, restaurant): return {'is_favorite': Favorite.objects.is_favorite(user, restaurant)} A: When all else fails you can use the {% expr whatever %} tag to compute a value and stick it in a variable that you can use in your template. I don't let designers know about it, but sometimes it's the only thing that works short of standing on your head and ... well, you know. See http://www.djangosnippets.org/snippets/9/
How to create a specific if condition templatetag with Django?
My problem is a if condition. I would like somethings like that but cannot figure out how to do it. {% if restaurant.is_favorite_of(user) %} <img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" /> {% else %} <img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" /> {% endif %} In the Favorite manager, I created : def is_favorite(self, user, content_object): """ This method returns : - True if content_object is favorite of user - False if not >>> user = User.objects.get(username="alice") >>> fav_user = User.objects.get(username="bob") >>> fav1 = Favorite.create_favorite(user, fav_user) >>> Favorite.objects.is_favorite(user, fav_user) True >>> Favorite.objects.is_favorite(user, user) False >>> Favorite.objects.all().delete() Above if we test if bob is favorite of alice it is true. But alice is not favorite of alice. """ ct = ContentType.objects.get_for_model(type(content_object)) try: self.filter(user=user).filter(content_type = ct).get(object_id = content_object.id) return True except Favorite.DoesNotExist: return False Because in Django templates there is no way of doing it likes this, I could do a templatetag that act like that : {% is_favorite user resto %} <img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" /> {% else %} <img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" /> {% endif %} But how to do it ? Do you have a better idea ?
[ "Easiest way is to create a filter.\[email protected]\ndef is_favourite_of(object, user):\n return Favourite.objects.is_favourite(user, object)\n\nand in the template:\n{% if restaurant|is_favourite_of:user %}\n\n", "Maybe I could use the inclusion tag.\nCreate a tag like that :\n{% show_favorite_img user restaurant %}\n\ntemplatetags/user_extra.py :\[email protected]_tag('users/favorites.html')\ndef show_favorite_img(user, restaurant):\n return {'is_favorite': Favorite.objects.is_favorite(user, restaurant)}\n\n", "When all else fails you can use the {% expr whatever %} tag to compute a value and stick it in a variable that you can use in your template. I don't let designers know about it, but sometimes it's the only thing that works short of standing on your head and ... well, you know.\nSee http://www.djangosnippets.org/snippets/9/\n" ]
[ 11, 2, 0 ]
[]
[]
[ "django", "django_templates", "favorites", "python" ]
stackoverflow_0001546816_django_django_templates_favorites_python.txt
Q: How do do this list manipulation in Python? This is tricky Suppose I have this list: [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] What is the MOST efficient way to turn it into this list? [ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] Notice, I grab the first from each. Then the 2nd element from each. Of course, this function needs to be done with X elements. I've tried it, but mine has many loops,and I think it's too long and complicated. Thanks. A: >>> L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] >>> L2 = [] >>> map(L2.extend, zip(*L1)) >>> L2 [5, 7, 1, 44, 21, 32, 73, 99, 100] A: import itertools list(itertools.chain(*zip(*L1))) If you need lists of varying length: import itertools [x for x in itertools.chain(*itertools.izip_longest(*L1)) if x is not None] A: "One-liner" != "Pythonic" It is bad form to use a list comprehension just to implement a for loop in one line. Save the list expressions or generator expressions for times when you want the results of the expression. The clearest and most Pythonic to my eye is (for sublists of equal length): L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] L2 = [] for nextitems in zip(*L1): L2.extend(nextitems) Sure you could write this as: [ L2.extend(nextitems) for nextitems in zip(*L1) ] but this generates a list of [None,None,...] as long as the number of items in each sublist, since extend() returns None. And what are we doing with this list? Nothing, and so it gets discarded immediately. But the reader has to look at this for a bit before realizing that this list is "built" for the purpose of running extend() on each created sublist. The Pythonicness is given by the use of zip and *L1 to pass the sublists of L as args to zip. List comprehensions are generally regarded as Pythonic too, but when they are used for the purpose of creating a list of things, not as a clever shortcut for a for loop. A: As long as all sublists are the same length: def flattener(nestedlist): if not nestedlist: return [] return [ x for i in range(len(nestedlist[0])) for x in [sublist[i] for sublist in nestedlist] ] For example, print flattener([ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]) emits exactly the flat list you desire. If not all sublist need be the same length, what do you want to happen when some are longer, some shorter...? A precise spec is needed if you need to take such inequality into account. A: >>> L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] >>> L2 = list(sum(zip(*L1), ())) >>> L2 [5, 7, 1, 44, 21, 32, 73, 99, 100] A: Here is an O^2 solution, it assumes all the inner arrays are of the same length parent = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] final = [] for i in range(len(parent[0])): for x in range(len(parent)): final.append(parent[x][i]) print final # [5, 7, 1, 44, 21, 32, 73, 99, 100] A: A simple list comprehension to the second depth: >>> L = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] >>> [x for li in zip(*L) for x in li] [5, 7, 1, 44, 21, 32, 73, 99, 100] pretty nice. If the sublists are of uneven length, it is not as elegant to express: >>> L = [ [5, 44, 73] , [7], [1, 32, 100, 101] ] >>> [li[idx] for idx in xrange(max(map(len, L))) for li in L if idx < len(li)] [5, 7, 1, 44, 32, 73, 100, 101] These solutions are of complexity O(n), where n is the total number of elements. A: As long as all the sublists are of the same length: lst = [[5, 44, 73] , [7, 21, 99], [1, 32, 100]] list(reduce(lambda l, r: l + r, zip(*lst))) Edit: This will work with sublists of different lengths: lst = [[5, 44, 73, 23] , [7, 21, 99], [1, 32, 100]] list(filter(lambda p: p is not None, reduce(lambda x, y: x + y, map(None, *lst))))
How do do this list manipulation in Python? This is tricky
Suppose I have this list: [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] What is the MOST efficient way to turn it into this list? [ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] Notice, I grab the first from each. Then the 2nd element from each. Of course, this function needs to be done with X elements. I've tried it, but mine has many loops,and I think it's too long and complicated. Thanks.
[ ">>> L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]\n>>> L2 = []\n>>> map(L2.extend, zip(*L1))\n>>> L2\n[5, 7, 1, 44, 21, 32, 73, 99, 100]\n\n", "import itertools\nlist(itertools.chain(*zip(*L1)))\n\nIf you need lists of varying length:\nimport itertools\n[x for x in itertools.chain(*itertools.izip_longest(*L1)) if x is not None]\n\n", "\"One-liner\" != \"Pythonic\"\nIt is bad form to use a list comprehension just to implement a for loop in one line. Save the list expressions or generator expressions for times when you want the results of the expression. The clearest and most Pythonic to my eye is (for sublists of equal length):\nL1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]\nL2 = []\nfor nextitems in zip(*L1):\n L2.extend(nextitems)\n\nSure you could write this as:\n[ L2.extend(nextitems) for nextitems in zip(*L1) ]\n\nbut this generates a list of [None,None,...] as long as the number of items in each sublist, since extend() returns None. And what are we doing with this list? Nothing, and so it gets discarded immediately. But the reader has to look at this for a bit before realizing that this list is \"built\" for the purpose of running extend() on each created sublist.\nThe Pythonicness is given by the use of zip and *L1 to pass the sublists of L as args to zip. List comprehensions are generally regarded as Pythonic too, but when they are used for the purpose of creating a list of things, not as a clever shortcut for a for loop.\n", "As long as all sublists are the same length:\ndef flattener(nestedlist):\n if not nestedlist: return []\n return [ x for i in range(len(nestedlist[0]))\n for x in [sublist[i] for sublist in nestedlist]\n ]\n\nFor example,\nprint flattener([ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ])\n\nemits exactly the flat list you desire.\nIf not all sublist need be the same length, what do you want to happen when some are longer, some shorter...? A precise spec is needed if you need to take such inequality into account.\n", ">>> L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]\n>>> L2 = list(sum(zip(*L1), ()))\n>>> L2\n[5, 7, 1, 44, 21, 32, 73, 99, 100]\n\n", "Here is an O^2 solution, it assumes all the inner arrays are of the same length\nparent = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]\nfinal = []\nfor i in range(len(parent[0])):\n for x in range(len(parent)):\n final.append(parent[x][i])\nprint final # [5, 7, 1, 44, 21, 32, 73, 99, 100]\n\n", "A simple list comprehension to the second depth:\n>>> L = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]\n>>> [x for li in zip(*L) for x in li]\n[5, 7, 1, 44, 21, 32, 73, 99, 100]\n\npretty nice. If the sublists are of uneven length, it is not as elegant to express:\n>>> L = [ [5, 44, 73] , [7], [1, 32, 100, 101] ]\n>>> [li[idx] for idx in xrange(max(map(len, L))) for li in L if idx < len(li)]\n[5, 7, 1, 44, 32, 73, 100, 101]\n\nThese solutions are of complexity O(n), where n is the total number of elements.\n", "As long as all the sublists are of the same length:\nlst = [[5, 44, 73] , [7, 21, 99], [1, 32, 100]]\nlist(reduce(lambda l, r: l + r, zip(*lst)))\n\nEdit: This will work with sublists of different lengths:\nlst = [[5, 44, 73, 23] , [7, 21, 99], [1, 32, 100]]\nlist(filter(lambda p: p is not None, reduce(lambda x, y: x + y, map(None, *lst))))\n\n" ]
[ 10, 8, 4, 2, 1, 0, 0, -2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001549445_list_python.txt
Q: Why does this happen in my template for Django? simple%20minds is displayed when do this: {{ rec.artist_name }} How do I remove the %20...and make it spaces? When I put | safe as a fitler, the error is: Could not parse the remainder: ' | safe' from 'active.artist_name | safe' Thanks. A: I think you're being hit by Django's relatively-new autoescaping. What happens if you do {{ rec.artist_name | safe }} to avid the value being autoescaped? A: Try removing the space between the rec.artist_name and the |. So you should have this: {{ rec.artist_name|safe }} That'll fix the autoescaping, but I think the other commentors are correct in saying that you're storing the %20 into the db. So you'll probably have to fix it on that end of things.
Why does this happen in my template for Django?
simple%20minds is displayed when do this: {{ rec.artist_name }} How do I remove the %20...and make it spaces? When I put | safe as a fitler, the error is: Could not parse the remainder: ' | safe' from 'active.artist_name | safe' Thanks.
[ "I think you're being hit by Django's relatively-new autoescaping. What happens if you do \n{{ rec.artist_name | safe }}\n\nto avid the value being autoescaped?\n", "Try removing the space between the rec.artist_name and the |. So you should have this: \n{{ rec.artist_name|safe }}\nThat'll fix the autoescaping, but I think the other commentors are correct in saying that you're storing the %20 into the db. So you'll probably have to fix it on that end of things.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001549606_django_python.txt
Q: How to do nested Django SELECT? class Friendship(models.Model): from_friend = models.ForeignKey(User, related_name='friend_set') to_friend = models.ForeignKey(User, related_name='to_friend_set') I'd like to SELECT all to_friends that have from_friend = a certain User. Then, I'd like to pass to_friends to inside filter in another .objects.filter(). Is this the way to do it? Thanks! A: I'd like to SELECT all to_friends that have from_friend = a certain User. You could get all the Friendship objects for this step like so: friendships = Friendship.objects.filter(from_friend=some_user) Then you can get all the to_friend fields into a flat list using the values_list method of a query set: friends = friendships.values_list("to_friend", flat=True) At this point friends is a ValuesListQuery object that works just like a list. You can iterate over the friends and use the values in other filter() calls. A: As pccardune says, you get the relevant users like this: friendships = Friendship.objects.filter(from_friend=some_user) But in fact you can pass this directly into your next query: second_select = Whatever.objects.filter(friend__in=friendships) A: This appears to return the desired results User.objects.filter(to_friend_set__from_friend=1)
How to do nested Django SELECT?
class Friendship(models.Model): from_friend = models.ForeignKey(User, related_name='friend_set') to_friend = models.ForeignKey(User, related_name='to_friend_set') I'd like to SELECT all to_friends that have from_friend = a certain User. Then, I'd like to pass to_friends to inside filter in another .objects.filter(). Is this the way to do it? Thanks!
[ "\nI'd like to SELECT all to_friends that have from_friend = a certain User.\n\nYou could get all the Friendship objects for this step like so:\nfriendships = Friendship.objects.filter(from_friend=some_user)\n\nThen you can get all the to_friend fields into a flat list using the values_list method of a query set:\nfriends = friendships.values_list(\"to_friend\", flat=True)\n\nAt this point friends is a ValuesListQuery object that works just like a list. You can iterate over the friends and use the values in other filter() calls.\n", "As pccardune says, you get the relevant users like this:\nfriendships = Friendship.objects.filter(from_friend=some_user)\n\nBut in fact you can pass this directly into your next query:\nsecond_select = Whatever.objects.filter(friend__in=friendships)\n\n", "This appears to return the desired results\nUser.objects.filter(to_friend_set__from_friend=1)\n\n" ]
[ 3, 2, 2 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0001547494_django_mysql_python.txt
Q: Regex From .NET to Python I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#: ((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.)) I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception). It is a lame question/request, but I have been staring at this for a while, but nothing obvious is jumping out at me. Note: I am simply trying r = re.compile('((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.))') Thanks, Scott A: There are some syntax incompatibilities between .NET regexps and PCRE/Python regexps : (?<name>...) is (?P<name>...) (?...) does not exist, and as I don't know what it is used for in .NET I can't guess any equivalent. A Google codesearch do not give me any pointer to what it could be used for. Besides, you should use Python raw strings (r"I am a raw string") instead of normal strings when expressing regexps : raw strings do not interpret escape sequences (like \n). But it is not the problem in your example as you're not using any known escape sequence which could be replaced (\s does not mean anything as an escape sequence, so it is not replaced). A: Is "(?" there to prevent creation of a separate group? In Python's re's, this is "(:?". Try this: r = re.compile(r'((^|\s))(:?<tag>\@(:?<tagname>(\w|\+)+))(:?($|\s|\.))') Also, note the use of a raw string literal (the "r" character just before the quotes). Raw literals suppress '\' escaping, so that your '\' characters pass straight through to re (otherwise, you'd need '\\' for every '\').
Regex From .NET to Python
I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#: ((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.)) I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception). It is a lame question/request, but I have been staring at this for a while, but nothing obvious is jumping out at me. Note: I am simply trying r = re.compile('((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.))') Thanks, Scott
[ "There are some syntax incompatibilities between .NET regexps and PCRE/Python regexps :\n\n(?<name>...) is (?P<name>...)\n(?...) does not exist, and as I don't know what it is used for in .NET I can't guess any equivalent. A Google codesearch do not give me any pointer to what it could be used for.\n\nBesides, you should use Python raw strings (r\"I am a raw string\") instead of normal strings when expressing regexps : raw strings do not interpret escape sequences (like \\n). But it is not the problem in your example as you're not using any known escape sequence which could be replaced (\\s does not mean anything as an escape sequence, so it is not replaced).\n", "Is \"(?\" there to prevent creation of a separate group? In Python's re's, this is \"(:?\". Try this:\nr = re.compile(r'((^|\\s))(:?<tag>\\@(:?<tagname>(\\w|\\+)+))(:?($|\\s|\\.))')\n\nAlso, note the use of a raw string literal (the \"r\" character just before the quotes). Raw literals suppress '\\' escaping, so that your '\\' characters pass straight through to re (otherwise, you'd need '\\\\' for every '\\').\n" ]
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001549716_python_regex.txt
Q: Unexpected result on a simple example # Barn yard example: counting heads and legs def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks if totLegs == numLegs: return [numPigs, numChicks] return [None, None] def barnYard(heads, legs): pigs, chickens = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens barnYard(20,56) Expected result is 8 and 12 I think, but it returns 'There is no solution'. What am I doing wrong? I'm just starting with programming, so please be nice ... :) A: look at your indentation. return [None, None] is inside the loop. it returns [None, None] after the first iteration A: In solve(), your return statement is indented to be inside of the for loop. Back it out one level, and it should work just fine. def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks if totLegs == numLegs: return [numPigs, numChicks] return [None, None]
Unexpected result on a simple example
# Barn yard example: counting heads and legs def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks if totLegs == numLegs: return [numPigs, numChicks] return [None, None] def barnYard(heads, legs): pigs, chickens = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens barnYard(20,56) Expected result is 8 and 12 I think, but it returns 'There is no solution'. What am I doing wrong? I'm just starting with programming, so please be nice ... :)
[ "look at your indentation. return [None, None] is inside the loop. it returns [None, None] after the first iteration\n", "In solve(), your return statement is indented to be inside of the for loop. Back it out one level, and it should work just fine.\ndef solve(numLegs, numHeads):\n for numChicks in range(0, numHeads + 1):\n numPigs = numHeads - numChicks\n totLegs = 4*numPigs + 2*numChicks\n if totLegs == numLegs:\n return [numPigs, numChicks]\n return [None, None]\n\n" ]
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001549795_python.txt
Q: Python 3.1.1 with --enable-shared : will not build any extensions Summary: Building Python 3.1 on RHEL 5.3 64 bit with --enable-shared fails to compile all extensions. Building "normal" works fine without any problems. Please note that this question may seem to blur the line between programming and system administration. However, I believe that because it has to deal directly with getting language support in place, and it very much has to do with supporting the process of programming, that I would cross-post it here. Also at: https://serverfault.com/questions/73196/python-3-1-1-with-enable-shared-will-not-build-any-extensions. Thank you! Problem: Building Python 3.1 on RHEL 5.3 64 bit with --enable-shared fails to compile all extensions. Building "normal" works fine without any problems. I can build python 3.1 just fine, but when built as a shared library, it emits many warnings (see below), and refuses to build any of the c based modules. Despite this failure, I can still build mod_wsgi 3.0c5 against it, and run it under apache. Needless to say, the functionality of Python is greatly reduced... Interesting to note that Python 3.2a0 (from svn) compiles fine with --enable-shared, and mod_wsgi compiles fine against it. But when starting apache, I get: Cannot load /etc/httpd/modules/mod_wsgi.so into server: /etc/httpd/modules/mod_wsgi.so: undefined symbol: PyCObject_FromVoidPtr The project that this is for is a long-term project, so I'm okay with alpha quality software if needed. Here are some more details on the problem. Host: Dell PowerEdge Intel Xenon RHEL 5.3 64bit Nothing "special" Build: Python 3.1.1 source distribution Works fine with ./configure Does not work fine with ./configure --enable-shared (export CFLAGS="-fPIC" has been done) make output gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -fPIC -DPy_BUILD_CORE -c ./Modules/_weakref.c -o Modules/_weakref.o building 'bz2' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -I./Include -I/usr/local/include -IInclude -I/home/build/RPMBUILD/BUILD/Python-3.1.1 -c /home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.c -o build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o -L/usr/local/lib -L. -lbz2 -lpython3.1 -o build/lib.linux-x86_64-3.1/bz2.so /usr/bin/ld: /usr/local/lib/libpython3.1.a(abstract.o): relocation R_X86_64_32 against 'a local symbol' can not be used when making a shared object; recompile with -fPIC Failed to build these modules: _bisect _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _collections _csv _ctypes _ctypes_test _curses _curses_panel _dbm _elementtree _gdbm _hashlib _heapq _json _lsprof _multibytecodec _multiprocessing _pickle _random _socket _sqlite3 _ssl _struct _testcapi array atexit audioop binascii bz2 cmath crypt datetime fcntl grp itertools math mmap nis operator ossaudiodev parser pyexpat readline resource select spwd syslog termios time unicodedata zlib A: Something is wrong with your build environment. It is picking up a libpython3.1.a from /usr/local/lib; this confuses the error messages. It tries linking with that library, which fails - however, it shouldn't have tried that in the first place, since it should have used the libpython that it just built. I recommend taking the Python 3.1 installation in /usr/local out of the way. You don't show in your output whether a libpython3.1.so.1.0 was created in the build tree; it would be important to find out whether it exists, how it was linked, and what symbols it has exported. A: /usr/local/lib has been added to the library include path at compile time: -L/usr/local/lib -L. Its common for compile time to look in multiple 'common' paths for libraries (/usr/lib, /usr/local/lib, ./, etc) but also, it's possibly picking up /usr/local/lib from the environment variable LD_LIBRARY_PATH and tacking it on to the build command.
Python 3.1.1 with --enable-shared : will not build any extensions
Summary: Building Python 3.1 on RHEL 5.3 64 bit with --enable-shared fails to compile all extensions. Building "normal" works fine without any problems. Please note that this question may seem to blur the line between programming and system administration. However, I believe that because it has to deal directly with getting language support in place, and it very much has to do with supporting the process of programming, that I would cross-post it here. Also at: https://serverfault.com/questions/73196/python-3-1-1-with-enable-shared-will-not-build-any-extensions. Thank you! Problem: Building Python 3.1 on RHEL 5.3 64 bit with --enable-shared fails to compile all extensions. Building "normal" works fine without any problems. I can build python 3.1 just fine, but when built as a shared library, it emits many warnings (see below), and refuses to build any of the c based modules. Despite this failure, I can still build mod_wsgi 3.0c5 against it, and run it under apache. Needless to say, the functionality of Python is greatly reduced... Interesting to note that Python 3.2a0 (from svn) compiles fine with --enable-shared, and mod_wsgi compiles fine against it. But when starting apache, I get: Cannot load /etc/httpd/modules/mod_wsgi.so into server: /etc/httpd/modules/mod_wsgi.so: undefined symbol: PyCObject_FromVoidPtr The project that this is for is a long-term project, so I'm okay with alpha quality software if needed. Here are some more details on the problem. Host: Dell PowerEdge Intel Xenon RHEL 5.3 64bit Nothing "special" Build: Python 3.1.1 source distribution Works fine with ./configure Does not work fine with ./configure --enable-shared (export CFLAGS="-fPIC" has been done) make output gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -fPIC -DPy_BUILD_CORE -c ./Modules/_weakref.c -o Modules/_weakref.o building 'bz2' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -I./Include -I/usr/local/include -IInclude -I/home/build/RPMBUILD/BUILD/Python-3.1.1 -c /home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.c -o build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o -L/usr/local/lib -L. -lbz2 -lpython3.1 -o build/lib.linux-x86_64-3.1/bz2.so /usr/bin/ld: /usr/local/lib/libpython3.1.a(abstract.o): relocation R_X86_64_32 against 'a local symbol' can not be used when making a shared object; recompile with -fPIC Failed to build these modules: _bisect _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _collections _csv _ctypes _ctypes_test _curses _curses_panel _dbm _elementtree _gdbm _hashlib _heapq _json _lsprof _multibytecodec _multiprocessing _pickle _random _socket _sqlite3 _ssl _struct _testcapi array atexit audioop binascii bz2 cmath crypt datetime fcntl grp itertools math mmap nis operator ossaudiodev parser pyexpat readline resource select spwd syslog termios time unicodedata zlib
[ "Something is wrong with your build environment. It is picking up a libpython3.1.a from /usr/local/lib; this confuses the error messages. It tries linking with that library, which fails - however, it shouldn't have tried that in the first place, since it should have used the libpython that it just built. I recommend taking the Python 3.1 installation in /usr/local out of the way.\nYou don't show in your output whether a libpython3.1.so.1.0 was created in the build tree; it would be important to find out whether it exists, how it was linked, and what symbols it has exported.\n", "/usr/local/lib has been added to the library include path at compile time:\n-L/usr/local/lib -L.\nIts common for compile time to look in multiple 'common' paths for libraries (/usr/lib, /usr/local/lib, ./, etc) but also, it's possibly picking up /usr/local/lib from the environment variable LD_LIBRARY_PATH and tacking it on to the build command.\n" ]
[ 6, 0 ]
[]
[]
[ "compilation", "mod_wsgi", "python", "python_3.x" ]
stackoverflow_0001547310_compilation_mod_wsgi_python_python_3.x.txt
Q: Problem about python writing files I've got a weird problem with python programming. I used the statement'writelines()' to write a series of lists into a new file.During the process I could see the context in the file icon via preview, however once after the program finished running the output file comes out to be a blank file. In short, my problem is that the program doesn't have any output but a blank file. Here's the code: infile=open('/Users/Jim/Desktop/py/result.txt','r') outfile=open('/Users/Jim/Desktop/py/output.txt','a') line=infile.readline() i=1 while(line): check=str(i)+':' if line.startswith(check): i+=1 block=[infile.readline() for j in range(1,7)] judge=block[1].split() for j in judge: if j=='stem' or j=='differetiation' or j=='differetiating': outfile.write(str(i)+':\n') outfile.writelines(block) #check if the paragraph has the given key words, if true then write the paragraph into the output file. break line=infile.readline() outfile.close() infile.close() Some additional information if helpful: The python version is 2.6.3, and the os is Mac OS 10.6. A: I guess it's caused by incorrect indentation. The break statement should be inside the if block. The loop as it is written will only try the first option from judge. Check if you don't have mixed spaces and tabs in the file.
Problem about python writing files
I've got a weird problem with python programming. I used the statement'writelines()' to write a series of lists into a new file.During the process I could see the context in the file icon via preview, however once after the program finished running the output file comes out to be a blank file. In short, my problem is that the program doesn't have any output but a blank file. Here's the code: infile=open('/Users/Jim/Desktop/py/result.txt','r') outfile=open('/Users/Jim/Desktop/py/output.txt','a') line=infile.readline() i=1 while(line): check=str(i)+':' if line.startswith(check): i+=1 block=[infile.readline() for j in range(1,7)] judge=block[1].split() for j in judge: if j=='stem' or j=='differetiation' or j=='differetiating': outfile.write(str(i)+':\n') outfile.writelines(block) #check if the paragraph has the given key words, if true then write the paragraph into the output file. break line=infile.readline() outfile.close() infile.close() Some additional information if helpful: The python version is 2.6.3, and the os is Mac OS 10.6.
[ "I guess it's caused by incorrect indentation. The break statement should be inside the if block. The loop as it is written will only try the first option from judge. Check if you don't have mixed spaces and tabs in the file.\n" ]
[ 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0001550132_file_python.txt
Q: Adding to local namespace in Python? Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally? Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print statement would print '1'. def A(): B(locals()) print x def B(d): d['x'] = 1 A: In Python 2.*, you can disable the normal optimizations performed by the Python compiler regarding local variable access by starting your function with exec ''; this will make the function very much slower (I just posted, earlier today, an answer showing how the local-variable optimization can easily speed code up by 3 or 4 times), but it will make your desired hack work. I.e., in Python 2.*: def A(): exec '' B(locals()) print x def B(d): d['x'] = 1 A() will emit 1, as you desire. This hack was disabled in Python 3.* (where exec is just a function, not a statement nor a keyword any more) -- the compiler now performs the local variable optimization unconditionally, so there is no longer any way to work around it and make such hacks work. A: Seems pretty horrible to rely on a hack like exec ''. What about communicating like this with the global statement, it seems to work: >>> def outer(): ... global x ... b() ... print x ... >>> def b(): ... global x ... x = 2 ... >>> outer() 2 You could create a namespace for your variables instead: class Namespace(object): pass def A(): names = Namespace() B(names) print names.x def B(d): d.x = 1 Then use names.x or getattr(names, "x") to access the attributes.
Adding to local namespace in Python?
Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally? Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print statement would print '1'. def A(): B(locals()) print x def B(d): d['x'] = 1
[ "In Python 2.*, you can disable the normal optimizations performed by the Python compiler regarding local variable access by starting your function with exec ''; this will make the function very much slower (I just posted, earlier today, an answer showing how the local-variable optimization can easily speed code up by 3 or 4 times), but it will make your desired hack work. I.e., in Python 2.*:\ndef A():\n exec ''\n B(locals())\n print x\n\ndef B(d):\n d['x'] = 1\n\nA()\n\nwill emit 1, as you desire.\nThis hack was disabled in Python 3.* (where exec is just a function, not a statement nor a keyword any more) -- the compiler now performs the local variable optimization unconditionally, so there is no longer any way to work around it and make such hacks work.\n", "Seems pretty horrible to rely on a hack like exec ''. What about communicating like this with the global statement, it seems to work:\n>>> def outer():\n... global x\n... b()\n... print x\n... \n>>> def b():\n... global x\n... x = 2\n... \n>>> outer()\n2\n\nYou could create a namespace for your variables instead:\nclass Namespace(object):\n pass\n\ndef A():\n names = Namespace()\n B(names)\n print names.x\n\ndef B(d):\n d.x = 1\n\nThen use names.x or getattr(names, \"x\") to access the attributes.\n" ]
[ 4, 1 ]
[]
[]
[ "class", "methods", "namespaces", "python" ]
stackoverflow_0001549201_class_methods_namespaces_python.txt
Q: web2py - how to inject html i used rows.xml() to generate html output. i want to know how to add html codes to this generated html page e.g: "add logo, link css file,.. etc" rows=db(db.member.membership_id==request.args[0]).select(db.member.membership_id ,db.member.first_name,db.member.middle_name ,db.member.last_name) return rows.xml() A: There are many HTML helpers you can use, for example: html_code = A('<click>', rows.xml(), _href='http://mylink') html_code = B('Results:', rows.xml(), _class='results', _id=1) html_page = HTML(BODY(B('Results:', rows.xml(), _class='results', _id=1))) and so on. You can even create a whole table automatically: table = SQLTABLE(rows, orderby=True, _width="100%") and then pick it apart to insert links or modify its elements. It is very powerful and normally you don't have to bother writing the actual HTML yourself. Here is the cheatsheet, or you can check directly on the website documentation. Edit: Just to make sure, you don't actually need to generate the whole HTML page, it is easier to let web2py insert your response in a template that has the same name as your controller (or force a particular template with response.view = 'template.html'. The documentation tutorial will explain that better and in further details. In a few words, if you are implementing the function index, you could either return a string (the whole page HTML, which seems to be what you are heading for), or a dictionary to use templates. In the first case, just code your function like this: def index(): # ... code to extract the rows return HTML(BODY(B('Results:', rows.xml(), _class='results', _id=1))).xml() Otherwise, write an html template in views/controller/index.html (or another file if you insert the response.view=... in your function, to re-use the same template), which could be like this: <html><head></head> <body> {{=message}} </body> </html> and return a dictionary: def index(): # ... code to extract the rows html = B('Results:', rows.xml(), _class='results', _id=1) return dict(message=html) A: Just prepend/append it to the string that rows.xml() returns: html = '<html><head>...</head><body>' + rows.xml() + '</body></html>'
web2py - how to inject html
i used rows.xml() to generate html output. i want to know how to add html codes to this generated html page e.g: "add logo, link css file,.. etc" rows=db(db.member.membership_id==request.args[0]).select(db.member.membership_id ,db.member.first_name,db.member.middle_name ,db.member.last_name) return rows.xml()
[ "There are many HTML helpers you can use, for example:\nhtml_code = A('<click>', rows.xml(), _href='http://mylink')\nhtml_code = B('Results:', rows.xml(), _class='results', _id=1)\nhtml_page = HTML(BODY(B('Results:', rows.xml(), _class='results', _id=1)))\n\nand so on.\nYou can even create a whole table automatically:\ntable = SQLTABLE(rows, orderby=True, _width=\"100%\")\n\nand then pick it apart to insert links or modify its elements.\nIt is very powerful and normally you don't have to bother writing the actual HTML yourself. Here is the cheatsheet, or you can check directly on the website documentation.\n\nEdit: Just to make sure, you don't actually need to generate the whole HTML page, it is easier to let web2py insert your response in a template that has the same name as your controller (or force a particular template with response.view = 'template.html'. The documentation tutorial will explain that better and in further details.\nIn a few words, if you are implementing the function index, you could either return a string (the whole page HTML, which seems to be what you are heading for), or a dictionary to use templates.\nIn the first case, just code your function like this:\ndef index():\n # ... code to extract the rows\n return HTML(BODY(B('Results:', rows.xml(), _class='results', _id=1))).xml()\n\nOtherwise, write an html template in views/controller/index.html (or another file if you insert the response.view=... in your function, to re-use the same template), which could be like this:\n<html><head></head>\n <body>\n {{=message}}\n </body>\n</html>\n\nand return a dictionary:\ndef index():\n # ... code to extract the rows\n html = B('Results:', rows.xml(), _class='results', _id=1)\n return dict(message=html)\n\n", "Just prepend/append it to the string that rows.xml() returns:\nhtml = '<html><head>...</head><body>' + rows.xml() + '</body></html>'\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0001550368_python_web2py.txt
Q: I do urllib2 and I download the htmlSource of the webpage. How do I make this all on 1 line? urlReq = urllib2.Request(theurl) urlReq.add_header('User-Agent',random.choice(agents)) urlResponse = urllib2.urlopen(urlReq) htmlSource = urlResponse.read() How do I make htmlSource in 1 line, instead of many lines? A: You can't really do that, the only possible thing is put the response and the source on the same line. Or you could use ; between statements, but that's ugly. But more importantly, why would you do that? Why is it better to have it all in on line? >>> import this The Zen of Python, by Tim Peters ... Readability counts. ... A: How to do that in one line? That's what functions are for. Like this: def getsource(url): urlReq = urllib2.Request(url) urlReq.add_header('User-Agent',random.choice(agents)) urlResponse = urllib2.urlopen(urlReq) return urlResponse.read() Now you can do it in one line: htmlSource = getsource(theurl) Done! Update: Filtering the htmlSource to be one linebreak (as you now claim you want) is done something like this: htmlSource = htmlSource.replace('\n', '') And you might need htmlSource = htmlSource.replace('\r', '') as well. I sincerely doubt it will speed anything up.
I do urllib2 and I download the htmlSource of the webpage. How do I make this all on 1 line?
urlReq = urllib2.Request(theurl) urlReq.add_header('User-Agent',random.choice(agents)) urlResponse = urllib2.urlopen(urlReq) htmlSource = urlResponse.read() How do I make htmlSource in 1 line, instead of many lines?
[ "You can't really do that, the only possible thing is put the response and the source on the same line. Or you could use ; between statements, but that's ugly.\nBut more importantly, why would you do that? Why is it better to have it all in on line?\n>>> import this\n\nThe Zen of Python, by Tim Peters\n\n...\nReadability counts.\n...\n\n", "How to do that in one line? That's what functions are for. Like this:\ndef getsource(url):\n urlReq = urllib2.Request(url)\n urlReq.add_header('User-Agent',random.choice(agents))\n urlResponse = urllib2.urlopen(urlReq)\n return urlResponse.read()\n\nNow you can do it in one line:\nhtmlSource = getsource(theurl)\n\nDone!\nUpdate:\nFiltering the htmlSource to be one linebreak (as you now claim you want) is done something like this:\nhtmlSource = htmlSource.replace('\\n', '')\n\nAnd you might need\nhtmlSource = htmlSource.replace('\\r', '')\n\nas well. I sincerely doubt it will speed anything up.\n" ]
[ 9, 6 ]
[]
[]
[ "python" ]
stackoverflow_0001550406_python.txt
Q: Counting all the keys pressed and what they are (python) I'd like to create a map of the number of presses for every key for a project I'm working on. I'd like to do this with a Python module. Is it possible to do this in any way? A: On Windows, a possible solution is to install Python for Windows extensions and use the PyCWnd.HookAllKeyStrokes A: As Nick D points out, on Windows, the PyHook library would work. On Linux, the Python X Library gives you access to key-presses on the X-server. A good example of the use of both libraries is pykeylogger. It's open source; see pyxhook.py for example for the relevant X library calls. A lower level option in Linux is to read directly from /dev/input/*. The evdev (ctypes) and evdev (c-api) modules may help you here; I don't know much about them though.
Counting all the keys pressed and what they are (python)
I'd like to create a map of the number of presses for every key for a project I'm working on. I'd like to do this with a Python module. Is it possible to do this in any way?
[ "On Windows, a possible solution is to install Python for Windows extensions and use the PyCWnd.HookAllKeyStrokes\n", "As Nick D points out, on Windows, the PyHook library would work.\nOn Linux, the Python X Library gives you access to key-presses on the X-server.\nA good example of the use of both libraries is pykeylogger. It's open source; see pyxhook.py for example for the relevant X library calls.\nA lower level option in Linux is to read directly from /dev/input/*. The evdev (ctypes) and evdev (c-api) modules may help you here; I don't know much about them though.\n" ]
[ 1, 1 ]
[]
[]
[ "counting", "key", "python" ]
stackoverflow_0001550273_counting_key_python.txt
Q: Django: how to include the file? I have a Django Application. I want to have all my models to be separated in files and lay in the specific directory, for instance: /usr/project/models/myModel.py Is it any possible? Just importing through from myModel import * doesn't work, unfortunately. Is there any specific way to do this? A: Create file /usr/project/models/__init__.py containing from myModel import *. __init__.py file is required to make directory a python package. A: You can split your models into separate files, it's just Python code.
Django: how to include the file?
I have a Django Application. I want to have all my models to be separated in files and lay in the specific directory, for instance: /usr/project/models/myModel.py Is it any possible? Just importing through from myModel import * doesn't work, unfortunately. Is there any specific way to do this?
[ "Create file /usr/project/models/__init__.py containing from myModel import *. __init__.py file is required to make directory a python package.\n", "You can split your models into separate files, it's just Python code. \n" ]
[ 1, 0 ]
[]
[]
[ "django_urls", "python" ]
stackoverflow_0001550601_django_urls_python.txt
Q: Difference between defining a member in __init__ to defining it in the class body in python? What is the difference between doing class a: def __init__(self): self.val=1 to doing class a: val=1 def __init__(self): pass A: class a: def __init__(self): self.val=1 this creates a class (in Py2, a cruddy, legacy, old-style, don't do that! class; in Py3, the nasty old legacy classes have finally gone away so this would be a class of the one and only kind -- the **good* kind, which requires class a(object): in Py2) such that each instance starts out with its own reference to the integer object 1. class a: val=1 def __init__(self): pass this creates a class (of the same kind) which itself has a reference to the integer object 1 (its instances start out with no per-instance reference). For immutables like int values, it's hard to see a practical difference. For example, in either case, if you later do self.val = 2 on one instance of a, this will make an instance reference (the existing answer is badly wrong in this respect). The distinction is important for mutable objects, because they have mutator methods, so it's pretty crucial to know if a certain list is unique per-instance or shared among all instances. But for immutable objects, since you can never change the object itself but only assign (e.g. to self.val, which will always make a per-instance reference), it's pretty minor. Just about the only relevant difference for immutables: if you later assign a.val = 3, in the first case this will affect what's seen as self.val by each instance (except for instances that had their own self.val assigned to, or equivalent actions); in the second case, it will not affect what's seen as self.val by any instance (except for instances for which you had performed del self.val or equivalent actions). A: Others have explained the technical differences. I'll try to explain why you might want to use class variables. If you're only instantiating the class once, then class variables effectively are instance variables. However, if you're making many copies, or want to share state among a few instances, then class variables are very handy. For example: class Foo(object): def __init__(self): self.bar = expensivefunction() myobjs = [Foo() for _ in range(1000000)] will cause expensivefunction() to be called a million times. If it's going to return the same value each time, say fetching a configuration parameter from a database, then you should consider moving it into the class definition so that it's only called once and then shared across all instances. I also use class variables a lot when memoizing results. Example: class Foo(object): bazcache = {} @classmethod def baz(cls, key): try: result = cls.bazcache[key] except KeyError: result = expensivefunction(key) cls.bazcache[key] = result return result In this case, baz is a class method; its result doesn't depend on any instance variables. That means we can keep one copy of the results cache in the class variable, so that 1) you don't store the same results multiple times, and 2) each instance can benefit from results that were cached from other instances. To illustrate, suppose that you have a million instances, each operating on the results of a Google search. You'd probably much prefer that all those objects share those results than to have each one execute the search and wait for the answer. So I'd disagree with Lennart here. Class variables are very convenient in certain cases. When they're the right tool for the job, don't hesitate to use them. A: As mentioned by others, in one case it's an attribute on the class on the other an attribute on the instance. Does this matter? Yes, in one case it does. As Alex said, if the value is mutable. The best explanation is code, so I'll add some code to show it (that's all this answer does, really): First a class defining two instance attributes. >>> class A(object): ... def __init__(self): ... self.number = 45 ... self.letters = ['a', 'b', 'c'] ... And then a class defining two class attributes. >>> class B(object): ... number = 45 ... letters = ['a', 'b', 'c'] ... Now we use them: >>> a1 = A() >>> a2 = A() >>> a2.number = 15 >>> a2.letters.append('z') And all is well: >>> a1.number 45 >>> a1.letters ['a', 'b', 'c'] Now use the class attribute variation: >>> b1 = B() >>> b2 = B() >>> b2.number = 15 >>> b2.letters.append('z') And all is...well... >>> b1.number 45 >>> b1.letters ['a', 'b', 'c', 'z'] Yeah, notice that when you changed, the mutable class attribute it changed for all classes. That's usually not what you want. If you are using the ZODB, you use a lot of class attributes because it's a handy way of upgrading existing objects with new attributes, or adding information on a class level that doesn't get persisted. Otherwise you can pretty much ignore them.
Difference between defining a member in __init__ to defining it in the class body in python?
What is the difference between doing class a: def __init__(self): self.val=1 to doing class a: val=1 def __init__(self): pass
[ "class a:\n def __init__(self):\n self.val=1\n\nthis creates a class (in Py2, a cruddy, legacy, old-style, don't do that! class; in Py3, the nasty old legacy classes have finally gone away so this would be a class of the one and only kind -- the **good* kind, which requires class a(object): in Py2) such that each instance starts out with its own reference to the integer object 1.\nclass a:\n val=1\n def __init__(self):\n pass\n\nthis creates a class (of the same kind) which itself has a reference to the integer object 1 (its instances start out with no per-instance reference).\nFor immutables like int values, it's hard to see a practical difference. For example, in either case, if you later do self.val = 2 on one instance of a, this will make an instance reference (the existing answer is badly wrong in this respect).\nThe distinction is important for mutable objects, because they have mutator methods, so it's pretty crucial to know if a certain list is unique per-instance or shared among all instances. But for immutable objects, since you can never change the object itself but only assign (e.g. to self.val, which will always make a per-instance reference), it's pretty minor.\nJust about the only relevant difference for immutables: if you later assign a.val = 3, in the first case this will affect what's seen as self.val by each instance (except for instances that had their own self.val assigned to, or equivalent actions); in the second case, it will not affect what's seen as self.val by any instance (except for instances for which you had performed del self.val or equivalent actions).\n", "Others have explained the technical differences. I'll try to explain why you might want to use class variables.\nIf you're only instantiating the class once, then class variables effectively are instance variables. However, if you're making many copies, or want to share state among a few instances, then class variables are very handy. For example:\nclass Foo(object):\n def __init__(self):\n self.bar = expensivefunction()\n\nmyobjs = [Foo() for _ in range(1000000)]\n\nwill cause expensivefunction() to be called a million times. If it's going to return the same value each time, say fetching a configuration parameter from a database, then you should consider moving it into the class definition so that it's only called once and then shared across all instances.\nI also use class variables a lot when memoizing results. Example:\nclass Foo(object):\n bazcache = {}\n\n @classmethod\n def baz(cls, key):\n try:\n result = cls.bazcache[key]\n except KeyError:\n result = expensivefunction(key)\n cls.bazcache[key] = result\n return result\n\nIn this case, baz is a class method; its result doesn't depend on any instance variables. That means we can keep one copy of the results cache in the class variable, so that 1) you don't store the same results multiple times, and 2) each instance can benefit from results that were cached from other instances.\nTo illustrate, suppose that you have a million instances, each operating on the results of a Google search. You'd probably much prefer that all those objects share those results than to have each one execute the search and wait for the answer.\nSo I'd disagree with Lennart here. Class variables are very convenient in certain cases. When they're the right tool for the job, don't hesitate to use them.\n", "As mentioned by others, in one case it's an attribute on the class on the other an attribute on the instance. Does this matter? Yes, in one case it does. As Alex said, if the value is mutable. The best explanation is code, so I'll add some code to show it (that's all this answer does, really):\nFirst a class defining two instance attributes.\n>>> class A(object):\n... def __init__(self):\n... self.number = 45\n... self.letters = ['a', 'b', 'c']\n... \n\nAnd then a class defining two class attributes.\n>>> class B(object):\n... number = 45\n... letters = ['a', 'b', 'c']\n... \n\nNow we use them:\n>>> a1 = A()\n>>> a2 = A()\n>>> a2.number = 15\n>>> a2.letters.append('z')\n\nAnd all is well:\n>>> a1.number\n45\n>>> a1.letters\n['a', 'b', 'c']\n\nNow use the class attribute variation:\n>>> b1 = B()\n>>> b2 = B()\n>>> b2.number = 15\n>>> b2.letters.append('z')\n\nAnd all is...well...\n>>> b1.number\n45\n>>> b1.letters\n['a', 'b', 'c', 'z']\n\nYeah, notice that when you changed, the mutable class attribute it changed for all classes. That's usually not what you want.\nIf you are using the ZODB, you use a lot of class attributes because it's a handy way of upgrading existing objects with new attributes, or adding information on a class level that doesn't get persisted. Otherwise you can pretty much ignore them.\n" ]
[ 10, 6, 5 ]
[]
[]
[ "class", "init", "python" ]
stackoverflow_0001549722_class_init_python.txt
Q: web2py SQLTABLE - How can I transpose the table? I am using: rows = db(db.member.membership_id==request.args[0]).select(db.member.membership_id, db.member.first_name, db.member.middle_name, db.member.last_name, db.member.birthdate, db.member.registration_date, db.member.membership_end_date) rows.colnames = ('Membership Id', 'First Name', 'Middle Name', 'Last Name', 'Birthday Date', 'Registration Date', 'Membership ending Date') table = SQLTABLE(rows, _width="100%") Now I want to transpose the table, how can I do this? A: Try this: rows=db(query).select(*fields).as_list() if rows: table=TABLE(*[TR(TH(field),*[TD(row[field]) for row in rows]) \ for field in row[0].keys()]) else: table="nothing to see here" return dict(table=table)
web2py SQLTABLE - How can I transpose the table?
I am using: rows = db(db.member.membership_id==request.args[0]).select(db.member.membership_id, db.member.first_name, db.member.middle_name, db.member.last_name, db.member.birthdate, db.member.registration_date, db.member.membership_end_date) rows.colnames = ('Membership Id', 'First Name', 'Middle Name', 'Last Name', 'Birthday Date', 'Registration Date', 'Membership ending Date') table = SQLTABLE(rows, _width="100%") Now I want to transpose the table, how can I do this?
[ "Try this:\nrows=db(query).select(*fields).as_list()\nif rows:\n table=TABLE(*[TR(TH(field),*[TD(row[field]) for row in rows]) \\ \n for field in row[0].keys()])\nelse:\n table=\"nothing to see here\"\nreturn dict(table=table)\n\n" ]
[ 1 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0001550707_python_web2py.txt
Q: Dynamically importing modules in Python3.0? I want to dynamically import a list of modules. I'm having a problem doing this. Python always yells out an ImportError and tells me my module doesn't exist. First I get the list of module filenames and chop off the ".py" suffixes, like so: viable_plugins = filter(is_plugin, os.listdir(plugin_dir)) viable_plugins = map(lambda name: name[:-3], viable_plugins) Then I os.chdir to the plugins directory and map __import__ the entire thing, like so: active_plugins = map(__import__, viable_plugins) However, when I turn active_plugins into a list and try to access the modules within, Python will throw out an error, saying it cannot import the modules since they don't appear to be there. What am I doing wrong? Edit: By simply using the interactive interpreter, doing os.chdir and __import__(modulefilename) produces exactly what I need. Why isn't the above approach working, then? Am I doing something wrong with Python's more functional parts? A: It says it can't do it, because even though you're changing your directory to where the modules are, that directory isn't on your import path. What you need to do, instead of changing to the directory where the modules are located, is to insert that directory into sys.path. import sys sys.path.insert(0, directory_of_modules) # do imports here.
Dynamically importing modules in Python3.0?
I want to dynamically import a list of modules. I'm having a problem doing this. Python always yells out an ImportError and tells me my module doesn't exist. First I get the list of module filenames and chop off the ".py" suffixes, like so: viable_plugins = filter(is_plugin, os.listdir(plugin_dir)) viable_plugins = map(lambda name: name[:-3], viable_plugins) Then I os.chdir to the plugins directory and map __import__ the entire thing, like so: active_plugins = map(__import__, viable_plugins) However, when I turn active_plugins into a list and try to access the modules within, Python will throw out an error, saying it cannot import the modules since they don't appear to be there. What am I doing wrong? Edit: By simply using the interactive interpreter, doing os.chdir and __import__(modulefilename) produces exactly what I need. Why isn't the above approach working, then? Am I doing something wrong with Python's more functional parts?
[ "It says it can't do it, because even though you're changing your directory to where the modules are, that directory isn't on your import path.\nWhat you need to do, instead of changing to the directory where the modules are located, is to insert that directory into sys.path.\nimport sys\nsys.path.insert(0, directory_of_modules)\n# do imports here.\n\n" ]
[ 8 ]
[]
[]
[ "import", "python", "python_3.x" ]
stackoverflow_0001551063_import_python_python_3.x.txt
Q: urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't match, it downloads them. The server-side is plain-vanilla Apache 2 on Ubuntu over port 80. The client side works perfectly on Mac and Linux, but gives me this error on Windows (XP and Vista) after downloading a number of files: urllib2.URLError: <urlopen error <10048, 'Address already in use'>> This link: http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect points me to TCP port exhaustion, but "netstat -n" never showed me more than six connections in "TIME_WAIT" status, even just before it errored out. The code (called once for each of the 55,000 files it downloads) is this: request = urllib2.Request(file_remote_path) opener = urllib2.build_opener() datastream = opener.open(request) outfileobj = open(temp_file_path, 'wb') try: while True: chunk = datastream.read(CHUNK_SIZE) if chunk == '': break else: outfileobj.write(chunk) finally: outfileobj = outfileobj.close() datastream.close() UPDATE: I find by greping the log that it enters the download routine exactly 3998 times. I've run this multiple times and it fails at 3998 each time. Given that the linked article states that available ports are 5000-1025=3975 (and some are probably expiring and being reused) it's starting to look a lot more like the linked article describes the real issue. However, I'm still not sure how to fix this. Making registry edits is not an option. A: If it is really a resource problem (freeing os socket resources) try this: request = urllib2.Request(file_remote_path) opener = urllib2.build_opener() retry = 3 # 3 tries while retry : try : datastream = opener.open(request) except urllib2.URLError, ue: if ue.reason.find('10048') > -1 : if retry : retry -= 1 else : raise urllib2.URLError("Address already in use / retries exhausted") else : retry = 0 if datastream : retry = 0 outfileobj = open(temp_file_path, 'wb') try: while True: chunk = datastream.read(CHUNK_SIZE) if chunk == '': break else: outfileobj.write(chunk) finally: outfileobj = outfileobj.close() datastream.close() if you want you can insert a sleep or you make it os depended on my win-xp the problem doesn't show up (I reached 5000 downloads) I watch my processes and network with process hacker. A: Thinking outside the box, the problem you seem to be trying to solve has already been solved by a program called rsync. You might look for a Windows implementation and see if it meets your needs. A: You should seriously consider copying and modifying this pyCurl example for efficient downloading of a large collection of files. A: Instead of opening a new TCP connection for each request you should really use persistent HTTP connections - have a look at urlgrabber (or alternatively, just at keepalive.py for how to add keep-alive connection support to urllib2). A: All indications point to a lack of available sockets. Are you sure that only 6 are in TIME_WAIT status? If you're running so many download operations it's very likely that netstat overruns your terminal buffer. I find that netstat stat overruns my terminal during normal useage periods. The solution is to either modify the code to reuse sockets. Or introduce a timeout. It also wouldn't hurt to keep track of how many open sockets you have. To optimize waiting. The default timeout on Windows XP is 120 seconds. so you want to sleep for at least that long if you run out of sockets. Unfortunately it doesn't look like there's an easy way to check from Python when a socket has closed and left the TIME_WAIT status. Given the asynchronous nature of the requests and timeouts, the best way to do this might be in a thread. Make each threat sleep for 2 minutes before it finishes. You can either use a Semaphore or limit the number of active threads to ensure that you don't run out of sockets. Here's how I'd handle it. You might want to add an exception clause to the inner try block of the fetch section, to warn you about failed fetches. import time import threading import Queue # assumes url_queue is a Queue object populated with tuples in the form of(url_to_fetch, temp_file) # also assumes that TotalUrls is the size of the queue before any threads are started. class urlfetcher(threading.Thread) def __init__ (self, queue) Thread.__init__(self) self.queue = queue def run(self) try: # needed to handle empty exception raised by an empty queue. file_remote_path, temp_file_path = self.queue.get() request = urllib2.Request(file_remote_path) opener = urllib2.build_opener() datastream = opener.open(request) outfileobj = open(temp_file_path, 'wb') try: while True: chunk = datastream.read(CHUNK_SIZE) if chunk == '': break else: outfileobj.write(chunk) finally: outfileobj = outfileobj.close() datastream.close() time.sleep(120) self.queue.task_done() elsewhere: while url_queue.size() < TotalUrls: # hard limit of available ports. if threading.active_threads() < 3975: # Hard limit of available ports t = urlFetcher(url_queue) t.start() else: time.sleep(2) url_queue.join() Sorry, my python is a little rusty, so I wouldn't be surprised if I missed something.
urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows
I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't match, it downloads them. The server-side is plain-vanilla Apache 2 on Ubuntu over port 80. The client side works perfectly on Mac and Linux, but gives me this error on Windows (XP and Vista) after downloading a number of files: urllib2.URLError: <urlopen error <10048, 'Address already in use'>> This link: http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect points me to TCP port exhaustion, but "netstat -n" never showed me more than six connections in "TIME_WAIT" status, even just before it errored out. The code (called once for each of the 55,000 files it downloads) is this: request = urllib2.Request(file_remote_path) opener = urllib2.build_opener() datastream = opener.open(request) outfileobj = open(temp_file_path, 'wb') try: while True: chunk = datastream.read(CHUNK_SIZE) if chunk == '': break else: outfileobj.write(chunk) finally: outfileobj = outfileobj.close() datastream.close() UPDATE: I find by greping the log that it enters the download routine exactly 3998 times. I've run this multiple times and it fails at 3998 each time. Given that the linked article states that available ports are 5000-1025=3975 (and some are probably expiring and being reused) it's starting to look a lot more like the linked article describes the real issue. However, I'm still not sure how to fix this. Making registry edits is not an option.
[ "If it is really a resource problem (freeing os socket resources)\ntry this:\nrequest = urllib2.Request(file_remote_path)\nopener = urllib2.build_opener()\n\nretry = 3 # 3 tries\nwhile retry :\n try :\n datastream = opener.open(request)\n except urllib2.URLError, ue:\n if ue.reason.find('10048') > -1 :\n if retry :\n retry -= 1\n else :\n raise urllib2.URLError(\"Address already in use / retries exhausted\")\n else :\n retry = 0\n if datastream :\n retry = 0\n\noutfileobj = open(temp_file_path, 'wb')\ntry:\n while True:\n chunk = datastream.read(CHUNK_SIZE)\n if chunk == '':\n break\n else:\n outfileobj.write(chunk)\nfinally:\n outfileobj = outfileobj.close()\n datastream.close()\n\nif you want you can insert a sleep or you make it os depended\non my win-xp the problem doesn't show up (I reached 5000 downloads)\nI watch my processes and network with process hacker.\n", "Thinking outside the box, the problem you seem to be trying to solve has already been solved by a program called rsync. You might look for a Windows implementation and see if it meets your needs.\n", "You should seriously consider copying and modifying this pyCurl example for efficient downloading of a large collection of files. \n", "Instead of opening a new TCP connection for each request you should really use persistent HTTP connections - have a look at urlgrabber (or alternatively, just at keepalive.py for how to add keep-alive connection support to urllib2).\n", "All indications point to a lack of available sockets. Are you sure that only 6 are in TIME_WAIT status? If you're running so many download operations it's very likely that netstat overruns your terminal buffer. I find that netstat stat overruns my terminal during normal useage periods.\nThe solution is to either modify the code to reuse sockets. Or introduce a timeout. It also wouldn't hurt to keep track of how many open sockets you have. To optimize waiting. The default timeout on Windows XP is 120 seconds. so you want to sleep for at least that long if you run out of sockets. Unfortunately it doesn't look like there's an easy way to check from Python when a socket has closed and left the TIME_WAIT status.\nGiven the asynchronous nature of the requests and timeouts, the best way to do this might be in a thread. Make each threat sleep for 2 minutes before it finishes. You can either use a Semaphore or limit the number of active threads to ensure that you don't run out of sockets.\nHere's how I'd handle it. You might want to add an exception clause to the inner try block of the fetch section, to warn you about failed fetches.\nimport time\nimport threading\nimport Queue\n\n# assumes url_queue is a Queue object populated with tuples in the form of(url_to_fetch, temp_file)\n# also assumes that TotalUrls is the size of the queue before any threads are started.\n\n\nclass urlfetcher(threading.Thread)\n def __init__ (self, queue)\n Thread.__init__(self)\n self.queue = queue\n\n\n def run(self)\n try: # needed to handle empty exception raised by an empty queue.\n file_remote_path, temp_file_path = self.queue.get()\n request = urllib2.Request(file_remote_path)\n opener = urllib2.build_opener()\n datastream = opener.open(request)\n outfileobj = open(temp_file_path, 'wb')\n try:\n while True:\n chunk = datastream.read(CHUNK_SIZE)\n if chunk == '':\n break\n else:\n outfileobj.write(chunk)\n finally:\n outfileobj = outfileobj.close()\n datastream.close() \n time.sleep(120)\n self.queue.task_done()\n\nelsewhere:\n\n\nwhile url_queue.size() < TotalUrls: # hard limit of available ports.\n if threading.active_threads() < 3975: # Hard limit of available ports\n t = urlFetcher(url_queue)\n t.start()\n else: \n time.sleep(2)\n\nurl_queue.join()\n\nSorry, my python is a little rusty, so I wouldn't be surprised if I missed something.\n" ]
[ 5, 1, 1, 1, 1 ]
[]
[]
[ "download", "http", "python", "urllib2", "windows" ]
stackoverflow_0001512057_download_http_python_urllib2_windows.txt
Q: python: parse HTTP POST request w/file upload and additional params The task is simple: on the server side (python) accept an HTTP POST which contains an uploaded file and more form parameters. I am trying to implement upload progress indicator, and therefore I need to be able to read the file content chunk-by-chunk. All methods I found are based on cgi.FieldStorage, which somehow only allows me to obtain the file in its entirety (in memory, which is a disaster in itself). Some advise to redefine the FieldStorage.make_file method(), which seems to break down the cgi implementation (weird...). I am currently able to read the entire wsgi input, chunk by chunk, to the filesystem, resulting in the following data: -----------------------------9514143097616 Content-Disposition: form-data; name="myfile"; filename="inbound_marketing_cartoon_ebook.pdf" Content-Type: application/pdf ... 1.5 MB of PDF data -----------------------------9514143097616 Content-Disposition: form-data; name="tid" 194 -----------------------------9514143097616-- Does anyone know if there are any Python libraries that could reliably parse this thing? Or should I do this manually? (Python 2.5 that is) Thanks. A: As you suggested, I would (and have done before) override the make_file method of a FieldStorage object. Just return an object which has a write method that both accepts the data (into a file or memory or what-have-you) and tracks how much has been received for your progress indicator. Doing it this way you also get access to the length of the file (as supplied by the client), file name, and the key that it is posted under. Why does this seem to break down the CGI implementation for you? Another option is to do the progress tracking in the browser with a flash uploader (YUI Uploader and SWFUpload come to mind) and skip tracking it on the server entirely. Then you don't have to have a series of AJAX requests to get the progress. A: It seems counter-intuitive (and I feel that the module is poorly-named), but email will likely do what you want. I've never used it, but a coworker has in an e-mail processing system; since these messages are simply RFC 2822 in nature, email will probably parse them. The documentation for email is quite thorough, at first glance. My gut feeling would be to say that you're likely going to end up with the file in memory, however, which you did express chagrin at. A: You might want to take a look at what Django has done. They have a really nice implementation of custom file upload handlers, which allows you to subclass them to enable things like progress bars etc. See the documentation and the relevant code - even if you don't want to use Django, it's bound to give you some ideas.
python: parse HTTP POST request w/file upload and additional params
The task is simple: on the server side (python) accept an HTTP POST which contains an uploaded file and more form parameters. I am trying to implement upload progress indicator, and therefore I need to be able to read the file content chunk-by-chunk. All methods I found are based on cgi.FieldStorage, which somehow only allows me to obtain the file in its entirety (in memory, which is a disaster in itself). Some advise to redefine the FieldStorage.make_file method(), which seems to break down the cgi implementation (weird...). I am currently able to read the entire wsgi input, chunk by chunk, to the filesystem, resulting in the following data: -----------------------------9514143097616 Content-Disposition: form-data; name="myfile"; filename="inbound_marketing_cartoon_ebook.pdf" Content-Type: application/pdf ... 1.5 MB of PDF data -----------------------------9514143097616 Content-Disposition: form-data; name="tid" 194 -----------------------------9514143097616-- Does anyone know if there are any Python libraries that could reliably parse this thing? Or should I do this manually? (Python 2.5 that is) Thanks.
[ "As you suggested, I would (and have done before) override the make_file method of a FieldStorage object. Just return an object which has a write method that both accepts the data (into a file or memory or what-have-you) and tracks how much has been received for your progress indicator.\nDoing it this way you also get access to the length of the file (as supplied by the client), file name, and the key that it is posted under.\nWhy does this seem to break down the CGI implementation for you?\nAnother option is to do the progress tracking in the browser with a flash uploader (YUI Uploader and SWFUpload come to mind) and skip tracking it on the server entirely. Then you don't have to have a series of AJAX requests to get the progress.\n", "It seems counter-intuitive (and I feel that the module is poorly-named), but email will likely do what you want. I've never used it, but a coworker has in an e-mail processing system; since these messages are simply RFC 2822 in nature, email will probably parse them.\nThe documentation for email is quite thorough, at first glance.\nMy gut feeling would be to say that you're likely going to end up with the file in memory, however, which you did express chagrin at.\n", "You might want to take a look at what Django has done. They have a really nice implementation of custom file upload handlers, which allows you to subclass them to enable things like progress bars etc. See the documentation and the relevant code - even if you don't want to use Django, it's bound to give you some ideas.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python", "upload", "wsgi" ]
stackoverflow_0001551552_python_upload_wsgi.txt
Q: How can 2 Python dictionaries become 1? Possible Duplicate: Python “extend” for a dictionary I know that Python list can be appended or extended. Is there an easy way to combine two Python dictionaries with unique keys, for instance: basket_one = {'fruit': 'watermelon', 'veggie': 'pumpkin'} basket_two = {'dairy': 'cheese', 'meat': 'turkey'} I then want one big basket of food: basket = { 'fruit': 'watermelon', 'veggie': 'pumpkin', 'dairy': 'cheese', 'meat': 'turkey' } How can I perform the above in Python? A: The "oneliner way", altering neither of the input dicts, is basket = dict(basket_one, **basket_two) In case of conflict, the items from basket_two will override the ones from basket_one. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict that's a mix of two others comes in handy (any reader who has trouble understanding it will in fact be very well served by the way this prompts him or hear towards learning about dict and the ** form;-). So, for example, uses like: x = mungesomedict(dict(adict, **anotherdict)) are reasonably frequent occurrences in my code. Note: In Python 3, this will only work if every key in anotherdict is a string. See these alternatives. A: basket = basket_one.copy() basket.update(basket_two) (if the original basket_one does not need to stay intact, you can leave out the copy)
How can 2 Python dictionaries become 1?
Possible Duplicate: Python “extend” for a dictionary I know that Python list can be appended or extended. Is there an easy way to combine two Python dictionaries with unique keys, for instance: basket_one = {'fruit': 'watermelon', 'veggie': 'pumpkin'} basket_two = {'dairy': 'cheese', 'meat': 'turkey'} I then want one big basket of food: basket = { 'fruit': 'watermelon', 'veggie': 'pumpkin', 'dairy': 'cheese', 'meat': 'turkey' } How can I perform the above in Python?
[ "The \"oneliner way\", altering neither of the input dicts, is\nbasket = dict(basket_one, **basket_two)\n\nIn case of conflict, the items from basket_two will override the ones from basket_one. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict that's a mix of two others comes in handy (any reader who has trouble understanding it will in fact be very well served by the way this prompts him or hear towards learning about dict and the ** form;-). So, for example, uses like:\nx = mungesomedict(dict(adict, **anotherdict))\n\nare reasonably frequent occurrences in my code.\nNote: In Python 3, this will only work if every key in anotherdict is a string. See these alternatives.\n", "basket = basket_one.copy()\nbasket.update(basket_two)\n\n(if the original basket_one does not need to stay intact, you can leave out the copy)\n" ]
[ 65, 8 ]
[]
[]
[ "dictionary", "merge", "python" ]
stackoverflow_0001551666_dictionary_merge_python.txt
Q: How to perform this RegExp in Python? I would like to transform a phone number of this form +33.300000000 in 03.00.00.00.00 +33 is the indicatif it could be 2 or 3 digits length. Digits after the . are the phone number. It could be 9 or 10 digits length. I try like this : p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE) number = "+33.300000000" p.sub("0\1", number) But this doesn't work. However, the search seams to work : >>> p.search(number).groups() ('300000000',) And after how to modify 0300000000 in 03.00.00.00.00 in Python ? Thank you for your help, Natim A: The simplest approach is a mix of RE and pure string manipulation, e.g.: import re def doitall(number): # get 9 or 10 digits, or None: mo = re.search(r'\d{9,10}', number) if mo is None: return None # add a leading 0 if they were just 9 digits = ('0' + mo.group())[-10:] # now put a dot after each 2 digits # and discard the resulting trailing dot return re.sub(r'(\d\d)', r'\1.', digits)[:-1] number = "+33.300000000" print doitall(number) emits 03.00.00.00.00, as required. Yes, you can do it all in a RE, but it's not worth the headache -- the mix works fine;-). A: In the terminal it works like that : p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE) number = "+33.300000000" p.sub("0\\1", number) And in the python script it works like that : p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE) number = "+33.300000000" p.sub("0\1", number)
How to perform this RegExp in Python?
I would like to transform a phone number of this form +33.300000000 in 03.00.00.00.00 +33 is the indicatif it could be 2 or 3 digits length. Digits after the . are the phone number. It could be 9 or 10 digits length. I try like this : p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE) number = "+33.300000000" p.sub("0\1", number) But this doesn't work. However, the search seams to work : >>> p.search(number).groups() ('300000000',) And after how to modify 0300000000 in 03.00.00.00.00 in Python ? Thank you for your help, Natim
[ "The simplest approach is a mix of RE and pure string manipulation, e.g.:\nimport re\n\ndef doitall(number):\n # get 9 or 10 digits, or None:\n mo = re.search(r'\\d{9,10}', number)\n if mo is None: return None\n # add a leading 0 if they were just 9\n digits = ('0' + mo.group())[-10:]\n # now put a dot after each 2 digits\n # and discard the resulting trailing dot\n return re.sub(r'(\\d\\d)', r'\\1.', digits)[:-1]\n\nnumber = \"+33.300000000\"\nprint doitall(number)\n\nemits 03.00.00.00.00, as required.\nYes, you can do it all in a RE, but it's not worth the headache -- the mix works fine;-).\n", "In the terminal it works like that :\np = re.compile( \"\\+[0-9]+\\.([0-9]+)\", re.VERBOSE)\nnumber = \"+33.300000000\"\np.sub(\"0\\\\1\", number)\n\nAnd in the python script it works like that :\np = re.compile( \"\\+[0-9]+\\.([0-9]+)\", re.VERBOSE)\nnumber = \"+33.300000000\"\np.sub(\"0\\1\", number)\n\n" ]
[ 3, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001552124_python_string.txt
Q: Why doesn't memcache work in my Django? from django.core.cache import cache def testcache(): cache.set('test','I am putting this message in',3333) print cache.get('test') It just prints "None" This is in "ps aux": dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:20 0:00 memcached -d -u root -m 3900 -p 11211 dovr 2247 0.0 3.7 83696 9800 pts/2 S+ 04:20 0:00 python manage.py runserver 0.0.0.0:8000 And this is in my settings.py: CACHE_BACKEND = 'memcached://MYIPADRESS:11211/' By the way, it worked before, but not anymore! I don't know why. So weird. A: You can insure that you can reach memcached from your code by logging value returned from set() method. Probably memcached listens on 127.0.0.1 while you are trying to connect to external interface. A: Solved. Django was talking to the server. I did "nc IPADRESS 11211" . And typed "stats" Then, I looked that cmd_get and cmd_set were changing, so that means it's talking. Then, I realized that I had problem with code in my views. You can't have "space" in the key. It has to be non-spaceless (and encoded)
Why doesn't memcache work in my Django?
from django.core.cache import cache def testcache(): cache.set('test','I am putting this message in',3333) print cache.get('test') It just prints "None" This is in "ps aux": dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:20 0:00 memcached -d -u root -m 3900 -p 11211 dovr 2247 0.0 3.7 83696 9800 pts/2 S+ 04:20 0:00 python manage.py runserver 0.0.0.0:8000 And this is in my settings.py: CACHE_BACKEND = 'memcached://MYIPADRESS:11211/' By the way, it worked before, but not anymore! I don't know why. So weird.
[ "You can insure that you can reach memcached from your code by logging value returned from set() method. Probably memcached listens on 127.0.0.1 while you are trying to connect to external interface.\n", "Solved.\nDjango was talking to the server.\nI did \"nc IPADRESS 11211\" .\nAnd typed \"stats\"\nThen, I looked that cmd_get and cmd_set were changing, so that means it's talking.\nThen, I realized that I had problem with code in my views.\nYou can't have \"space\" in the key. It has to be non-spaceless (and encoded)\n" ]
[ 2, 0 ]
[]
[]
[ "django", "memcached", "python" ]
stackoverflow_0001550180_django_memcached_python.txt
Q: How to transform Python 3 script to Mac OS application bundle? Is there currently a way to create an application bundle from Py3k script? py2app uses Carbon package and therefore, as far as I understand, cannot be ported to py3k - Carbon development was terminated. A: There's always Platypus and PyObjC http://www.sveinbjorn.org/platypus http://pyobjc.sourceforge.net A: I have not checked if that's true, but cx_freeze 4.1 claims to support Python 3.1 (cx_freeze in general has long supported Mac OS X, as well as Windows and Linux, and I believe that also applies to the recent 4.1 release).
How to transform Python 3 script to Mac OS application bundle?
Is there currently a way to create an application bundle from Py3k script? py2app uses Carbon package and therefore, as far as I understand, cannot be ported to py3k - Carbon development was terminated.
[ "There's always Platypus and PyObjC\nhttp://www.sveinbjorn.org/platypus\nhttp://pyobjc.sourceforge.net\n", "I have not checked if that's true, but cx_freeze 4.1 claims to support Python 3.1 (cx_freeze in general has long supported Mac OS X, as well as Windows and Linux, and I believe that also applies to the recent 4.1 release).\n" ]
[ 1, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0001534933_macos_python.txt
Q: Rules of thumb for when to use operator overloading in python From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading + you probably also want to overload ++ and +=, and also make sure to handle end cases like adding an object to itself etc.), you should only consider it in those cases where this feature will have a major impact on your code, like overloading the operators for the matrix class in a math application. Does the same apply to python? Would you recommend overriding operator behavior in python? And what rules of thumb can you give me? A: Operator overloading is mostly useful when you're making a new class that falls into an existing "Abstract Base Class" (ABC) -- indeed, many of the ABCs in standard library module collections rely on the presence of certain special methods (and special methods, one with names starting and ending with double underscores AKA "dunders", are exactly the way you perform operator overloading in Python). This provides good starting guidance. For example, a Container class must override special method __contains__, i.e., the membership check operator item in container (as in, if item in container: -- don't confuse with the for statement, for item in container:, which relies on __iter__!-). Similarly, a Hashable must override __hash__, a Sized must override __len__, a Sequence or a Mapping must override __getitem__, and so forth. (Moreover, the ABCs can provide your class with mixin functionality -- e.g., both Sequence and Mapping can provide __contains__ on the basis of your supplied __getitem__ override, and thereby automatically make your class a Container). Beyond the collections, you'll want to override special methods (i.e. provide for operator overloading) mostly if your new class "is a number". Other special cases exist, but resist the temptation of overloading operators "just for coolness", with no semantic connection to the "normal" meanings, as C++'s streams do for << and >> and Python strings (in Python 2.*, fortunately not in 3.* any more;-) do for % -- when such operators do not any more mean "bit-shifting" or "division remainder", you're just engendering confusion. A language's standard library can get away with it (though it shouldn't;-), but unless your library gets as widespread as the language's standard one, the confusion will hurt!-) A: I've written software with significant amounts of overloading, and lately I regret that policy. I would say this: Only overload operators if it's the natural, expected thing to do and doesn't have any side effects. So if you make a new RomanNumeral class, it makes sense to overload addition and subtraction etc. But don't overload it unless it's natural: it makes no sense to define addition and subtraction for a Car or a Vehicle object. Another rule of thumb: don't overload ==. It makes it very hard (though not impossible) to actually test if two objects are the same. I made this mistake and paid for it for a long time. As for when to overload +=, ++ etc, I'd actually say: only overload additional operators if you have a lot of demand for that functionality. It's easier to have one way to do something than five. Sure, it means sometimes you'll have to write x = x + 1 instead of x += 1, but more code is ok if it's clearer. In general, like with many 'fancy' features, it's easy to think that you want something when you don't really, implement a bunch of stuff, not notice the side effects, and then figure it out later. Err on the conservative side. EDIT: I wanted to add an explanatory note about overloading ==, because it seems various commenters misunderstand this, and it's caught me out. Yes, is exists, but it's a different operation. Say I have an object x, which is either from my custom class, or is an integer. I want to see if x is the number 500. But if you set x = 500, then later test x is 500, you will get False, due to the way Python caches numbers. With 50, it would return True. But you can't use is, because you might want x == 500 to return True if x is an instance of your class. Confusing? Definitely. But this is the kind of detail you need to understand to successfully overload operators. A: Here is an example that uses the bitwise or operation to simulate a unix pipeline. This is intended as a counter example to most of the rules of thumb. I just found Lumberjack which uses this syntax in real code class pipely(object): def __init__(self, *args, **kw): self._args = args self.__dict__.update(kw) def __ror__(self, other): return ( self.map(x) for x in other if self.filter(x) ) def map(self, x): return x def filter(self, x): return True class sieve(pipely): def filter(self, x): n = self._args[0] return x==n or x%n class strify(pipely): def map(self, x): return str(x) class startswith(pipely): def filter(self, x): n=str(self._args[0]) if x.startswith(n): return x print"*"*80 for i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | strify() | startswith(5): print i print"*"*80 for i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | pipely(map=str) | startswith(5): print i print"*"*80 for i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | pipely(map=str) | pipely(filter=lambda x: x.startswith('5')): print i A: Python's overloading is "safer" in general than C++'s -- for example, the assignment operator can't be overloaded, and += has a sensible default implementation. In some ways, though, overloading in Python is still as "broken" as in C++. Programmers should restrain the desire to "re-use" an operator for unrelated purposes, such as C++ re-using the bitshifts to perform string formatting and parsing. Don't overload an operator with different semantics from your implementation just to get prettier syntax. Modern Python style strongly discourages "rogue" overloading, but many aspects of the language and standard library retain poorly-named operators for backwards compatibility. For example: %: modulus and string formatting +: addition and sequence concatenation *: multiplication and sequence repetition So, rule of thumb? If your operator implementation will surprise people, don't do it.
Rules of thumb for when to use operator overloading in python
From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading + you probably also want to overload ++ and +=, and also make sure to handle end cases like adding an object to itself etc.), you should only consider it in those cases where this feature will have a major impact on your code, like overloading the operators for the matrix class in a math application. Does the same apply to python? Would you recommend overriding operator behavior in python? And what rules of thumb can you give me?
[ "Operator overloading is mostly useful when you're making a new class that falls into an existing \"Abstract Base Class\" (ABC) -- indeed, many of the ABCs in standard library module collections rely on the presence of certain special methods (and special methods, one with names starting and ending with double underscores AKA \"dunders\", are exactly the way you perform operator overloading in Python). This provides good starting guidance.\nFor example, a Container class must override special method __contains__, i.e., the membership check operator item in container (as in, if item in container: -- don't confuse with the for statement, for item in container:, which relies on __iter__!-).\nSimilarly, a Hashable must override __hash__, a Sized must override __len__, a Sequence or a Mapping must override __getitem__, and so forth. (Moreover, the ABCs can provide your class with mixin functionality -- e.g., both Sequence and Mapping can provide __contains__ on the basis of your supplied __getitem__ override, and thereby automatically make your class a Container).\nBeyond the collections, you'll want to override special methods (i.e. provide for operator overloading) mostly if your new class \"is a number\". Other special cases exist, but resist the temptation of overloading operators \"just for coolness\", with no semantic connection to the \"normal\" meanings, as C++'s streams do for << and >> and Python strings (in Python 2.*, fortunately not in 3.* any more;-) do for % -- when such operators do not any more mean \"bit-shifting\" or \"division remainder\", you're just engendering confusion. A language's standard library can get away with it (though it shouldn't;-), but unless your library gets as widespread as the language's standard one, the confusion will hurt!-)\n", "I've written software with significant amounts of overloading, and lately I regret that policy. I would say this:\nOnly overload operators if it's the natural, expected thing to do and doesn't have any side effects.\nSo if you make a new RomanNumeral class, it makes sense to overload addition and subtraction etc. But don't overload it unless it's natural: it makes no sense to define addition and subtraction for a Car or a Vehicle object.\nAnother rule of thumb: don't overload ==. It makes it very hard (though not impossible) to actually test if two objects are the same. I made this mistake and paid for it for a long time.\nAs for when to overload +=, ++ etc, I'd actually say: only overload additional operators if you have a lot of demand for that functionality. It's easier to have one way to do something than five. Sure, it means sometimes you'll have to write x = x + 1 instead of x += 1, but more code is ok if it's clearer.\nIn general, like with many 'fancy' features, it's easy to think that you want something when you don't really, implement a bunch of stuff, not notice the side effects, and then figure it out later. Err on the conservative side.\nEDIT: I wanted to add an explanatory note about overloading ==, because it seems various commenters misunderstand this, and it's caught me out. Yes, is exists, but it's a different operation. Say I have an object x, which is either from my custom class, or is an integer. I want to see if x is the number 500. But if you set x = 500, then later test x is 500, you will get False, due to the way Python caches numbers. With 50, it would return True. But you can't use is, because you might want x == 500 to return True if x is an instance of your class. Confusing? Definitely. But this is the kind of detail you need to understand to successfully overload operators.\n", "Here is an example that uses the bitwise or operation to simulate a unix pipeline. This is intended as a counter example to most of the rules of thumb.\nI just found Lumberjack which uses this syntax in real code\n\n\nclass pipely(object):\n def __init__(self, *args, **kw):\n self._args = args\n self.__dict__.update(kw)\n\n def __ror__(self, other):\n return ( self.map(x) for x in other if self.filter(x) )\n\n def map(self, x):\n return x\n\n def filter(self, x):\n return True\n\nclass sieve(pipely):\n def filter(self, x):\n n = self._args[0]\n return x==n or x%n\n\nclass strify(pipely):\n def map(self, x):\n return str(x)\n\nclass startswith(pipely):\n def filter(self, x):\n n=str(self._args[0])\n if x.startswith(n):\n return x\n\nprint\"*\"*80\nfor i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | strify() | startswith(5):\n print i\n\nprint\"*\"*80\nfor i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | pipely(map=str) | startswith(5):\n print i\n\nprint\"*\"*80\nfor i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | pipely(map=str) | pipely(filter=lambda x: x.startswith('5')):\n print i\n\n\n", "Python's overloading is \"safer\" in general than C++'s -- for example, the assignment operator can't be overloaded, and += has a sensible default implementation.\nIn some ways, though, overloading in Python is still as \"broken\" as in C++. Programmers should restrain the desire to \"re-use\" an operator for unrelated purposes, such as C++ re-using the bitshifts to perform string formatting and parsing. Don't overload an operator with different semantics from your implementation just to get prettier syntax.\nModern Python style strongly discourages \"rogue\" overloading, but many aspects of the language and standard library retain poorly-named operators for backwards compatibility. For example:\n\n%: modulus and string formatting\n+: addition and sequence concatenation\n*: multiplication and sequence repetition\n\nSo, rule of thumb? If your operator implementation will surprise people, don't do it.\n" ]
[ 24, 12, 6, 3 ]
[]
[]
[ "operator_overloading", "python" ]
stackoverflow_0001552260_operator_overloading_python.txt
Q: Is there a cleaner way to chain empty list checks in Python? I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this: if a.get("key") and a["key"][0] and a["key"][0][0] : for b in a["key"][0][0] : #Do something which works, but is pretty ugly. It seems there has to be a better way to do this, so what's a more elegant solution? A: try: bs = a["key"][0][0] # Note: the syntax for catching exceptions is different in old versions # of Python. Use whichever one of these lines is appropriate to your version. except KeyError, IndexError, TypeError: # Python 3 except (KeyError, IndexError, TypeError): # Python 2 bs = [] for b in bs: And you can package it up into a function, if you don't mind longer lines: def maybe_list(f): try: return f() except KeyError, IndexError, TypeError: return [] for b in maybe_list(lambda: a["key"][0][0]): A: I would write a custom indexer function like this: def safe_indexer(obj, *indices): for idx in indices: if not obj: break if hasattr(obj, "get"): obj = obj.get(idx) else: obj = obj[idx] return obj Usage: a = {"key": {0: {0: "foo"} } }; print safe_indexer(a, "key", 0, 0) print safe_indexer(a, "bad", 0, 0) Output: foo None A: What about this: try: for b in a['key'][0][0]: # do stuff. except KeyError, TypeError, IndexError: # respond appropriately.
Is there a cleaner way to chain empty list checks in Python?
I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this: if a.get("key") and a["key"][0] and a["key"][0][0] : for b in a["key"][0][0] : #Do something which works, but is pretty ugly. It seems there has to be a better way to do this, so what's a more elegant solution?
[ "try:\n bs = a[\"key\"][0][0]\n# Note: the syntax for catching exceptions is different in old versions\n# of Python. Use whichever one of these lines is appropriate to your version.\nexcept KeyError, IndexError, TypeError: # Python 3\nexcept (KeyError, IndexError, TypeError): # Python 2\n bs = []\nfor b in bs:\n\nAnd you can package it up into a function, if you don't mind longer lines:\ndef maybe_list(f):\n try:\n return f()\n except KeyError, IndexError, TypeError:\n return []\n\nfor b in maybe_list(lambda: a[\"key\"][0][0]):\n\n", "I would write a custom indexer function like this:\ndef safe_indexer(obj, *indices):\n for idx in indices:\n if not obj: break\n\n if hasattr(obj, \"get\"):\n obj = obj.get(idx)\n else:\n obj = obj[idx]\n\n return obj\n\nUsage:\na = {\"key\": {0: {0: \"foo\"} } };\nprint safe_indexer(a, \"key\", 0, 0)\nprint safe_indexer(a, \"bad\", 0, 0)\n\nOutput:\nfoo\nNone\n\n", "What about this:\ntry:\n for b in a['key'][0][0]:\n # do stuff.\nexcept KeyError, TypeError, IndexError:\n # respond appropriately.\n\n" ]
[ 14, 3, 2 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0001552310_coding_style_python.txt
Q: Understanding an example def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks if totLegs == numLegs: return [numPigs, numChicks] return [None, None] def barnYard(heads, legs): pigs, chickens = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens I'm learning Python and came across this example, can someone please explain in plain english (or pseudo-code) what this is doing line by line. Many thanks A: solve is computing how many chicks (1 head, 2 legs) and how many pigs (1 head, 4 legs) it takes to total up to the given numbers of heads and legs. It uses a "brute force", that is, maximally simple, approach: it tries even possible number of chicks from none at all to as many as was specified as number of heads (that's the role of the loop for numChicks in range(0, numHeads + 1):, since range gives integers from the starting value included to the ending value excluded); for each given numChicks it computes how many pigs there would be to give the requested number of heads, by the statement numPigs = numHeads - numChicks then it computes how many total legs those chicks and pigs would have, by totLegs = 4*numPigs + 2*numChicks then it checks if the totLegs equal the requested number: if so, it returns a list with two items, the numbers of chicks and pigs that solve the problem lastly, if it "falls of the bottom" of the for loop without having returned a value yet, it knows there's no solution, and signifies that by returning a list each of whose two items is None. barnYard just delegates the solution to solve, and prints it out in a nice readable way, either as "no solution" or as nicely decorated numbers of chicks and pigs. Now, to keep progressing, ask yourself if solve could be written more efficiently. Clearly there is no solution if the number of legs is less than twice the number of heads, or more than four times the number of heads, or odd -- maybe solve could test for those case and return [None, None] immediately. Could you code that...? It may not be obvious, but every other combination of numbers of heads and legs has a solution -- and there IS a way to find it just by arithmetic, without looping. Think about it, maybe with the help of elementary middle-school algebra... A: Alex Martelli alludes to an algebraic solution which I'll include here for completeness. It can be worked out with the use of simultaneous equations. Being a simple mathematical solution, it's possibly faster, at least for large numbers of legs and heads :-) Let: H be the number of heads; L be the number of legs; C be the number of chicks; and P be the number of pigs. Given C and P, we can calculate the other two variables with: H = C + P (1) L = 2C + 4P (2) I'll detail every step in the calculations below. The mathematically inclined can no doubt point out that steps could be combined but I'd prefer to be explicit. From (1), we can calculate: H = C + P => 0 = C + P - H [subtract H from both sides] => 0 = H - C - P [multiply both sides by -1] => P = H - C [add P to both sides] (3) and substitute that into (2): L = 2C + 4P => L = 2C + 4(H - C) [substitute H-C for P] => L = 2C + 4H - 4C [expand 4(H-C) to 4H-4C] => L = 4H - 2C [combine 2C-4C into -2C] => 0 = 4H - 2C - L [subtract L from both sides] => 2C = 4H - L [add 2C to both sides] => C = 2H - L/2 [divide both sides by 2] (4) Now you have two formulae, one that can calculate the number of chicks from head and legs (4), the other which can calculate number of pigs from chicks and heads (3). So here's the Python code to do it, with appropriate checks to ensure you don't allow some of the more bizarre mathematical solutions, like 2 heads and 7 legs giving us a pig and a half along with half a chick, or 1 head and 12 legs giving 5 pigs and -4 chicks :-) def solve (numLegs, numHeads): # Use the formulae (these make integers). chicks = numHeads * 2 - int (numLegs / 2) pigs = numHeads - chicks # Don't allow negative number of animals. if chicks < 0 or pigs < 0: return [None, None] # Don't allow fractional animals. if chicks * 2 + pigs * 4 != numLegs: return [None, None] if chicks + pigs != numHeads: return [None, None] return [pigs, chicks] Of course, if you pass in fractional numbers of head or legs, all bets are off. Here's a complete test program so you can try out various values to ensure both methods return the same values: import sys def usage (reason): print "Error: %s"%(reason) print "Usage: solve <numHeads> <numLegs>" sys.exit (1); def solve1 (numLegs, numHeads): for numChicks in range (0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4 * numPigs + 2 * numChicks if totLegs == numLegs: return [numPigs, numChicks] return [None, None] def solve2 (numLegs, numHeads): chicks = numHeads * 2 - int (numLegs / 2) pigs = numHeads - chicks if chicks < 0 or pigs < 0: return [None, None] if chicks * 2 + pigs * 4 != numLegs: return [None, None] if chicks + pigs != numHeads: return [None, None] return [pigs, chicks] if len (sys.argv) != 3: usage ("Wrong number of parameters (%d)"%(len (sys.argv))) try: heads = int (sys.argv[1]) except: usage ("Invalid <numHeads> of '%s'"%(sys.argv[1])) try: legs = int (sys.argv[2]) except: usage ("Invalid <numLegs> of '%s'"%(sys.argv[2])) print "[pigs, chicks]:" print " ", solve1 (legs, heads) print " ", solve2 (legs, heads) A: It is iterating through every possible combination of pigs and chickens (with the specified number of heads) until it finds one that has the correct number of legs, and then returns the numbers of pigs and chickens. If it gets through each combination without finding a valid answer, it returns [None, None] to indicate failure. A: Essentially, solve is iterating through every possible combination of chickens and pigs, and when it finds a match, returning it.) NumChickens + NumPigs must equal NumHeads, so it checks every NumChickens from 0 to NumHeads (that's what for range(0,NumHeads+1) does), and sets NumPigs to be NumHeads-NumChickens. From there, its just a matter of multiplying out the number of feet, and seeing if they match. A: Basically, it's trying to figure out the answer to the problem, "How many chickens and pigs are there in a barnyard if there are X heads and Y legs in the barnyard?" The for numChicks in range(0, numHeads + 1):code creates a variables numChicks, and cycles through it from numChicks = 0 to numChicks = numHeads. (Note: the range function doesn't include the highest value). For each number of numChicks, it checks to see if that numChicks and corresponding numPigs values comes up with the correct value of numLegs. numHeads will always be correct since numChicks + numPigs = numHeads, but numLegs varies based on the distribution -- hence the loop. If at any point the solution is found (when totLegs == numLegs), then that value is returned. If the entire loop gets done and no solution was found, then the list [None, None] is returned, meaning that there's no solution for this input.
Understanding an example
def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks if totLegs == numLegs: return [numPigs, numChicks] return [None, None] def barnYard(heads, legs): pigs, chickens = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens I'm learning Python and came across this example, can someone please explain in plain english (or pseudo-code) what this is doing line by line. Many thanks
[ "solve is computing how many chicks (1 head, 2 legs) and how many pigs (1 head, 4 legs) it takes to total up to the given numbers of heads and legs.\nIt uses a \"brute force\", that is, maximally simple, approach: \n\nit tries even possible number of\nchicks from none at all to as many as\nwas specified as number of heads\n(that's the role of the loop for\nnumChicks in range(0, numHeads +\n1):, since range gives integers\nfrom the starting value included\nto the ending value excluded);\nfor each given numChicks it computes\nhow many pigs there would be to give\nthe requested number of heads, by the\nstatement numPigs = numHeads - numChicks\nthen it computes how many total legs\nthose chicks and pigs would have, by\ntotLegs = 4*numPigs + 2*numChicks\nthen it checks if the totLegs equal\nthe requested number: if so, it returns\na list with two items, the numbers of\nchicks and pigs that solve the problem\nlastly, if it \"falls of the bottom\" of\nthe for loop without having returned\na value yet, it knows there's no solution,\nand signifies that by returning a list\neach of whose two items is None.\n\nbarnYard just delegates the solution to solve, and prints it out in a nice readable way, either as \"no solution\" or as nicely decorated numbers of chicks and pigs.\nNow, to keep progressing, ask yourself if solve could be written more efficiently. Clearly there is no solution if the number of legs is less than twice the number of heads, or more than four times the number of heads, or odd -- maybe solve could test for those case and return [None, None] immediately. Could you code that...?\nIt may not be obvious, but every other combination of numbers of heads and legs has a solution -- and there IS a way to find it just by arithmetic, without looping. Think about it, maybe with the help of elementary middle-school algebra...\n", "Alex Martelli alludes to an algebraic solution which I'll include here for completeness. It can be worked out with the use of simultaneous equations. Being a simple mathematical solution, it's possibly faster, at least for large numbers of legs and heads :-)\nLet:\n\nH be the number of heads;\nL be the number of legs;\nC be the number of chicks; and\nP be the number of pigs.\n\nGiven C and P, we can calculate the other two variables with:\nH = C + P (1)\nL = 2C + 4P (2)\n\nI'll detail every step in the calculations below. The mathematically inclined can no doubt point out that steps could be combined but I'd prefer to be explicit. From (1), we can calculate:\n H = C + P\n=> 0 = C + P - H [subtract H from both sides]\n=> 0 = H - C - P [multiply both sides by -1]\n=> P = H - C [add P to both sides] (3)\n\nand substitute that into (2):\n L = 2C + 4P\n=> L = 2C + 4(H - C) [substitute H-C for P]\n=> L = 2C + 4H - 4C [expand 4(H-C) to 4H-4C]\n=> L = 4H - 2C [combine 2C-4C into -2C]\n=> 0 = 4H - 2C - L [subtract L from both sides]\n=> 2C = 4H - L [add 2C to both sides]\n=> C = 2H - L/2 [divide both sides by 2] (4)\n\nNow you have two formulae, one that can calculate the number of chicks from head and legs (4), the other which can calculate number of pigs from chicks and heads (3).\nSo here's the Python code to do it, with appropriate checks to ensure you don't allow some of the more bizarre mathematical solutions, like 2 heads and 7 legs giving us a pig and a half along with half a chick, or 1 head and 12 legs giving 5 pigs and -4 chicks :-)\ndef solve (numLegs, numHeads):\n # Use the formulae (these make integers).\n chicks = numHeads * 2 - int (numLegs / 2)\n pigs = numHeads - chicks\n\n # Don't allow negative number of animals.\n if chicks < 0 or pigs < 0:\n return [None, None]\n\n # Don't allow fractional animals.\n if chicks * 2 + pigs * 4 != numLegs:\n return [None, None]\n if chicks + pigs != numHeads:\n return [None, None]\n\n return [pigs, chicks]\n\nOf course, if you pass in fractional numbers of head or legs, all bets are off. Here's a complete test program so you can try out various values to ensure both methods return the same values:\nimport sys\n\ndef usage (reason):\n print \"Error: %s\"%(reason)\n print \"Usage: solve <numHeads> <numLegs>\"\n sys.exit (1);\n\ndef solve1 (numLegs, numHeads):\n for numChicks in range (0, numHeads + 1):\n numPigs = numHeads - numChicks\n totLegs = 4 * numPigs + 2 * numChicks\n if totLegs == numLegs:\n return [numPigs, numChicks]\n return [None, None]\n\ndef solve2 (numLegs, numHeads):\n chicks = numHeads * 2 - int (numLegs / 2)\n pigs = numHeads - chicks\n if chicks < 0 or pigs < 0: return [None, None]\n if chicks * 2 + pigs * 4 != numLegs: return [None, None]\n if chicks + pigs != numHeads: return [None, None]\n return [pigs, chicks]\n\nif len (sys.argv) != 3:\n usage (\"Wrong number of parameters (%d)\"%(len (sys.argv)))\n\ntry: heads = int (sys.argv[1])\nexcept: usage (\"Invalid <numHeads> of '%s'\"%(sys.argv[1]))\n\ntry: legs = int (sys.argv[2])\nexcept: usage (\"Invalid <numLegs> of '%s'\"%(sys.argv[2]))\n\nprint \"[pigs, chicks]:\"\nprint \" \", solve1 (legs, heads)\nprint \" \", solve2 (legs, heads)\n\n", "It is iterating through every possible combination of pigs and chickens (with the specified number of heads) until it finds one that has the correct number of legs, and then returns the numbers of pigs and chickens. If it gets through each combination without finding a valid answer, it returns [None, None] to indicate failure.\n", "Essentially, solve is iterating through every possible combination of chickens and pigs, and when it finds a match, returning it.)\nNumChickens + NumPigs must equal NumHeads, so it checks every NumChickens from 0 to NumHeads (that's what for range(0,NumHeads+1) does), and sets NumPigs to be NumHeads-NumChickens. \nFrom there, its just a matter of multiplying out the number of feet, and seeing if they match.\n", "Basically, it's trying to figure out the answer to the problem, \"How many chickens and pigs are there in a barnyard if there are X heads and Y legs in the barnyard?\" The for numChicks in range(0, numHeads + 1):code creates a variables numChicks, and cycles through it from numChicks = 0 to numChicks = numHeads. (Note: the range function doesn't include the highest value). \nFor each number of numChicks, it checks to see if that numChicks and corresponding numPigs values comes up with the correct value of numLegs. numHeads will always be correct since numChicks + numPigs = numHeads, but numLegs varies based on the distribution -- hence the loop. If at any point the solution is found (when totLegs == numLegs), then that value is returned. If the entire loop gets done and no solution was found, then the list [None, None] is returned, meaning that there's no solution for this input.\n" ]
[ 8, 2, 1, 1, 1 ]
[]
[]
[ "pseudocode", "python" ]
stackoverflow_0001549828_pseudocode_python.txt
Q: Extracting text fields from HTML using Python? what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number? </tr><tr class="tableRowOdd"> <td>"JSC company inc. 00" &lt;[email protected]&gt;</td> <td>1231231234</td> </tr><tr class="tableRowEven"> <td>"JSC company inc. 01" &lt;[email protected]&gt;</td> <td>234234234234234</td> </tr><tr class="tableRowOdd"> <td>"JSC company inc. 02" &lt;[email protected]&gt;</td> <td>32423234234</td> </tr><tr class="tableRowEven"> <td>"JSC company inc. 03" &lt;[email protected]&gt;</td> <td>23423424324</td> </tr><tr class="tableRowOdd"> <td>"JSC company inc. 04" &lt;[email protected]&gt;</td> <td>234234232324244</td> </tr> <tr> A: For extracting and general HTML munging look at http://www.crummy.com/software/BeautifulSoup/ For the MySQL I suggest googling on: MySQL tutorial python A: Here is how you get the td contents into a python list using BeautifulSoup: #!/usr/bin/python from BeautifulSoup import BeautifulSoup, SoupStrainer def find_rows(data): table_rows = SoupStrainer('tr') rows = [tag for tag in BeautifulSoup(data, parseOnlyThese=table_rows)] return rows def cell_data(row): cells = [tag.string for tag in row.contents] return cells if __name__ == "__main__": f = open("testdata.html", "r") data = f.read() rows = find_rows(data) for row in rows: print cell_data(row) Save your html file as testdata.html, and run this script from the same directory. With the data you posted here, the output is [u'\n', u'"JSC company inc. 00" &lt;[email protected]&gt;', u'\n', u'1231231234', u'\n'] [u'\n', u'"JSC company inc. 01" &lt;[email protected]&gt;', u'\n', u'234234234234234', u'\n'] [u'\n', u'"JSC company inc. 02" &lt;[email protected]&gt;', u'\n', u'32423234234', u'\n'] [u'\n', u'"JSC company inc. 03" &lt;[email protected]&gt;', u'\n', u'23423424324', u'\n'] [u'\n', u'"JSC company inc. 04" &lt;[email protected]&gt;', u'\n', u'234234232324244', u'\n'] A: For the parsing, I definitely also recommend Beautiful Soup. To put the text in a database, I recommend a good Python ORM. My top suggestion is to use the ORM from Django, if you can. With Django, you not only get an ORM, you also get a web interface that lets you browse through your database with a web browser; you can even enter data into the database using the web browser. If you can't use Django, I recommend SQLAlchemy. Good luck. A: With lxml you can do it almost as easily as you could do it with jQuery. from lxml import html doc = html.parse('test.html').getroot() for row in doc.cssselect('tr'): name, phone_number = row.cssselect('td')[:2] print name.text_content() print phone_number.text_content() A: +1 for BeautifulSoup Now that you've got the data, you need to put it into MySQL. If you want a pure python solution, you'll also need the MySQL-Python binding. Otherwise, the SQL you'll need to generate is relatively painless. We'll hijack gnuds example. Add to the top of the file: import re Then at the bottom: exp = r'\"(.*)\" &lt;(.*)&gt;' for row in rows: matcher = re.match(exp, row[1]) name, email = matcher.groups() phone = row[3] sql = "INSERT INTO company (email, name, phone) VALUES ('%s','%s','%s')" % (email, name, phone) print sql Which gives you output like: INSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 00','1231231234'); INSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 01','234234234234234'); INSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 02','32423234234'); INSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 03','23423424324'); INSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 04','234234232324244');
Extracting text fields from HTML using Python?
what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number? </tr><tr class="tableRowOdd"> <td>"JSC company inc. 00" &lt;[email protected]&gt;</td> <td>1231231234</td> </tr><tr class="tableRowEven"> <td>"JSC company inc. 01" &lt;[email protected]&gt;</td> <td>234234234234234</td> </tr><tr class="tableRowOdd"> <td>"JSC company inc. 02" &lt;[email protected]&gt;</td> <td>32423234234</td> </tr><tr class="tableRowEven"> <td>"JSC company inc. 03" &lt;[email protected]&gt;</td> <td>23423424324</td> </tr><tr class="tableRowOdd"> <td>"JSC company inc. 04" &lt;[email protected]&gt;</td> <td>234234232324244</td> </tr> <tr>
[ "For extracting and general HTML munging look at\nhttp://www.crummy.com/software/BeautifulSoup/\n\nFor the MySQL I suggest googling on: MySQL tutorial python \n", "Here is how you get the td contents into a python list using BeautifulSoup:\n#!/usr/bin/python\nfrom BeautifulSoup import BeautifulSoup, SoupStrainer\n\ndef find_rows(data):\n table_rows = SoupStrainer('tr')\n rows = [tag for tag in BeautifulSoup(data, parseOnlyThese=table_rows)]\n return rows\n\ndef cell_data(row):\n cells = [tag.string for tag in row.contents]\n return cells\n\nif __name__ == \"__main__\":\n f = open(\"testdata.html\", \"r\")\n data = f.read()\n rows = find_rows(data)\n for row in rows:\n print cell_data(row)\n\nSave your html file as testdata.html, and run this script from the same directory.\nWith the data you posted here, the output is\n[u'\\n', u'\"JSC company inc. 00\" &lt;[email protected]&gt;', u'\\n', u'1231231234', u'\\n']\n[u'\\n', u'\"JSC company inc. 01\" &lt;[email protected]&gt;', u'\\n', u'234234234234234', u'\\n']\n[u'\\n', u'\"JSC company inc. 02\" &lt;[email protected]&gt;', u'\\n', u'32423234234', u'\\n']\n[u'\\n', u'\"JSC company inc. 03\" &lt;[email protected]&gt;', u'\\n', u'23423424324', u'\\n']\n[u'\\n', u'\"JSC company inc. 04\" &lt;[email protected]&gt;', u'\\n', u'234234232324244', u'\\n']\n\n", "For the parsing, I definitely also recommend Beautiful Soup.\nTo put the text in a database, I recommend a good Python ORM. My top suggestion is to use the ORM from Django, if you can. With Django, you not only get an ORM, you also get a web interface that lets you browse through your database with a web browser; you can even enter data into the database using the web browser.\nIf you can't use Django, I recommend SQLAlchemy.\nGood luck.\n", "With lxml you can do it almost as easily as you could do it with jQuery.\nfrom lxml import html\n\ndoc = html.parse('test.html').getroot()\nfor row in doc.cssselect('tr'):\n name, phone_number = row.cssselect('td')[:2]\n print name.text_content()\n print phone_number.text_content()\n\n", "+1 for BeautifulSoup\nNow that you've got the data, you need to put it into MySQL. If you want a pure python solution, you'll also need the MySQL-Python binding. \nOtherwise, the SQL you'll need to generate is relatively painless. We'll hijack gnuds example. Add to the top of the file:\n import re\n\nThen at the bottom:\nexp = r'\\\"(.*)\\\" &lt;(.*)&gt;'\nfor row in rows:\n matcher = re.match(exp, row[1])\n name, email = matcher.groups()\n phone = row[3]\n\n sql = \"INSERT INTO company (email, name, phone) VALUES ('%s','%s','%s')\" % (email, name, phone)\n print sql\n\nWhich gives you output like:\nINSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 00','1231231234');\nINSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 01','234234234234234');\nINSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 02','32423234234');\nINSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 03','23423424324');\nINSERT INTO company (email, name, phone) VALUES ('[email protected]','JSC company inc. 04','234234232324244');\n\n" ]
[ 6, 1, 1, 1, 0 ]
[]
[]
[ "python", "text" ]
stackoverflow_0001551293_python_text.txt
Q: python adding gibberish when reading from a .rtf file? I have a .rtf file that contains nothing but an integer, say 15. I wish to read this integer in through python and manipulate that integer in some way. However, it seems that python is reading in much of the metadata associated with .rtf files. Why is that? How can I avoid it? For example, trying to read in this file, I get.. {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl720\margr720\margb720\margt720\vieww9000\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural A: That's the nature of .RTF (i.e Rich Text files), they include extra data to define how the text is layed-out and formated. It is not recommended to store data in such files lest you encounter the difficulties you noted. Would you go through the effort to parse this file and "recover" your one numeric value, you may expose your application to the risk of updated versions of the RTF format which may render the parsing logic partially incorrect and hence yield wrong numeric data for the application). Why not store this info in a true text file. This could be a flat text file or preferably an XML, YAML, JSON file for example for added "forward" compatibility as your application and you may add extra parameters and such in the file. If this file is a given, however, there probably exist Python libraries to read and write to it. Check the Python Package Index (PyPI) for the RTF keyword. A: That's exactly what the RTF file contains, so Python (in the absence of further instruction) is giving you what the file contains. You may be looking for a library to read the contents of RTF files, such as pyrtf-ng.
python adding gibberish when reading from a .rtf file?
I have a .rtf file that contains nothing but an integer, say 15. I wish to read this integer in through python and manipulate that integer in some way. However, it seems that python is reading in much of the metadata associated with .rtf files. Why is that? How can I avoid it? For example, trying to read in this file, I get.. {\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl720\margr720\margb720\margt720\vieww9000\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural
[ "That's the nature of .RTF (i.e Rich Text files), they include extra data to define how the text is layed-out and formated.\nIt is not recommended to store data in such files lest you encounter the difficulties you noted. Would you go through the effort to parse this file and \"recover\" your one numeric value, you may expose your application to the risk of updated versions of the RTF format which may render the parsing logic partially incorrect and hence yield wrong numeric data for the application).\nWhy not store this info in a true text file. This could be a flat text file or preferably an XML, YAML, JSON file for example for added \"forward\" compatibility as your application and you may add extra parameters and such in the file.\nIf this file is a given, however, there probably exist Python libraries to read and write to it. Check the Python Package Index (PyPI) for the RTF keyword.\n", "That's exactly what the RTF file contains, so Python (in the absence of further instruction) is giving you what the file contains.\nYou may be looking for a library to read the contents of RTF files, such as pyrtf-ng.\n" ]
[ 4, 4 ]
[]
[]
[ "file_io", "python", "rtf" ]
stackoverflow_0001552886_file_io_python_rtf.txt
Q: Web Service client in Python using ZSI - "Classless struct didn't get dictionary" I am trying to write a sample client in Python using ZSI for a simple Web Service. The Web Service WSDL is following: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.example.org/test/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="test" targetNamespace="http://www.example.org/test/"> <wsdl:message name="NewOperationRequest"> <wsdl:part name="NewOperationRequest" type="xsd:string"/> </wsdl:message> <wsdl:message name="NewOperationResponse"> <wsdl:part name="NewOperationResponse" type="xsd:string"/> </wsdl:message> <wsdl:portType name="test"> <wsdl:operation name="NewOperation"> <wsdl:input message="tns:NewOperationRequest"/> <wsdl:output message="tns:NewOperationResponse"/> </wsdl:operation> </wsdl:portType> <wsdl:binding name="testSOAP" type="tns:test"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="NewOperation"> <soap:operation soapAction="http://www.example.org/test/NewOperation"/> <wsdl:input> <soap:body namespace="http://www.example.org/test/" use="literal"/> </wsdl:input> <wsdl:output> <soap:body namespace="http://www.example.org/test/" use="literal"/> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="test"> <wsdl:port binding="tns:testSOAP" name="testSOAP"> <soap:address location="http://localhost/test"/> </wsdl:port> </wsdl:service> </wsdl:definitions> Every time I run following code: from ZSI.ServiceProxy import ServiceProxy service = ServiceProxy('test.wsdl') service.NewOperation('test') I receive: (...) /var/lib/python-support/python2.5/ZSI/TCcompound.pyc in cb(self, elt, sw, pyobj, name, **kw) 345 f = lambda attr: pyobj.get(attr) 346 if TypeCode.typechecks and type(d) != types.DictType: --> 347 raise TypeError("Classless struct didn't get dictionary") 348 349 indx, lenofwhat = 0, len(self.ofwhat) TypeError: Classless struct didn't get dictionary I have searched Google for this error and I found couple posts describing similar problem but with no answer. Do you know was is wrong here? Is there an error in the WSDL, do I miss something in the code or there is a bug in ZSI? Thank you in advance for you help :-) A: Finally, I have found the solution. I should run like this: from ZSI.ServiceProxy import ServiceProxy service = ServiceProxy('test.wsdl') service.NewOperation(NewOperationRequest='test') The reason of the problem was that the name of the parameter was missing (sic!) - silly error ;-)
Web Service client in Python using ZSI - "Classless struct didn't get dictionary"
I am trying to write a sample client in Python using ZSI for a simple Web Service. The Web Service WSDL is following: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.example.org/test/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="test" targetNamespace="http://www.example.org/test/"> <wsdl:message name="NewOperationRequest"> <wsdl:part name="NewOperationRequest" type="xsd:string"/> </wsdl:message> <wsdl:message name="NewOperationResponse"> <wsdl:part name="NewOperationResponse" type="xsd:string"/> </wsdl:message> <wsdl:portType name="test"> <wsdl:operation name="NewOperation"> <wsdl:input message="tns:NewOperationRequest"/> <wsdl:output message="tns:NewOperationResponse"/> </wsdl:operation> </wsdl:portType> <wsdl:binding name="testSOAP" type="tns:test"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="NewOperation"> <soap:operation soapAction="http://www.example.org/test/NewOperation"/> <wsdl:input> <soap:body namespace="http://www.example.org/test/" use="literal"/> </wsdl:input> <wsdl:output> <soap:body namespace="http://www.example.org/test/" use="literal"/> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="test"> <wsdl:port binding="tns:testSOAP" name="testSOAP"> <soap:address location="http://localhost/test"/> </wsdl:port> </wsdl:service> </wsdl:definitions> Every time I run following code: from ZSI.ServiceProxy import ServiceProxy service = ServiceProxy('test.wsdl') service.NewOperation('test') I receive: (...) /var/lib/python-support/python2.5/ZSI/TCcompound.pyc in cb(self, elt, sw, pyobj, name, **kw) 345 f = lambda attr: pyobj.get(attr) 346 if TypeCode.typechecks and type(d) != types.DictType: --> 347 raise TypeError("Classless struct didn't get dictionary") 348 349 indx, lenofwhat = 0, len(self.ofwhat) TypeError: Classless struct didn't get dictionary I have searched Google for this error and I found couple posts describing similar problem but with no answer. Do you know was is wrong here? Is there an error in the WSDL, do I miss something in the code or there is a bug in ZSI? Thank you in advance for you help :-)
[ "Finally, I have found the solution. \nI should run like this:\nfrom ZSI.ServiceProxy import ServiceProxy\nservice = ServiceProxy('test.wsdl')\nservice.NewOperation(NewOperationRequest='test')\n\nThe reason of the problem was that the name of the parameter was missing (sic!) - silly error ;-)\n" ]
[ 3 ]
[]
[]
[ "python", "wsdl", "zsi" ]
stackoverflow_0001496910_python_wsdl_zsi.txt
Q: Python sqlite3 version Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.4.1' Questions: Why is the version of the sqlite3 module '2.4.1' Whats the reason behind bundling such an old sqlite with Python? The sqlite releaselog says 2002 Mar 13 (2.4.1). A: Python 2.5.1 >>> import sqlite3 >>> sqlite3.version '2.3.2' >>> sqlite3.sqlite_version '3.3.4' version - pysqlite version sqlite_version - sqlite version
Python sqlite3 version
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.4.1' Questions: Why is the version of the sqlite3 module '2.4.1' Whats the reason behind bundling such an old sqlite with Python? The sqlite releaselog says 2002 Mar 13 (2.4.1).
[ "Python 2.5.1\n>>> import sqlite3\n>>> sqlite3.version\n'2.3.2'\n>>> sqlite3.sqlite_version\n'3.3.4'\n\nversion - pysqlite version\nsqlite_version - sqlite version\n" ]
[ 97 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0001553160_python_sqlite.txt
Q: How to strip a list of tuple with python? I have an array with some flag for each case. In order to use print the array in HTML and use colspan, I need to convert this : [{'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}] In this for the open flag: [{'colspan': 12, 'open': False}, {'colspan': 60, 'open': True}, {'colspan': 24, 'open': False}] And another to generate the serve one. How can I do this the smartest way using Python ? I could count the case one by one, but it doesn't seams to be a good idea. A: def cluster(dicts, key): current_value = None current_span = 0 result = [] for d in dicts: value = d[key] if current_value is None: current_value = value elif current_value != value: result.append({'colspan': current_span, key: current_value}) current_value = value current_span = 0 current_span += 1 result.append({'colspan': current_span, key: current_value}) return result by_open = cluster(data, 'open') by_serve = cluster(data, 'serve') Second version, inspired by Denis' answer and his use of itertools.groupby: import itertools import operator def make_spans(data, key): groups = itertools.groupby(data, operator.itemgetter(key)) return [{'colspan': len(list(items)), key: value} for value, items in groups] A: This is not clear what you need, but I hope the following examples will help you: >>> groupped = itertools.groupby(your_list, operator.itemgetter('open')) >>> [{'colspan': len(list(group)), 'open': open} for open, group in groupped] [{'colspan': 12, 'open': False}, {'colspan': 60, 'open': True}, {'colspan': 78, 'open': False}] >>> groupped = itertools.groupby(your_list) >>> [dict(d, colspan=len(list(group))) for d, group in groupped] [{'serve': False, 'open': False, 'colspan': 12}, {'serve': True, 'open': True, 'colspan': 52}, {'serve': False, 'open': True, 'colspan': 8}, {'serve': False, 'open': False, 'colspan': 78}]
How to strip a list of tuple with python?
I have an array with some flag for each case. In order to use print the array in HTML and use colspan, I need to convert this : [{'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}] In this for the open flag: [{'colspan': 12, 'open': False}, {'colspan': 60, 'open': True}, {'colspan': 24, 'open': False}] And another to generate the serve one. How can I do this the smartest way using Python ? I could count the case one by one, but it doesn't seams to be a good idea.
[ "def cluster(dicts, key):\n current_value = None\n current_span = 0\n result = []\n\n for d in dicts:\n value = d[key]\n if current_value is None:\n current_value = value\n elif current_value != value:\n result.append({'colspan': current_span, key: current_value})\n current_value = value\n current_span = 0\n current_span += 1\n\n result.append({'colspan': current_span, key: current_value})\n return result\n\nby_open = cluster(data, 'open')\nby_serve = cluster(data, 'serve')\n\nSecond version, inspired by Denis' answer and his use of itertools.groupby:\nimport itertools\nimport operator\n\ndef make_spans(data, key):\n groups = itertools.groupby(data, operator.itemgetter(key))\n return [{'colspan': len(list(items)), key: value} for value, items in groups]\n\n", "This is not clear what you need, but I hope the following examples will help you:\n>>> groupped = itertools.groupby(your_list, operator.itemgetter('open'))\n>>> [{'colspan': len(list(group)), 'open': open} for open, group in groupped]\n[{'colspan': 12, 'open': False}, {'colspan': 60, 'open': True}, {'colspan': 78, 'open': False}]\n>>> groupped = itertools.groupby(your_list)\n>>> [dict(d, colspan=len(list(group))) for d, group in groupped]\n[{'serve': False, 'open': False, 'colspan': 12}, {'serve': True, 'open': True, 'colspan': 52}, {'serve': False, 'open': True, 'colspan': 8}, {'serve': False, 'open': False, 'colspan': 78}]\n\n" ]
[ 4, 4 ]
[]
[]
[ "dictionary", "flags", "list", "python" ]
stackoverflow_0001553275_dictionary_flags_list_python.txt
Q: % operator in python over string What does the following Python statement mean? send_data="" str_len = "%#04d" % (len(send_data)/2) A: This sets str_len to show half the length of send_data, padded with zeros to be four characters right. The % character is carrying out interpolation. See the printf-style String Formatting section of the documentation.
% operator in python over string
What does the following Python statement mean? send_data="" str_len = "%#04d" % (len(send_data)/2)
[ "This sets str_len to show half the length of send_data, padded with zeros to be four characters right. The % character is carrying out interpolation. See the printf-style String Formatting section of the documentation.\n" ]
[ 4 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0001553434_python_string_formatting.txt
Q: After submitting form, the value is different due to encoding? (Python) I am using Django. In a regular form, the user enters "Gerry & Pacemakers". (Notice the Ampersand sign.) When I go views.py... def myview(request): q = request.GET.get('q','').strip() print q q is "Gerry"...but it's supposed to be "Gerry & Pacemakers"...encoded Is the correct way doing this by using urllib?? How do I encode it BEFORE it hits the view? It's very weird, because the URL contains the encoding: ?q=gerry+%26+pacemakers A: Since you are pulling the data from request.GET, it looks like you're building the URL in the browser somehow. You need to use the Javascript escape() function to handle URL-significant characters properly.
After submitting form, the value is different due to encoding? (Python)
I am using Django. In a regular form, the user enters "Gerry & Pacemakers". (Notice the Ampersand sign.) When I go views.py... def myview(request): q = request.GET.get('q','').strip() print q q is "Gerry"...but it's supposed to be "Gerry & Pacemakers"...encoded Is the correct way doing this by using urllib?? How do I encode it BEFORE it hits the view? It's very weird, because the URL contains the encoding: ?q=gerry+%26+pacemakers
[ "Since you are pulling the data from request.GET, it looks like you're building the URL in the browser somehow. You need to use the Javascript escape() function to handle URL-significant characters properly.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001553564_django_python.txt
Q: Dynamic Finders and Method Missing in Python I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this: Your Person has some fields: name, age and email. Suppose you want to find all the users whose name is "Robot". The Person class has a method called "find_by_name" that receives the name and returns the result of the query: @classmethod def find_by_name(cls, name): return Person.gql("WHERE name = :1", name).get() Instead of having to write a method like that for each attribute, I'd like to have something like Ruby's method_missing that allows me to do it. So far I've seen these 2 blog posts: http://blog.iffy.us/?p=43 and http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm but I'd like to hear what's the "most appropiate" way of doing it. A: There's really no need to use GQL here - it just complicates matters. Here's a simple implementation: class FindableModel(db.Model): def __getattr__(self, name): if not name.startswith("find_by_"): raise AttributeError(name) field = name[len("find_by_"):] return lambda value: self.all().filter(field, value) Note that it returns a Query object, which you can call .get(), .fetch() etc on; this is more versatile, but if you want you can of course make it just return a single entity. A: You could use a 'find_by' method and keywords, like Django does: class Person (object): def find_by(self, *kw): qspec = ' AND '.join('%s=%s' % kv for kv in kw.items()) return self.gql('WHERE ' + qspec) person.find_by(name='Robot') person.find_by(name='Robot', age='2') Down this road you may end up designing your own query syntax. Take a look at what Django does... A: class Person(object): def __getattr__(self, name): if not name.startswith("find_by"): raise AttributeError(name) field_name = name.split("find_by_",1)[1] return lambda name: Person.gql("WHERE %s = :1" % field_name, name).get() A: class Person: name = "" age = 0 salary = 0 def __init__(self, name, age): self.name = name self.age = age def find(clsobj, *args): return Person(name="Jack", age=20) The for loop below inserts @classmethod for all class attributes. This makes "find_by_name", "find_by_age" and "sinf_by_salary" bound methods available. for attr in Person.__dict__.keys(): setattr(Person, 'find_by_'+attr, find) setattr(Person, 'find_by_'+attr, classmethod(find)) print Person.find_by_name("jack").age # will print value 20. I'm not sure if this the right way of doing things. But if you are able to implement a unified "find" for all attributes, then the above script works.
Dynamic Finders and Method Missing in Python
I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this: Your Person has some fields: name, age and email. Suppose you want to find all the users whose name is "Robot". The Person class has a method called "find_by_name" that receives the name and returns the result of the query: @classmethod def find_by_name(cls, name): return Person.gql("WHERE name = :1", name).get() Instead of having to write a method like that for each attribute, I'd like to have something like Ruby's method_missing that allows me to do it. So far I've seen these 2 blog posts: http://blog.iffy.us/?p=43 and http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm but I'd like to hear what's the "most appropiate" way of doing it.
[ "There's really no need to use GQL here - it just complicates matters. Here's a simple implementation:\nclass FindableModel(db.Model):\n def __getattr__(self, name):\n if not name.startswith(\"find_by_\"):\n raise AttributeError(name)\n field = name[len(\"find_by_\"):]\n return lambda value: self.all().filter(field, value)\n\nNote that it returns a Query object, which you can call .get(), .fetch() etc on; this is more versatile, but if you want you can of course make it just return a single entity.\n", "You could use a 'find_by' method and keywords, like Django does:\nclass Person (object):\n def find_by(self, *kw):\n qspec = ' AND '.join('%s=%s' % kv for kv in kw.items())\n return self.gql('WHERE ' + qspec)\n\nperson.find_by(name='Robot')\nperson.find_by(name='Robot', age='2')\n\nDown this road you may end up designing your own query syntax. Take a look at what Django does...\n", "class Person(object):\n def __getattr__(self, name):\n if not name.startswith(\"find_by\"): raise AttributeError(name)\n field_name = name.split(\"find_by_\",1)[1]\n return lambda name: Person.gql(\"WHERE %s = :1\" % field_name, name).get()\n\n", "class Person:\n\n name = \"\"\n age = 0\n salary = 0\n\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\ndef find(clsobj, *args):\n return Person(name=\"Jack\", age=20)\nThe for loop below inserts @classmethod for all class attributes. This makes \"find_by_name\", \"find_by_age\" and \"sinf_by_salary\" bound methods available.\nfor attr in Person.__dict__.keys():\n setattr(Person, 'find_by_'+attr, find)\n setattr(Person, 'find_by_'+attr, classmethod(find))\n\nprint Person.find_by_name(\"jack\").age # will print value 20.\nI'm not sure if this the right way of doing things. But if you are able to implement a unified \"find\" for all attributes, then the above script works.\n" ]
[ 8, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0000913020_google_app_engine_python_web_applications.txt
Q: reading midi input is there a module to read midi input (live) with python? A: I used PyPortMidi successfully in 2006 to record Midi input in real time (on OS X). It should work on Windows, OS X, and Linux. It was very light on the processor side, which was great! A: I had this discussion like ages ago once, and the consensus kinda ended up on using MidiShare, which has Python bindings. But things may have moved on since then, that was like 2004 or something. So it's not a recommendation, just a "check it out".
reading midi input
is there a module to read midi input (live) with python?
[ "I used PyPortMidi successfully in 2006 to record Midi input in real time (on OS X). It should work on Windows, OS X, and Linux. It was very light on the processor side, which was great!\n", "I had this discussion like ages ago once, and the consensus kinda ended up on using MidiShare, which has Python bindings. But things may have moved on since then, that was like 2004 or something. So it's not a recommendation, just a \"check it out\".\n" ]
[ 3, 1 ]
[]
[]
[ "input", "midi", "python" ]
stackoverflow_0001554362_input_midi_python.txt
Q: Extracting info from html using PHP(XPath), PHP/Python(Regexp) or Python(XPath) I have approx. 40k+ html documents where I need to extract information from. I have tried to do so using PHP+Tidy(because most files are not well-formed)+DOMDocument+XPath but it is extremely slow.... I am advised to use regexp but the html files are not marked up semantically (table based layout, with meaning-less tag/classes used everywhere) and I don't know where i should start... Just being curious, is using regexp (PHP/Python) faster than using Python's XPath library? Is Xpath library for Python generally faster than PHP's counterpart? A: If speed is a requirement have a look at lxml. lxml is a pythonic binding for the libxml2 and libxslt C libraries. Using the C libraries is much faster than any pure php or python version. There are some impressive benchmarks from Ian Bicking: In Conclusion I knew lxml was fast before I started these benchmarks, but I didn’t expect it to be quite this fast. Parsing Results: Parsing Resutls http://1.2.3.9/bmi/blog.ianbicking.org/wp-content/uploads/images/parsing-results.png A: You might give Beautiful Soup in Python a try. It's a pretty great parser for generating a usable DOM out of garbage HTML. That with some regex skills might get you what you need. Happy hunting! Most comparative operations in Python are faster than in PHP in my subjective experience. Partly due to Python being a compiled language instead of interpreted at runtime, partly due to Python having been optimized for greater efficiency by its contributors... Still, for 40k+ documents, find a nice fast machine ;-) A: As the previous post mentions Python in general is faster than php due to byte-code compilation (those .pyc files). And a lot of DOM/SAX parsers use fair bit of regexp internally anyway. Those who told you to use regexp need to be told that it is not a magic bullet. For 40k+ documents I would recommend parallelizing the task using the new multi-threads or the classic parallel python.
Extracting info from html using PHP(XPath), PHP/Python(Regexp) or Python(XPath)
I have approx. 40k+ html documents where I need to extract information from. I have tried to do so using PHP+Tidy(because most files are not well-formed)+DOMDocument+XPath but it is extremely slow.... I am advised to use regexp but the html files are not marked up semantically (table based layout, with meaning-less tag/classes used everywhere) and I don't know where i should start... Just being curious, is using regexp (PHP/Python) faster than using Python's XPath library? Is Xpath library for Python generally faster than PHP's counterpart?
[ "If speed is a requirement have a look at lxml. lxml is a pythonic binding for the libxml2 and libxslt C libraries. Using the C libraries is much faster than any pure php or python version.\nThere are some impressive benchmarks from Ian Bicking:\n\nIn Conclusion\nI knew lxml was fast before I started these benchmarks, but I didn’t expect it to be quite this fast.\n\nParsing Results:\nParsing Resutls http://1.2.3.9/bmi/blog.ianbicking.org/wp-content/uploads/images/parsing-results.png\n", "You might give Beautiful Soup in Python a try. It's a pretty great parser for generating a usable DOM out of garbage HTML. That with some regex skills might get you what you need. Happy hunting!\nMost comparative operations in Python are faster than in PHP in my subjective experience. Partly due to Python being a compiled language instead of interpreted at runtime, partly due to Python having been optimized for greater efficiency by its contributors...\nStill, for 40k+ documents, find a nice fast machine ;-)\n", "As the previous post mentions Python in general is faster than php due to byte-code compilation (those .pyc files). And a lot of DOM/SAX parsers use fair bit of regexp internally anyway. Those who told you to use regexp need to be told that it is not a magic bullet. For 40k+ documents I would recommend parallelizing the task using the new multi-threads or the classic parallel python.\n" ]
[ 3, 2, 0 ]
[]
[]
[ "html", "php", "python", "regex", "xpath" ]
stackoverflow_0001553511_html_php_python_regex_xpath.txt
Q: Python Clientform-can not get expexted result I am trying to search through http://www.wegottickets.com/ with the keywords "Live music". But the returned result is still the main page, not the search result page including lots of live music information. Could anyone show me out what the problem is? from urllib2 import urlopen from ClientForm import ParseResponse response = urlopen("http://www.wegottickets.com/") forms = ParseResponse(response, backwards_compat=False) form = forms[0] form.set_value("Live music", name="unified_query") form.set_all_readonly(False) control = form.find_control(type="submit") print control.disabled print control.readonly #print form request2 = form.click() try: response2 = urlopen(request2) except: print "Unsccessful query" print response2.geturl() print response2.info() print response.read() response2.close() Thank you very much! A: Never used it, but I've had success with the python mechanize module, if it turns out to be a fault in clientform. However, as a first step, I'd suggest removing your try...except wrapper. What you're basically doing is saying "catch any error, then ignore the actual error and print 'Unsuccessful Query' instead". Not helpful for debugging. The exception will stop the program and print a useful error message, if you don't get in its way.
Python Clientform-can not get expexted result
I am trying to search through http://www.wegottickets.com/ with the keywords "Live music". But the returned result is still the main page, not the search result page including lots of live music information. Could anyone show me out what the problem is? from urllib2 import urlopen from ClientForm import ParseResponse response = urlopen("http://www.wegottickets.com/") forms = ParseResponse(response, backwards_compat=False) form = forms[0] form.set_value("Live music", name="unified_query") form.set_all_readonly(False) control = form.find_control(type="submit") print control.disabled print control.readonly #print form request2 = form.click() try: response2 = urlopen(request2) except: print "Unsccessful query" print response2.geturl() print response2.info() print response.read() response2.close() Thank you very much!
[ "Never used it, but I've had success with the python mechanize module, if it turns out to be a fault in clientform.\nHowever, as a first step, I'd suggest removing your try...except wrapper. What you're basically doing is saying \"catch any error, then ignore the actual error and print 'Unsuccessful Query' instead\". Not helpful for debugging. The exception will stop the program and print a useful error message, if you don't get in its way.\n" ]
[ 0 ]
[]
[]
[ "clientform", "python" ]
stackoverflow_0001554534_clientform_python.txt
Q: Using Python locale or equivalent in web applications? Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale. And there are warnings in the locale docs that make the whole thing scary: On top of that, some implementation are broken in such a way that frequent locale changes may cause core dumps. This makes the locale somewhat painful to use correctly And It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program So, is there a reasonable locale alternative for use in web apps? Is Babel it or are there other alternatives? I'm looking for something that will handle currencies as well as dates and numbers. [Update] To clarify, I'm most interested in date, number, and currency formatting for various locales. A: locale is no good for any app that needs to support several locales -- it's really badly designed for those apps (basically any server-side app, including web apps). Where feasible, PyICU is a vastly superior solution -- top-quality i18n/L10n support, speed, flexibility (downside: while ICU's docs are good, PyICU's, well, not so much;-). Alas, not always are you allowed to deploy your own extensions...:-(. In particular, I'm still looking for a solid i18n/L10n solution for App Engine apps -- "translation" per se is the least of issues (you can just switch to the right set of templates), the problem is that there are many other L10n aspects (the ones that ICU supports so well, such as collation rules for example, etc, etc). I guess the already-mentioned Babel is the only sensible place to start from. A: Don't use setlocale. Check how it is done in django. It looks like they use class api of gettext library and do not use the setlocale function I bet there is a reason for this. They manually store a translation per thread check here how it is implemented (gettext function and _active dictionary). A: Your best approach will be to setlocale on the locale that the browser passes you, if you're doing currencies, dates, and numbers. There's a lot of zomgz warnings in the Python documentation for really off-color platforms; most of these can be ignored. "Frequent locale changes" shouldn't matter, unless I'm missing something. You're not doing message catalogs or anything fancy, so stick with what Python gives you. A: Django's i18n framework works out the shortcomings of setlocale() by not using it. This way the locale is set per request and if you use LocaleMiddleware it can be set to change according to UserAgent Accept-Language setting. See the docs.
Using Python locale or equivalent in web applications?
Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale. And there are warnings in the locale docs that make the whole thing scary: On top of that, some implementation are broken in such a way that frequent locale changes may cause core dumps. This makes the locale somewhat painful to use correctly And It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program So, is there a reasonable locale alternative for use in web apps? Is Babel it or are there other alternatives? I'm looking for something that will handle currencies as well as dates and numbers. [Update] To clarify, I'm most interested in date, number, and currency formatting for various locales.
[ "locale is no good for any app that needs to support several locales -- it's really badly designed for those apps (basically any server-side app, including web apps). Where feasible, PyICU is a vastly superior solution -- top-quality i18n/L10n support, speed, flexibility (downside: while ICU's docs are good, PyICU's, well, not so much;-). Alas, not always are you allowed to deploy your own extensions...:-(.\nIn particular, I'm still looking for a solid i18n/L10n solution for App Engine apps -- \"translation\" per se is the least of issues (you can just switch to the right set of templates), the problem is that there are many other L10n aspects (the ones that ICU supports so well, such as collation rules for example, etc, etc). I guess the already-mentioned Babel is the only sensible place to start from.\n", "Don't use setlocale.\nCheck how it is done in django. It looks like they use class api of gettext library and do not use the setlocale function I bet there is a reason for this.\nThey manually store a translation per thread check here how it is implemented (gettext function and _active dictionary).\n", "Your best approach will be to setlocale on the locale that the browser passes you, if you're doing currencies, dates, and numbers. There's a lot of zomgz warnings in the Python documentation for really off-color platforms; most of these can be ignored.\n\"Frequent locale changes\" shouldn't matter, unless I'm missing something.\nYou're not doing message catalogs or anything fancy, so stick with what Python gives you.\n", "Django's i18n framework works out the shortcomings of setlocale() by not using it. This way the locale is set per request and if you use LocaleMiddleware it can be set to change according to UserAgent Accept-Language setting. See the docs.\n" ]
[ 14, 1, 0, 0 ]
[]
[]
[ "django", "internationalization", "python" ]
stackoverflow_0001551508_django_internationalization_python.txt
Q: Implementing "Starts with" and "Ends with" queries with Google App Engine Am wondering if anyone can provide some guidance on how I might implement a starts with or ends with query against a Datastore model using Python? In pseudo code, it would work something like... Query for all entities A where property P starts with X or Query for all entities B where property P ends with X Thanks, Matt A: You can do a 'starts with' query by using inequality filters: MyModel.all().filter('prop >=', prefix).filter('prop <', prefix + u'\ufffd') Doing an 'ends with' query would require storing the reverse of the string, then applying the same tactic as above. A: Seems you can't do it for the general case, but can do it for prefix searches (starts with): Wildcard search on Appengine in python
Implementing "Starts with" and "Ends with" queries with Google App Engine
Am wondering if anyone can provide some guidance on how I might implement a starts with or ends with query against a Datastore model using Python? In pseudo code, it would work something like... Query for all entities A where property P starts with X or Query for all entities B where property P ends with X Thanks, Matt
[ "You can do a 'starts with' query by using inequality filters:\nMyModel.all().filter('prop >=', prefix).filter('prop <', prefix + u'\\ufffd')\n\nDoing an 'ends with' query would require storing the reverse of the string, then applying the same tactic as above.\n", "Seems you can't do it for the general case, but can do it for prefix searches (starts with):\nWildcard search on Appengine in python\n" ]
[ 16, 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001554600_google_app_engine_google_cloud_datastore_python.txt
Q: How do I ask for an authenticated url directly with python I want to get to an authenticated page using urllib2. I'm hoping there's a hack to do it directly. something like: urllib2.urlopen('http://username:pwd@server/page') If not, how do I use authentication? A: It depends on the type of authentication used. A simple example is Http Authentication If the site uses cookies for auth you need to add a cookiejar and login over http there are many more auth schemes, so find out which you need. A: AFAIK, there isn't a trivial way of doing this. Basically, you make a request and the server responds with a 401 authorization required, which urllib2 translates into an exception. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python25\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Authorization Required You will have to catch this exception, create a urllib2.HTTPPasswordManager object, add the username and password to the HTTPPasswordManager, create a urllib2.HTTPBasicAuthHandler object, create an opener object and finally fetch the url using the opener. Code and a tutorial is available here: http://www.voidspace.org.uk/python/articles/urllib2.shtml#id5
How do I ask for an authenticated url directly with python
I want to get to an authenticated page using urllib2. I'm hoping there's a hack to do it directly. something like: urllib2.urlopen('http://username:pwd@server/page') If not, how do I use authentication?
[ "It depends on the type of authentication used. \n\nA simple example is Http Authentication\nIf the site uses cookies for auth you need to add a cookiejar and login over http\nthere are many more auth schemes, so find out which you need.\n\n", "AFAIK, there isn't a trivial way of doing this. Basically, you make a request and the server responds with a 401 authorization required, which urllib2 translates into an exception. \n Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"C:\\Python25\\lib\\urllib2.py\", line 124, in urlopen\n return _opener.open(url, data)\n File \"C:\\Python25\\lib\\urllib2.py\", line 387, in open\n response = meth(req, response)\n File \"C:\\Python25\\lib\\urllib2.py\", line 498, in http_response\n 'http', request, response, code, msg, hdrs)\n File \"C:\\Python25\\lib\\urllib2.py\", line 425, in error\n return self._call_chain(*args)\n File \"C:\\Python25\\lib\\urllib2.py\", line 360, in _call_chain\n result = func(*args)\n File \"C:\\Python25\\lib\\urllib2.py\", line 506, in http_error_default\n raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)\n urllib2.HTTPError: HTTP Error 401: Authorization Required \n\nYou will have to catch this exception, create a urllib2.HTTPPasswordManager object, add the username and password to the HTTPPasswordManager, create a urllib2.HTTPBasicAuthHandler object, create an opener object and finally fetch the url using the opener. Code and a tutorial is available here: http://www.voidspace.org.uk/python/articles/urllib2.shtml#id5\n" ]
[ 2, 1 ]
[]
[]
[ "authentication", "python", "urllib2" ]
stackoverflow_0001554745_authentication_python_urllib2.txt
Q: Getting input from MIDI devices live (Python) I've got a trigger finger (MIDI tablet) and I want to be able to read its input live and make python execute actions depending on the pressed key. I need it for Windows, and preferably working with python 2.5 + Thanks A: PyGame includes a built-in midi module, available for Linux, Windows and MacOS and is very well supported. For example, here is the documentation for pygame.midi.Input: Input is used to get midi input from midi devices. Input(device_id) Input(device_id, buffer_size) Input.close - closes a midi stream, flushing any pending buffers. closes a midi stream, flushing any pending buffers. Input.poll - returns true if there's data, or false if not. returns true if there's data, or false if not. Input.read - reads num_events midi events from the buffer. reads num_events midi events from the buffer. If you're looking for an alternative, have a look at PythonInMusic in the Python wiki. There are various different projects related to MIDI input and output there, some for Windows as well. (Click the little > sign after each project to follow the link to the project homepage) I have not used any of them personally, but I'm sure it will help you get started.
Getting input from MIDI devices live (Python)
I've got a trigger finger (MIDI tablet) and I want to be able to read its input live and make python execute actions depending on the pressed key. I need it for Windows, and preferably working with python 2.5 + Thanks
[ "PyGame includes a built-in midi module, available for Linux, Windows and MacOS and is very well supported.\nFor example, here is the documentation for pygame.midi.Input:\n Input is used to get midi input from midi devices.\n Input(device_id)\n Input(device_id, buffer_size)\n Input.close - closes a midi stream, flushing any pending buffers. closes a midi stream, flushing any pending buffers.\n Input.poll - returns true if there's data, or false if not. returns true if there's data, or false if not.\n Input.read - reads num_events midi events from the buffer. reads num_events midi events from the buffer.\n\nIf you're looking for an alternative, have a look at PythonInMusic in the Python wiki.\nThere are various different projects related to MIDI input and output there, some for Windows as well. (Click the little > sign after each project to follow the link to the project homepage)\nI have not used any of them personally, but I'm sure it will help you get started.\n" ]
[ 10 ]
[]
[]
[ "midi", "python" ]
stackoverflow_0001554896_midi_python.txt
Q: How do I know what's the realm and uri of a site I want to use python's urllib2 with authentication and I need the realm and uri of a url. How do I get it? thanks A: When you make a request for a resource that requires authentication, the server will respond with a 401 status code, and a header that contains the realm: WWW-Authenticate: Basic realm="the realm" The URI is the URL you're trying to access.
How do I know what's the realm and uri of a site
I want to use python's urllib2 with authentication and I need the realm and uri of a url. How do I get it? thanks
[ "When you make a request for a resource that requires authentication, the server will respond with a 401 status code, and a header that contains the realm:\nWWW-Authenticate: Basic realm=\"the realm\"\n\nThe URI is the URL you're trying to access.\n" ]
[ 1 ]
[]
[]
[ "authentication", "python", "urllib2" ]
stackoverflow_0001555018_authentication_python_urllib2.txt
Q: Problem to make an apache server run correctly under mod_python We try to migrate our old server to a new one but we experienced some problems with mod_python. The problem is under this web page: http://auction.tinyerp.org/auction-in-europe.com/aie/ Here is our apache2 configuration: NameVirtualHost * <VirtualHost *> DocumentRoot /var/www/ <Directory /> Options FollowSymLinks AllowOverride all </Directory> <Directory "/var/www/auction-in-europe.com/aie"> Options Indexes FollowSymLinks MultiViews #AddHandler mod_python .py PythonOption mod_python.legacy.importer * SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On AllowOverride all Order allow,deny allow from all # This directive allows us to have apache2's default start page # in /apache2-default/, but still have / go to the right place </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ScriptAlias /bin/ /home/www/auction-in-europe.com/aie/bin/ ServerAdmin [email protected] ErrorLog /home/logs/auction-in-europe.com/error_log CustomLog /home/logs/auction-in-europe.com/access_log combined ServerName auction-in-europe.com ServerAlias www.auction-in-europe.com antique-in-europe.com www.antique-in-europe.com art-in-europe.com www.art-in-europe.com en.art-in-europe.com ServerAlias en.antique-in-europe.com en.auction-in-europe.com fr.antique-in-europe.com fr.art-in-europe.com fr.auction-in-europe.com auction.tinyerp.org #RewriteEngine on #RewriteRule ^/(.*)\.html /index.py [E=pg:$1] ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On Alias /doc/ "/usr/share/doc/" <Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </Directory> <Directory /home/www/postfixadmin> </Directory> </VirtualHost> Logs are quite empty: [Mon Oct 12 13:25:58 2009] [notice] mod_python: (Re)importing module 'mod_python.publisher' [Mon Oct 12 13:25:58 2009] [notice] [client 212.166.58.166] Publisher loading page /home/www/auction-in-europe.com/aie/index.py I really have no idea where to start. Please help! A: #!/usr/bin/python import os, sys base_dir = "/home/www/auction-in-europe.com/aie/" sys.path.insert(0, base_dir) import albatross import sql_db from albatross.apacheapp import Request from albatross import apacheapp from albatross.template import Content, EmptyTag, EnclosingTag import string import common class AppContext(albatross.SessionFileAppContext): def __init__(self, app): albatross.SessionFileAppContext.__init__(self, app) # path = os.environ.get('PATH_INFO','').split('/') # path = filter(lambda x: x, path) # self.module = path.pop(0) # self.path = {} # while path: # val = path.pop() # self.path[ path.pop() ] = val def load_template_once(self, template): new_template = os.path.join(self.lang_get(),template) return albatross.SessionFileAppContext.load_template_once(new_template) def load_template(self, template): new_template = os.path.join(self.lang_get(),template) return albatross.SessionFileAppContext.load_template(self,new_template) def run_template_once(self, template): new_template = os.path.join(self.lang_get(), template) return albatross.SessionFileAppContext.run_template_once(self,new_template) def run_template(self, template): new_template = os.path.join(self.lang_get(), template) return albatross.SessionFileAppContext.run_template(self,new_template) def req_get(self): return self.current_url()[len(self.base_url())+1:] def args_calc(self): path = self.current_url()[len(self.base_url())+1:].split('/') path = filter(lambda x: x, path) if not len(path): path=['index'] self.module = path.pop(0) self.path = {} while path: val = path.pop() self.path[ path.pop() ] = val def lang_get(self): if self.request.get_header('host')[:3] in ('fr.','en.'): return self.request.get_header('host')[:2] try: language = self.request.get_header('Accept-Language') if language: new_lang = language[:2] if new_lang in ('fr','en'): return new_lang except: return 'en' return 'en' def hostname_get(self): if self.request.get_header('host')[-17:]=='art-in-europe.com': return 'art' elif self.request.get_header('host')[-21:]=='antique-in-europe.com': return 'antique' else: return 'auction' def module_get(self): self.args_calc() return self.module def path_get(self, key): self.args_calc() return self.path[key] class App(albatross.ModularSessionFileApp): def __init__(self): albatross.ModularSessionFileApp.__init__(self, base_url = '/index.py', module_path = os.path.join(base_dir, 'modules'), template_path = os.path.join(base_dir, 'template'), start_page = 'index', secret = '(=-AiE-)', session_appid='A-i-E', session_dir='/var/tmp/albatross/') def create_context(self): return AppContext(self) class alx_a(albatross.EnclosingTag): name = 'alx-a' def to_html(self, ctx): ctx.write_content('') albatross.EnclosingTag.to_html(self, ctx) ctx.write_content('') # Escape text for attribute values def escape_br(text): text = str(text) text = string.replace(text, '&', '&') text = string.replace(text, '', '>',) text = string.replace(text, '"', '"') text = string.replace(text, "'", '') text = string.replace(text, "\n", '') return text class alx_value(EmptyTag): name = 'alx-value' def __init__(self, ctx, filename, line_num, attribs): EmptyTag.__init__(self, ctx, filename, line_num, attribs) #self.compile_expr() def to_html(self, ctx): value = ctx.eval_expr(self.get_attrib('expr')) format = self.get_attrib('date') if format: value = time.strftime(format, time.localtime(value)) ctx.write_content(value) return lookup_name = self.get_attrib('lookup') if lookup_name: lookup = ctx.get_lookup(lookup_name) if not lookup: self.raise_error('undefined lookup "%s"' % lookup_name) lookup.lookup_html(ctx, value) return if self.has_attrib('noescape'): ctx.write_content(str(value)) else: ctx.write_content(escape_br(value)) app = App() app.register_tagclasses(alx_a) app.register_tagclasses(alx_value) def handler(req): return app.run(apacheapp.Request(req)) A: Is that the index.py? I believe you are mixing up your install. You use the "PythonHandler mod_python.publisher" if you do not want to write your own handler. The file you just posted contains a handler, the lines: def handler(req): return app.run(apacheapp.Request(req)) This is rather difficult to trouble-shoot but I believe your apache config should be closer to this: <Directory "/var/www/auction-in-europe.com/aie"> Order allow,deny Allow from all SetHandler python-program .py PythonHandler index ## or what ever the above file is called without the .py PythonDebug On </Directory> This will make all requests to "/var/www/auction-in-europe.com/aie" get handled by index.py.
Problem to make an apache server run correctly under mod_python
We try to migrate our old server to a new one but we experienced some problems with mod_python. The problem is under this web page: http://auction.tinyerp.org/auction-in-europe.com/aie/ Here is our apache2 configuration: NameVirtualHost * <VirtualHost *> DocumentRoot /var/www/ <Directory /> Options FollowSymLinks AllowOverride all </Directory> <Directory "/var/www/auction-in-europe.com/aie"> Options Indexes FollowSymLinks MultiViews #AddHandler mod_python .py PythonOption mod_python.legacy.importer * SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On AllowOverride all Order allow,deny allow from all # This directive allows us to have apache2's default start page # in /apache2-default/, but still have / go to the right place </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ScriptAlias /bin/ /home/www/auction-in-europe.com/aie/bin/ ServerAdmin [email protected] ErrorLog /home/logs/auction-in-europe.com/error_log CustomLog /home/logs/auction-in-europe.com/access_log combined ServerName auction-in-europe.com ServerAlias www.auction-in-europe.com antique-in-europe.com www.antique-in-europe.com art-in-europe.com www.art-in-europe.com en.art-in-europe.com ServerAlias en.antique-in-europe.com en.auction-in-europe.com fr.antique-in-europe.com fr.art-in-europe.com fr.auction-in-europe.com auction.tinyerp.org #RewriteEngine on #RewriteRule ^/(.*)\.html /index.py [E=pg:$1] ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On Alias /doc/ "/usr/share/doc/" <Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </Directory> <Directory /home/www/postfixadmin> </Directory> </VirtualHost> Logs are quite empty: [Mon Oct 12 13:25:58 2009] [notice] mod_python: (Re)importing module 'mod_python.publisher' [Mon Oct 12 13:25:58 2009] [notice] [client 212.166.58.166] Publisher loading page /home/www/auction-in-europe.com/aie/index.py I really have no idea where to start. Please help!
[ "\n#!/usr/bin/python\nimport os, sys\nbase_dir = \"/home/www/auction-in-europe.com/aie/\"\nsys.path.insert(0, base_dir)\nimport albatross\nimport sql_db\nfrom albatross.apacheapp import Request\nfrom albatross import apacheapp\nfrom albatross.template import Content, EmptyTag, EnclosingTag\nimport string\nimport common\nclass AppContext(albatross.SessionFileAppContext):\n def __init__(self, app):\n albatross.SessionFileAppContext.__init__(self, app)\n# path = os.environ.get('PATH_INFO','').split('/')\n# path = filter(lambda x: x, path)\n# self.module = path.pop(0)\n# self.path = {}\n# while path:\n# val = path.pop()\n# self.path[ path.pop() ] = val\n def load_template_once(self, template):\n new_template = os.path.join(self.lang_get(),template)\n return albatross.SessionFileAppContext.load_template_once(new_template)\n def load_template(self, template):\n new_template = os.path.join(self.lang_get(),template)\n return albatross.SessionFileAppContext.load_template(self,new_template)\n def run_template_once(self, template):\n new_template = os.path.join(self.lang_get(), template)\n return albatross.SessionFileAppContext.run_template_once(self,new_template)\n def run_template(self, template):\n new_template = os.path.join(self.lang_get(), template)\n return albatross.SessionFileAppContext.run_template(self,new_template)\n def req_get(self):\n return self.current_url()[len(self.base_url())+1:]\n def args_calc(self):\n path = self.current_url()[len(self.base_url())+1:].split('/')\n path = filter(lambda x: x, path)\n if not len(path):\n path=['index']\n self.module = path.pop(0)\n self.path = {}\n while path:\n val = path.pop()\n self.path[ path.pop() ] = val\n def lang_get(self):\n if self.request.get_header('host')[:3] in ('fr.','en.'):\n return self.request.get_header('host')[:2]\n try:\n language = self.request.get_header('Accept-Language')\n if language:\n new_lang = language[:2]\n if new_lang in ('fr','en'):\n return new_lang\n except:\n return 'en'\n return 'en'\n def hostname_get(self):\n if self.request.get_header('host')[-17:]=='art-in-europe.com':\n return 'art'\n elif self.request.get_header('host')[-21:]=='antique-in-europe.com':\n return 'antique'\n else:\n return 'auction'\n def module_get(self):\n self.args_calc()\n return self.module\n def path_get(self, key):\n self.args_calc()\n return self.path[key]\nclass App(albatross.ModularSessionFileApp):\n def __init__(self):\n albatross.ModularSessionFileApp.__init__(self,\n base_url = '/index.py',\n module_path = os.path.join(base_dir, 'modules'),\n template_path = os.path.join(base_dir, 'template'),\n start_page = 'index',\n secret = '(=-AiE-)',\n session_appid='A-i-E',\n session_dir='/var/tmp/albatross/')\n def create_context(self):\n return AppContext(self)\nclass alx_a(albatross.EnclosingTag):\n name = 'alx-a'\n def to_html(self, ctx):\n ctx.write_content('')\n albatross.EnclosingTag.to_html(self, ctx)\n ctx.write_content('')\n# Escape text for attribute values\ndef escape_br(text):\n text = str(text)\n text = string.replace(text, '&', '&')\n text = string.replace(text, '', '>',)\n text = string.replace(text, '\"', '\"')\n text = string.replace(text, \"'\", '')\n text = string.replace(text, \"\\n\", '')\n return text\nclass alx_value(EmptyTag):\n name = 'alx-value'\n def __init__(self, ctx, filename, line_num, attribs):\n EmptyTag.__init__(self, ctx, filename, line_num, attribs)\n #self.compile_expr()\n def to_html(self, ctx):\n value = ctx.eval_expr(self.get_attrib('expr'))\n format = self.get_attrib('date')\n if format:\n value = time.strftime(format, time.localtime(value))\n ctx.write_content(value)\n return\n lookup_name = self.get_attrib('lookup')\n if lookup_name:\n lookup = ctx.get_lookup(lookup_name)\n if not lookup:\n self.raise_error('undefined lookup \"%s\"' % lookup_name)\n lookup.lookup_html(ctx, value)\n return\n if self.has_attrib('noescape'):\n ctx.write_content(str(value))\n else:\n ctx.write_content(escape_br(value))\napp = App()\napp.register_tagclasses(alx_a)\napp.register_tagclasses(alx_value)\ndef handler(req):\n return app.run(apacheapp.Request(req)) \n", "Is that the index.py? I believe you are mixing up your install. You use the \"PythonHandler mod_python.publisher\" if you do not want to write your own handler. The file you just posted contains a handler, the lines:\ndef handler(req):\n return app.run(apacheapp.Request(req)) \n\nThis is rather difficult to trouble-shoot but I believe your apache config should be closer to this:\n <Directory \"/var/www/auction-in-europe.com/aie\">\n Order allow,deny\n Allow from all\n SetHandler python-program .py\n PythonHandler index ## or what ever the above file is called without the .py\n PythonDebug On \n </Directory>\n\nThis will make all requests to \"/var/www/auction-in-europe.com/aie\" get handled by index.py.\n" ]
[ 0, 0 ]
[]
[]
[ "apache2", "mod_python", "python" ]
stackoverflow_0001554673_apache2_mod_python_python.txt
Q: Worker/Timeslot permutation/constraint filtering algorithm Hope you can help me out with this guys. It's not help with work -- it's for a charity of very hard working volunteers, who could really use a less confusing/annoying timetable system than what they currently have. If anyone knows of a good third-party app which (certainly) automate this, that would almost as good. Just... please don't suggest random timetabling stuff such as the ones for booking classrooms, as I don't think they can do this. Thanks in advance for reading; I know it's a big post. I'm trying to do my best to document this clearly though, and to show that I've made efforts on my own. Problem I need a worker/timeslot scheduling algorithm which generates shifts for workers, which meets the following criteria: Input Data import datetime.datetime as dt class DateRange: def __init__(self, start, end): self.start = start self.end = end class Shift: def __init__(self, range, min, max): self.range = range self.min_workers = min self.max_workers = max tue_9th_10pm = dt(2009, 1, 9, 22, 0) wed_10th_4am = dt(2009, 1, 10, 4, 0) wed_10th_10am = dt(2009, 1, 10, 10, 0) shift_1_times = Range(tue_9th_10pm, wed_10th_4am) shift_2_times = Range(wed_10th_4am, wed_10th_10am) shift_3_times = Range(wed_10th_10am, wed_10th_2pm) shift_1 = Shift(shift_1_times, 2,3) # allows 3, requires 2, but only 2 available shift_2 = Shift(shift_2_times, 2,2) # allows 2 shift_3 = Shift(shift_3_times, 2,3) # allows 3, requires 2, 3 available shifts = ( shift_1, shift_2, shift_3 ) joe_avail = [ shift_1, shift_2 ] bob_avail = [ shift_1, shift_3 ] sam_avail = [ shift_2 ] amy_avail = [ shift_2 ] ned_avail = [ shift_2, shift_3 ] max_avail = [ shift_3 ] jim_avail = [ shift_3 ] joe = Worker('joe', joe_avail) bob = Worker('bob', bob_avail) sam = Worker('sam', sam_avail) ned = Worker('ned', ned_avail) max = Worker('max', max_avail) amy = Worker('amy', amy_avail) jim = Worker('jim', jim_avail) workers = ( joe, bob, sam, ned, max, amy, jim ) Processing From above, shifts and workers are the two main input variables to process Each shift has a minimum and maximum number of workers needed. Filling the minimum requirements for a shift is crucial to success, but if all else fails, a rota with gaps to be filled manually is better than "error" :) The main algorithmic issue is that there shouldn't be unnecessary gaps, when enough workers are available. Ideally, the maximum number of workers for a shift would be filled, but this is the lowest priority relative to other constraints, so if anything has to give, it should be this. Flexible constraints These are a little flexible, and their boundaries can be pushed a little if a "perfect" solution can't be found. This flexibility should be a last resort though, rather than being exploited randomly. Ideally, the flexibility would be configurable with a "fudge_factor" variable, or similar. There is a minimum time period between two shifts. So, a worker shouldn't be scheduled for two shifts in the same day, for instance. There are a maximum number of shifts a worker can do in a given time period (say, a month) There are a maximum number of certain shifts that can be done in a month (say, overnight shifts) Nice to have, but not necessary If you can come up with an algorithm which does the above and includes any/all of these, I'll be seriously impressed and grateful. Even an add-on script to do these bits separately would be great too. Overlapping shifts. For instance, it would be good to be able to specify a "front desk" shift and a "back office" shift that both occur at the same time. This could be done with separate invocations of the program with different shift data, except that the constraints about scheduling people for multiple shifts in a given time period would be missed. Minimum reschedule time period for workers specifiable on a per-worker (rather than global) basis. For instance, if Joe is feeling overworked or is dealing with personal issues, or is a beginner learning the ropes, we might want to schedule him less often than other workers. Some automated/random/fair way of selecting staff to fill minimum shift numbers when no available workers fit. Some way of handling sudden cancellations, and just filling the gaps without rearranging other shifts. Output Test Probably, the algorithm should generate as many matching Solutions as possible, where each Solution looks like this: class Solution: def __init__(self, shifts_workers): """shifts_workers -- a dictionary of shift objects as keys, and a a lists of workers filling the shift as values.""" assert isinstance(dict, shifts_workers) self.shifts_workers = shifts_workers Here's a test function for an individual solution, given the above data. I think this is right, but I'd appreciate some peer review on it too. def check_solution(solution): assert isinstance(Solution, solution) def shift_check(shift, workers, workers_allowed): assert isinstance(Shift, shift): assert isinstance(list, workers): assert isinstance(list, workers_allowed) num_workers = len(workers) assert num_workers >= shift.min_workers assert num_workers <= shift.max_workers for w in workers_allowed: assert w in workers shifts_workers = solution.shifts_workers # all shifts should be covered assert len(shifts_workers.keys()) == 3 assert shift1 in shifts_workers.keys() assert shift2 in shifts_workers.keys() assert shift3 in shifts_workers.keys() # shift_1 should be covered by 2 people - joe, and bob shift_check(shift_1, shifts_workers[shift_1], (joe, bob)) # shift_2 should be covered by 2 people - sam and amy shift_check(shift_2, shifts_workers[shift_2], (sam, amy)) # shift_3 should be covered by 3 people - ned, max, and jim shift_check(shift_3, shifts_workers[shift_3], (ned,max,jim)) Attempts I've tried implementing this with a Genetic Algorithm, but can't seem to get it tuned quite right, so although the basic principle seems to work on single shifts, it can't solve even easy cases with a few shifts and a few workers. My latest attempt is to generate every possible permutation as a solution, then whittle down the permutations that don't meet the constraints. This seems to work much more quickly, and has gotten me further, but I'm using python 2.6's itertools.product() to help generate the permutations, and I can't quite get it right. It wouldn't surprise me if there are many bugs as, honestly, the problem doesn't fit in my head that well :) Currently my code for this is in two files: models.py and rota.py. models.py looks like: # -*- coding: utf-8 -*- class Shift: def __init__(self, start_datetime, end_datetime, min_coverage, max_coverage): self.start = start_datetime self.end = end_datetime self.duration = self.end - self.start self.min_coverage = min_coverage self.max_coverage = max_coverage def __repr__(self): return "<Shift %s--%s (%r<x<%r)" % (self.start, self.end, self.min_coverage, self.max_coverage) class Duty: def __init__(self, worker, shift, slot): self.worker = worker self.shift = shift self.slot = slot def __repr__(self): return "<Duty worker=%r shift=%r slot=%d>" % (self.worker, self.shift, self.slot) def dump(self, indent=4, depth=1): ind = " " * (indent * depth) print ind + "<Duty shift=%s slot=%s" % (self.shift, self.slot) self.worker.dump(indent=indent, depth=depth+1) print ind + ">" class Avail: def __init__(self, start_time, end_time): self.start = start_time self.end = end_time def __repr__(self): return "<%s to %s>" % (self.start, self.end) class Worker: def __init__(self, name, availabilities): self.name = name self.availabilities = availabilities def __repr__(self): return "<Worker %s Avail=%r>" % (self.name, self.availabilities) def dump(self, indent=4, depth=1): ind = " " * (indent * depth) print ind + "<Worker %s" % self.name for avail in self.availabilities: print ind + " " * indent + repr(avail) print ind + ">" def available_for_shift(self, shift): for a in self.availabilities: if shift.start >= a.start and shift.end <= a.end: return True print "Worker %s not available for %r (Availability: %r)" % (self.name, shift, self.availabilities) return False class Solution: def __init__(self, shifts): self._shifts = list(shifts) def __repr__(self): return "<Solution: shifts=%r>" % self._shifts def duties(self): d = [] for s in self._shifts: for x in s: yield x def shifts(self): return list(set([ d.shift for d in self.duties() ])) def dump_shift(self, s, indent=4, depth=1): ind = " " * (indent * depth) print ind + "<ShiftList" for duty in s: duty.dump(indent=indent, depth=depth+1) print ind + ">" def dump(self, indent=4, depth=1): ind = " " * (indent * depth) print ind + "<Solution" for s in self._shifts: self.dump_shift(s, indent=indent, depth=depth+1) print ind + ">" class Env: def __init__(self, shifts, workers): self.shifts = shifts self.workers = workers self.fittest = None self.generation = 0 class DisplayContext: def __init__(self, env): self.env = env def status(self, msg, *args): raise NotImplementedError() def cleanup(self): pass def update(self): pass and rota.py looks like: #!/usr/bin/env python2.6 # -*- coding: utf-8 -*- from datetime import datetime as dt am2 = dt(2009, 10, 1, 2, 0) am8 = dt(2009, 10, 1, 8, 0) pm12 = dt(2009, 10, 1, 12, 0) def duties_for_all_workers(shifts, workers): from models import Duty duties = [] # for all shifts for shift in shifts: # for all slots for cov in range(shift.min_coverage, shift.max_coverage): for slot in range(cov): # for all workers for worker in workers: # generate a duty duty = Duty(worker, shift, slot+1) duties.append(duty) return duties def filter_duties_for_shift(duties, shift): matching_duties = [ d for d in duties if d.shift == shift ] for m in matching_duties: yield m def duty_permutations(shifts, duties): from itertools import product # build a list of shifts shift_perms = [] for shift in shifts: shift_duty_perms = [] for slot in range(shift.max_coverage): slot_duties = [ d for d in duties if d.shift == shift and d.slot == (slot+1) ] shift_duty_perms.append(slot_duties) shift_perms.append(shift_duty_perms) all_perms = ( shift_perms, shift_duty_perms ) # generate all possible duties for all shifts perms = list(product(*shift_perms)) return perms def solutions_for_duty_permutations(permutations): from models import Solution res = [] for duties in permutations: sol = Solution(duties) res.append(sol) return res def find_clashing_duties(duty, duties): """Find duties for the same worker that are too close together""" from datetime import timedelta one_day = timedelta(days=1) one_day_before = duty.shift.start - one_day one_day_after = duty.shift.end + one_day for d in [ ds for ds in duties if ds.worker == duty.worker ]: # skip the duty we're considering, as it can't clash with itself if duty == d: continue clashes = False # check if dates are too close to another shift if d.shift.start >= one_day_before and d.shift.start <= one_day_after: clashes = True # check if slots collide with another shift if d.slot == duty.slot: clashes = True if clashes: yield d def filter_unwanted_shifts(solutions): from models import Solution print "possibly unwanted:", solutions new_solutions = [] new_duties = [] for sol in solutions: for duty in sol.duties(): duty_ok = True if not duty.worker.available_for_shift(duty.shift): duty_ok = False if duty_ok: print "duty OK:" duty.dump(depth=1) new_duties.append(duty) else: print "duty **NOT** OK:" duty.dump(depth=1) shifts = set([ d.shift for d in new_duties ]) shift_lists = [] for s in shifts: shift_duties = [ d for d in new_duties if d.shift == s ] shift_lists.append(shift_duties) new_solutions.append(Solution(shift_lists)) return new_solutions def filter_clashing_duties(solutions): new_solutions = [] for sol in solutions: solution_ok = True for duty in sol.duties(): num_clashing_duties = len(set(find_clashing_duties(duty, sol.duties()))) # check if many duties collide with this one (and thus we should delete this one if num_clashing_duties > 0: solution_ok = False break if solution_ok: new_solutions.append(sol) return new_solutions def filter_incomplete_shifts(solutions): new_solutions = [] shift_duty_count = {} for sol in solutions: solution_ok = True for shift in set([ duty.shift for duty in sol.duties() ]): shift_duties = [ d for d in sol.duties() if d.shift == shift ] num_workers = len(set([ d.worker for d in shift_duties ])) if num_workers < shift.min_coverage: solution_ok = False if solution_ok: new_solutions.append(sol) return new_solutions def filter_solutions(solutions, workers): # filter permutations ############################ # for each solution solutions = filter_unwanted_shifts(solutions) solutions = filter_clashing_duties(solutions) solutions = filter_incomplete_shifts(solutions) return solutions def prioritise_solutions(solutions): # TODO: not implemented! return solutions # prioritise solutions ############################ # for all solutions # score according to number of staff on a duty # score according to male/female staff # score according to skill/background diversity # score according to when staff last on shift # sort all solutions by score def solve_duties(shifts, duties, workers): # ramify all possible duties ######################### perms = duty_permutations(shifts, duties) solutions = solutions_for_duty_permutations(perms) solutions = filter_solutions(solutions, workers) solutions = prioritise_solutions(solutions) return solutions def load_shifts(): from models import Shift shifts = [ Shift(am2, am8, 2, 3), Shift(am8, pm12, 2, 3), ] return shifts def load_workers(): from models import Avail, Worker joe_avail = ( Avail(am2, am8), ) sam_avail = ( Avail(am2, am8), ) ned_avail = ( Avail(am2, am8), ) bob_avail = ( Avail(am8, pm12), ) max_avail = ( Avail(am8, pm12), ) joe = Worker("joe", joe_avail) sam = Worker("sam", sam_avail) ned = Worker("ned", sam_avail) bob = Worker("bob", bob_avail) max = Worker("max", max_avail) return (joe, sam, ned, bob, max) def main(): import sys shifts = load_shifts() workers = load_workers() duties = duties_for_all_workers(shifts, workers) solutions = solve_duties(shifts, duties, workers) if len(solutions) == 0: print "Sorry, can't solve this. Perhaps you need more staff available, or" print "simpler duty constraints?" sys.exit(20) else: print "Solved. Solutions found:" for sol in solutions: sol.dump() if __name__ == "__main__": main() Snipping the debugging output before the result, this currently gives: Solved. Solutions found: <Solution <ShiftList <Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1 <Worker joe <2009-10-01 02:00:00 to 2009-10-01 08:00:00> > > <Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1 <Worker sam <2009-10-01 02:00:00 to 2009-10-01 08:00:00> > > <Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1 <Worker ned <2009-10-01 02:00:00 to 2009-10-01 08:00:00> > > > <ShiftList <Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1 <Worker bob <2009-10-01 08:00:00 to 2009-10-01 12:00:00> > > <Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1 <Worker max <2009-10-01 08:00:00 to 2009-10-01 12:00:00> > > > > A: I've tried implementing this with a Genetic Algorithm, but can't seem to get it tuned quite right, so although the basic principle seems to work on single shifts, it can't solve even easy cases with a few shifts and a few workers. In short, don't! Unless you have lots of experience with genetic algorithms, you won't get this right. They are approximate methods that do not guarantee converging to a workable solution. They work only if you can reasonably well establish the quality of your current solution (i.e. number of criteria not met). Their quality critically depends on the quality of operators you use to combine/mutate previous solutions into new ones. It is a tough thing to get right in small python program if you have close to zero experience with GA. If you have a small group of people exhaustive search is not that bad option. The problem is that it may work right for n people, will be slow for n+1 people and will be unbearably slow for n+2 and it may very well be that your n will end up as low as 10. You are working on an NP-complete problem and there are no easy win solutions. If the fancy timetable scheduling problem of your choice does not work good enough, it is very unlikely you will have something better with your python script. If you insist on doing this via your own code, it is much easier to get some results with min-max or simulated annealing. A: I don't have an algorithm choice but I can relate some practical considerations. Since the algorithm is dealing with cancellations, it has to run whenever a scheduling exception occurs to reschedule everyone. Consider that some algorithms are not very linear and might radically reschedule everyone from that point forward. You probably want to avoid that, people like to know their schedules well in advance. You can deal with some cancellations without rerunning the algorithm because it can pre-schedule the next available person or two. It might not be possible or desirable to always generate the most optimal solution, but you can keep a running count of "less-than-optimal" events per worker, and always choose the worker with the lowest count when you have to assign another "bad choice". That's what people generally care about (several "bad" scheduling decisions frequently/unfairly). A: Okay, I don't know about a particular algorithm, but here is what I would take into consideration. Evaluation Whatever the method you will need a function to evaluate how much your solution is satisfying the constraints. You may take the 'comparison' approach (no global score but a way to compare two solutions), but I would recommend evaluation. What would be real good is if you could obtain a score for a shorter timespan, for example daily, it is really helpful with algorithms if you can 'predict' the range of the final score from a partial solution (eg, just the first 3 days out of 7). This way you can interrupt the computation based on this partial solution if it's already too low to meet your expectations. Symmetry It is likely that among those 200 people you have similar profiles: ie people sharing the same characteristics (availability, experience, willingness, ...). If you take two persons with the same profile, they are going to be interchangeable: Solution 1: (shift 1: Joe)(shift 2: Jim) ...other workers only... Solution 2: (shift 1: Jim)(shift 2: Joe) ...other workers only... are actually the same solution from your point of view. The good thing is that usually, you have less profiles than persons, which helps tremendously with the time spent in computation! For example, imagine that you generated all the solutions based on Solution 1, then there is no need to compute anything based on Solution 2. Iterative Instead of generating the whole schedule at once, you may consider generating it incrementally (say 1 week at a time). The net gain is that the complexity for a week is reduced (there are less possibilities). Then, once you have this week, you compute the second one, being careful of taking the first into account the first for your constraints of course. The advantage is that you explicitly design you algorithm to take into account an already used solution, this way for the next schedule generation it will make sure not to make a person work 24hours straight! Serialization You should consider the serialization of your solution objects (pick up your choice, pickle is quite good for Python). You will need the previous schedule when generating a new one, and I bet you'd rather not enter it manually for the 200 people. Exhaustive Now, after all that, I would actually favor an exhaustive search since using symmetry and evaluation the possibilities might not be so numerous (the problem remains NP-complete though, there is no silver bullet). You may be willing to try your hand at the Backtracking Algorithm. Also, you should take a look at the following links which deal with similar kind of problems: Python Sudoku Solver Java Sudoku Solver using Knuth Dancing Links (uses the backtracking algorithm) Both discuss the problems encountered during the implementation, so checking them out should help you.
Worker/Timeslot permutation/constraint filtering algorithm
Hope you can help me out with this guys. It's not help with work -- it's for a charity of very hard working volunteers, who could really use a less confusing/annoying timetable system than what they currently have. If anyone knows of a good third-party app which (certainly) automate this, that would almost as good. Just... please don't suggest random timetabling stuff such as the ones for booking classrooms, as I don't think they can do this. Thanks in advance for reading; I know it's a big post. I'm trying to do my best to document this clearly though, and to show that I've made efforts on my own. Problem I need a worker/timeslot scheduling algorithm which generates shifts for workers, which meets the following criteria: Input Data import datetime.datetime as dt class DateRange: def __init__(self, start, end): self.start = start self.end = end class Shift: def __init__(self, range, min, max): self.range = range self.min_workers = min self.max_workers = max tue_9th_10pm = dt(2009, 1, 9, 22, 0) wed_10th_4am = dt(2009, 1, 10, 4, 0) wed_10th_10am = dt(2009, 1, 10, 10, 0) shift_1_times = Range(tue_9th_10pm, wed_10th_4am) shift_2_times = Range(wed_10th_4am, wed_10th_10am) shift_3_times = Range(wed_10th_10am, wed_10th_2pm) shift_1 = Shift(shift_1_times, 2,3) # allows 3, requires 2, but only 2 available shift_2 = Shift(shift_2_times, 2,2) # allows 2 shift_3 = Shift(shift_3_times, 2,3) # allows 3, requires 2, 3 available shifts = ( shift_1, shift_2, shift_3 ) joe_avail = [ shift_1, shift_2 ] bob_avail = [ shift_1, shift_3 ] sam_avail = [ shift_2 ] amy_avail = [ shift_2 ] ned_avail = [ shift_2, shift_3 ] max_avail = [ shift_3 ] jim_avail = [ shift_3 ] joe = Worker('joe', joe_avail) bob = Worker('bob', bob_avail) sam = Worker('sam', sam_avail) ned = Worker('ned', ned_avail) max = Worker('max', max_avail) amy = Worker('amy', amy_avail) jim = Worker('jim', jim_avail) workers = ( joe, bob, sam, ned, max, amy, jim ) Processing From above, shifts and workers are the two main input variables to process Each shift has a minimum and maximum number of workers needed. Filling the minimum requirements for a shift is crucial to success, but if all else fails, a rota with gaps to be filled manually is better than "error" :) The main algorithmic issue is that there shouldn't be unnecessary gaps, when enough workers are available. Ideally, the maximum number of workers for a shift would be filled, but this is the lowest priority relative to other constraints, so if anything has to give, it should be this. Flexible constraints These are a little flexible, and their boundaries can be pushed a little if a "perfect" solution can't be found. This flexibility should be a last resort though, rather than being exploited randomly. Ideally, the flexibility would be configurable with a "fudge_factor" variable, or similar. There is a minimum time period between two shifts. So, a worker shouldn't be scheduled for two shifts in the same day, for instance. There are a maximum number of shifts a worker can do in a given time period (say, a month) There are a maximum number of certain shifts that can be done in a month (say, overnight shifts) Nice to have, but not necessary If you can come up with an algorithm which does the above and includes any/all of these, I'll be seriously impressed and grateful. Even an add-on script to do these bits separately would be great too. Overlapping shifts. For instance, it would be good to be able to specify a "front desk" shift and a "back office" shift that both occur at the same time. This could be done with separate invocations of the program with different shift data, except that the constraints about scheduling people for multiple shifts in a given time period would be missed. Minimum reschedule time period for workers specifiable on a per-worker (rather than global) basis. For instance, if Joe is feeling overworked or is dealing with personal issues, or is a beginner learning the ropes, we might want to schedule him less often than other workers. Some automated/random/fair way of selecting staff to fill minimum shift numbers when no available workers fit. Some way of handling sudden cancellations, and just filling the gaps without rearranging other shifts. Output Test Probably, the algorithm should generate as many matching Solutions as possible, where each Solution looks like this: class Solution: def __init__(self, shifts_workers): """shifts_workers -- a dictionary of shift objects as keys, and a a lists of workers filling the shift as values.""" assert isinstance(dict, shifts_workers) self.shifts_workers = shifts_workers Here's a test function for an individual solution, given the above data. I think this is right, but I'd appreciate some peer review on it too. def check_solution(solution): assert isinstance(Solution, solution) def shift_check(shift, workers, workers_allowed): assert isinstance(Shift, shift): assert isinstance(list, workers): assert isinstance(list, workers_allowed) num_workers = len(workers) assert num_workers >= shift.min_workers assert num_workers <= shift.max_workers for w in workers_allowed: assert w in workers shifts_workers = solution.shifts_workers # all shifts should be covered assert len(shifts_workers.keys()) == 3 assert shift1 in shifts_workers.keys() assert shift2 in shifts_workers.keys() assert shift3 in shifts_workers.keys() # shift_1 should be covered by 2 people - joe, and bob shift_check(shift_1, shifts_workers[shift_1], (joe, bob)) # shift_2 should be covered by 2 people - sam and amy shift_check(shift_2, shifts_workers[shift_2], (sam, amy)) # shift_3 should be covered by 3 people - ned, max, and jim shift_check(shift_3, shifts_workers[shift_3], (ned,max,jim)) Attempts I've tried implementing this with a Genetic Algorithm, but can't seem to get it tuned quite right, so although the basic principle seems to work on single shifts, it can't solve even easy cases with a few shifts and a few workers. My latest attempt is to generate every possible permutation as a solution, then whittle down the permutations that don't meet the constraints. This seems to work much more quickly, and has gotten me further, but I'm using python 2.6's itertools.product() to help generate the permutations, and I can't quite get it right. It wouldn't surprise me if there are many bugs as, honestly, the problem doesn't fit in my head that well :) Currently my code for this is in two files: models.py and rota.py. models.py looks like: # -*- coding: utf-8 -*- class Shift: def __init__(self, start_datetime, end_datetime, min_coverage, max_coverage): self.start = start_datetime self.end = end_datetime self.duration = self.end - self.start self.min_coverage = min_coverage self.max_coverage = max_coverage def __repr__(self): return "<Shift %s--%s (%r<x<%r)" % (self.start, self.end, self.min_coverage, self.max_coverage) class Duty: def __init__(self, worker, shift, slot): self.worker = worker self.shift = shift self.slot = slot def __repr__(self): return "<Duty worker=%r shift=%r slot=%d>" % (self.worker, self.shift, self.slot) def dump(self, indent=4, depth=1): ind = " " * (indent * depth) print ind + "<Duty shift=%s slot=%s" % (self.shift, self.slot) self.worker.dump(indent=indent, depth=depth+1) print ind + ">" class Avail: def __init__(self, start_time, end_time): self.start = start_time self.end = end_time def __repr__(self): return "<%s to %s>" % (self.start, self.end) class Worker: def __init__(self, name, availabilities): self.name = name self.availabilities = availabilities def __repr__(self): return "<Worker %s Avail=%r>" % (self.name, self.availabilities) def dump(self, indent=4, depth=1): ind = " " * (indent * depth) print ind + "<Worker %s" % self.name for avail in self.availabilities: print ind + " " * indent + repr(avail) print ind + ">" def available_for_shift(self, shift): for a in self.availabilities: if shift.start >= a.start and shift.end <= a.end: return True print "Worker %s not available for %r (Availability: %r)" % (self.name, shift, self.availabilities) return False class Solution: def __init__(self, shifts): self._shifts = list(shifts) def __repr__(self): return "<Solution: shifts=%r>" % self._shifts def duties(self): d = [] for s in self._shifts: for x in s: yield x def shifts(self): return list(set([ d.shift for d in self.duties() ])) def dump_shift(self, s, indent=4, depth=1): ind = " " * (indent * depth) print ind + "<ShiftList" for duty in s: duty.dump(indent=indent, depth=depth+1) print ind + ">" def dump(self, indent=4, depth=1): ind = " " * (indent * depth) print ind + "<Solution" for s in self._shifts: self.dump_shift(s, indent=indent, depth=depth+1) print ind + ">" class Env: def __init__(self, shifts, workers): self.shifts = shifts self.workers = workers self.fittest = None self.generation = 0 class DisplayContext: def __init__(self, env): self.env = env def status(self, msg, *args): raise NotImplementedError() def cleanup(self): pass def update(self): pass and rota.py looks like: #!/usr/bin/env python2.6 # -*- coding: utf-8 -*- from datetime import datetime as dt am2 = dt(2009, 10, 1, 2, 0) am8 = dt(2009, 10, 1, 8, 0) pm12 = dt(2009, 10, 1, 12, 0) def duties_for_all_workers(shifts, workers): from models import Duty duties = [] # for all shifts for shift in shifts: # for all slots for cov in range(shift.min_coverage, shift.max_coverage): for slot in range(cov): # for all workers for worker in workers: # generate a duty duty = Duty(worker, shift, slot+1) duties.append(duty) return duties def filter_duties_for_shift(duties, shift): matching_duties = [ d for d in duties if d.shift == shift ] for m in matching_duties: yield m def duty_permutations(shifts, duties): from itertools import product # build a list of shifts shift_perms = [] for shift in shifts: shift_duty_perms = [] for slot in range(shift.max_coverage): slot_duties = [ d for d in duties if d.shift == shift and d.slot == (slot+1) ] shift_duty_perms.append(slot_duties) shift_perms.append(shift_duty_perms) all_perms = ( shift_perms, shift_duty_perms ) # generate all possible duties for all shifts perms = list(product(*shift_perms)) return perms def solutions_for_duty_permutations(permutations): from models import Solution res = [] for duties in permutations: sol = Solution(duties) res.append(sol) return res def find_clashing_duties(duty, duties): """Find duties for the same worker that are too close together""" from datetime import timedelta one_day = timedelta(days=1) one_day_before = duty.shift.start - one_day one_day_after = duty.shift.end + one_day for d in [ ds for ds in duties if ds.worker == duty.worker ]: # skip the duty we're considering, as it can't clash with itself if duty == d: continue clashes = False # check if dates are too close to another shift if d.shift.start >= one_day_before and d.shift.start <= one_day_after: clashes = True # check if slots collide with another shift if d.slot == duty.slot: clashes = True if clashes: yield d def filter_unwanted_shifts(solutions): from models import Solution print "possibly unwanted:", solutions new_solutions = [] new_duties = [] for sol in solutions: for duty in sol.duties(): duty_ok = True if not duty.worker.available_for_shift(duty.shift): duty_ok = False if duty_ok: print "duty OK:" duty.dump(depth=1) new_duties.append(duty) else: print "duty **NOT** OK:" duty.dump(depth=1) shifts = set([ d.shift for d in new_duties ]) shift_lists = [] for s in shifts: shift_duties = [ d for d in new_duties if d.shift == s ] shift_lists.append(shift_duties) new_solutions.append(Solution(shift_lists)) return new_solutions def filter_clashing_duties(solutions): new_solutions = [] for sol in solutions: solution_ok = True for duty in sol.duties(): num_clashing_duties = len(set(find_clashing_duties(duty, sol.duties()))) # check if many duties collide with this one (and thus we should delete this one if num_clashing_duties > 0: solution_ok = False break if solution_ok: new_solutions.append(sol) return new_solutions def filter_incomplete_shifts(solutions): new_solutions = [] shift_duty_count = {} for sol in solutions: solution_ok = True for shift in set([ duty.shift for duty in sol.duties() ]): shift_duties = [ d for d in sol.duties() if d.shift == shift ] num_workers = len(set([ d.worker for d in shift_duties ])) if num_workers < shift.min_coverage: solution_ok = False if solution_ok: new_solutions.append(sol) return new_solutions def filter_solutions(solutions, workers): # filter permutations ############################ # for each solution solutions = filter_unwanted_shifts(solutions) solutions = filter_clashing_duties(solutions) solutions = filter_incomplete_shifts(solutions) return solutions def prioritise_solutions(solutions): # TODO: not implemented! return solutions # prioritise solutions ############################ # for all solutions # score according to number of staff on a duty # score according to male/female staff # score according to skill/background diversity # score according to when staff last on shift # sort all solutions by score def solve_duties(shifts, duties, workers): # ramify all possible duties ######################### perms = duty_permutations(shifts, duties) solutions = solutions_for_duty_permutations(perms) solutions = filter_solutions(solutions, workers) solutions = prioritise_solutions(solutions) return solutions def load_shifts(): from models import Shift shifts = [ Shift(am2, am8, 2, 3), Shift(am8, pm12, 2, 3), ] return shifts def load_workers(): from models import Avail, Worker joe_avail = ( Avail(am2, am8), ) sam_avail = ( Avail(am2, am8), ) ned_avail = ( Avail(am2, am8), ) bob_avail = ( Avail(am8, pm12), ) max_avail = ( Avail(am8, pm12), ) joe = Worker("joe", joe_avail) sam = Worker("sam", sam_avail) ned = Worker("ned", sam_avail) bob = Worker("bob", bob_avail) max = Worker("max", max_avail) return (joe, sam, ned, bob, max) def main(): import sys shifts = load_shifts() workers = load_workers() duties = duties_for_all_workers(shifts, workers) solutions = solve_duties(shifts, duties, workers) if len(solutions) == 0: print "Sorry, can't solve this. Perhaps you need more staff available, or" print "simpler duty constraints?" sys.exit(20) else: print "Solved. Solutions found:" for sol in solutions: sol.dump() if __name__ == "__main__": main() Snipping the debugging output before the result, this currently gives: Solved. Solutions found: <Solution <ShiftList <Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1 <Worker joe <2009-10-01 02:00:00 to 2009-10-01 08:00:00> > > <Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1 <Worker sam <2009-10-01 02:00:00 to 2009-10-01 08:00:00> > > <Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1 <Worker ned <2009-10-01 02:00:00 to 2009-10-01 08:00:00> > > > <ShiftList <Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1 <Worker bob <2009-10-01 08:00:00 to 2009-10-01 12:00:00> > > <Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1 <Worker max <2009-10-01 08:00:00 to 2009-10-01 12:00:00> > > > >
[ "\nI've tried implementing this with a Genetic Algorithm, \n but can't seem to get it tuned quite right, so although \n the basic principle seems to work on single shifts, \n it can't solve even easy cases with a few shifts and a few workers.\n\nIn short, don't! Unless you have lots of experience with genetic algorithms, you won't get this right.\n\nThey are approximate methods that do not guarantee converging to a workable solution. \nThey work only if you can reasonably well establish the quality of your current solution (i.e. number of criteria not met). \nTheir quality critically depends on the quality of operators you use to combine/mutate previous solutions into new ones.\n\nIt is a tough thing to get right in small python program if you have close to zero experience with GA. If you have a small group of people exhaustive search is not that bad option. The problem is that it may work right for n people, will be slow for n+1 people and will be unbearably slow for n+2 and it may very well be that your n will end up as low as 10.\nYou are working on an NP-complete problem and there are no easy win solutions. If the fancy timetable scheduling problem of your choice does not work good enough, it is very unlikely you will have something better with your python script.\nIf you insist on doing this via your own code, it is much easier to get some results with min-max or simulated annealing.\n", "I don't have an algorithm choice but I can relate some practical considerations.\nSince the algorithm is dealing with cancellations, it has to run whenever a scheduling exception occurs to reschedule everyone. \nConsider that some algorithms are not very linear and might radically reschedule everyone from that point forward. You probably want to avoid that, people like to know their schedules well in advance.\nYou can deal with some cancellations without rerunning the algorithm because it can pre-schedule the next available person or two. \nIt might not be possible or desirable to always generate the most optimal solution, but you can keep a running count of \"less-than-optimal\" events per worker, and always choose the worker with the lowest count when you have to assign another \"bad choice\". That's what people generally care about (several \"bad\" scheduling decisions frequently/unfairly).\n", "Okay, I don't know about a particular algorithm, but here is what I would take into consideration.\nEvaluation \nWhatever the method you will need a function to evaluate how much your solution is satisfying the constraints. You may take the 'comparison' approach (no global score but a way to compare two solutions), but I would recommend evaluation.\nWhat would be real good is if you could obtain a score for a shorter timespan, for example daily, it is really helpful with algorithms if you can 'predict' the range of the final score from a partial solution (eg, just the first 3 days out of 7). This way you can interrupt the computation based on this partial solution if it's already too low to meet your expectations.\nSymmetry\nIt is likely that among those 200 people you have similar profiles: ie people sharing the same characteristics (availability, experience, willingness, ...). If you take two persons with the same profile, they are going to be interchangeable:\n\nSolution 1: (shift 1: Joe)(shift 2: Jim) ...other workers only...\nSolution 2: (shift 1: Jim)(shift 2: Joe) ...other workers only...\n\nare actually the same solution from your point of view.\nThe good thing is that usually, you have less profiles than persons, which helps tremendously with the time spent in computation!\nFor example, imagine that you generated all the solutions based on Solution 1, then there is no need to compute anything based on Solution 2.\nIterative\nInstead of generating the whole schedule at once, you may consider generating it incrementally (say 1 week at a time). The net gain is that the complexity for a week is reduced (there are less possibilities).\nThen, once you have this week, you compute the second one, being careful of taking the first into account the first for your constraints of course.\nThe advantage is that you explicitly design you algorithm to take into account an already used solution, this way for the next schedule generation it will make sure not to make a person work 24hours straight!\nSerialization\nYou should consider the serialization of your solution objects (pick up your choice, pickle is quite good for Python). You will need the previous schedule when generating a new one, and I bet you'd rather not enter it manually for the 200 people.\nExhaustive\nNow, after all that, I would actually favor an exhaustive search since using symmetry and evaluation the possibilities might not be so numerous (the problem remains NP-complete though, there is no silver bullet).\nYou may be willing to try your hand at the Backtracking Algorithm.\nAlso, you should take a look at the following links which deal with similar kind of problems:\n\nPython Sudoku Solver\nJava Sudoku Solver using Knuth Dancing Links (uses the backtracking algorithm)\n\nBoth discuss the problems encountered during the implementation, so checking them out should help you.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "permutation", "python", "scheduling", "timeslots", "timetable" ]
stackoverflow_0001554366_permutation_python_scheduling_timeslots_timetable.txt
Q: webbrowser.get("firefox") on a Mac with Firefox "could not locate runnable browser" I think what I need here is to know which magic command-line or OSA script program to run to start up a URL in an existing Firefox browser, if one is running, or to also start up Firefox if it isn't. On Mac. I'm testing a Python program (Crunchy Python) which sets up a web server then uses Firefox for the front end. It starts the web application with the following: try: client = webbrowser.get("firefox") client.open(url) return except: try: client = webbrowser.get() client.open(url) return except: print('Please open %s in Firefox.' % url) I have Safari on my Mac as the default, but I also have Firefox installed and running. The above code started the new URL (on localhost) in Safari. Crunchy does not work well in Safari. I want to see it in Firefox, since I do have Firefox. Under Python 2.5, 2.6, and 2.7 (from version control) I get this: >>> import webbrowser >>> webbrowser.get("firefox") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/webbrowser.py", line 46, in get raise Error("could not locate runnable browser") webbrowser.Error: could not locate runnable browser Firefox is there. I tried using webbrowser.get("/Applications/Firefox.app/Contents/MacOS/firefox %s") which starts up a new instance of Firefox then complains that another instance of Firefox is already running. I really would like webbrowser to open up the URL in an existing tab/window of Firefox, if it's already running, or in a new Firefox is not already running. I looked at webbrowser.py and it looks like there is no 'firefox' support for MacOSX. That's okay, I can add that. But I don't know how to open the URL in Firefox in the way I want to. Ideas? And for now, I can force Crunchy to give me the URL, which I can manually paste into Firefox. A: Apple uses launch services to find applications. An application can be used by the open command - Apple developer man page for open The python command you want is client = webbrowser.get("open -a /Applications/Firefox.app %s") Following Nicholas Riley 's comment If Firefox is on the list of Applications then you can get away with open -a Firefox.app %s A: You should use Launch Services to open the URL. You can do this with the LaunchServices module, or with Apple's open utility, or with my launch utility (here): open is probably easiest: % open -b org.mozilla.firefox http://www.stackoverflow.com/ (or, of course, the equivalent in Python with subprocess or similar) should do what you want.
webbrowser.get("firefox") on a Mac with Firefox "could not locate runnable browser"
I think what I need here is to know which magic command-line or OSA script program to run to start up a URL in an existing Firefox browser, if one is running, or to also start up Firefox if it isn't. On Mac. I'm testing a Python program (Crunchy Python) which sets up a web server then uses Firefox for the front end. It starts the web application with the following: try: client = webbrowser.get("firefox") client.open(url) return except: try: client = webbrowser.get() client.open(url) return except: print('Please open %s in Firefox.' % url) I have Safari on my Mac as the default, but I also have Firefox installed and running. The above code started the new URL (on localhost) in Safari. Crunchy does not work well in Safari. I want to see it in Firefox, since I do have Firefox. Under Python 2.5, 2.6, and 2.7 (from version control) I get this: >>> import webbrowser >>> webbrowser.get("firefox") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/webbrowser.py", line 46, in get raise Error("could not locate runnable browser") webbrowser.Error: could not locate runnable browser Firefox is there. I tried using webbrowser.get("/Applications/Firefox.app/Contents/MacOS/firefox %s") which starts up a new instance of Firefox then complains that another instance of Firefox is already running. I really would like webbrowser to open up the URL in an existing tab/window of Firefox, if it's already running, or in a new Firefox is not already running. I looked at webbrowser.py and it looks like there is no 'firefox' support for MacOSX. That's okay, I can add that. But I don't know how to open the URL in Firefox in the way I want to. Ideas? And for now, I can force Crunchy to give me the URL, which I can manually paste into Firefox.
[ "Apple uses launch services to find applications. An application can be used by the open command - Apple developer man page for open\nThe python command you want is\nclient = webbrowser.get(\"open -a /Applications/Firefox.app %s\")\n\nFollowing Nicholas Riley 's comment\nIf Firefox is on the list of Applications then you can get away with open -a Firefox.app %s\n", "You should use Launch Services to open the URL. You can do this with the LaunchServices module, or with Apple's open utility, or with my launch utility (here):\nopen is probably easiest:\n% open -b org.mozilla.firefox http://www.stackoverflow.com/\n\n(or, of course, the equivalent in Python with subprocess or similar) should do what you want.\n" ]
[ 3, 3 ]
[]
[]
[ "browser", "firefox", "macos", "python" ]
stackoverflow_0001555283_browser_firefox_macos_python.txt
Q: In Django, How Do I Move Images When A Dynamic Path Changes? I have a Django app with an image field (a custom ThumbnailImageField type) that auto-generates the file path for an image based on the title, type, and country of the item the image is attached to (upload_ to = get_ image_path). Here's how: def get_image_path(instance, filename): dir = 'images' subdir = instance.get_type_display() sub_subdir = 'other' if instance.country: sub_subdir = instance.country.name name = instance.name extension = filename.split('.')[-1] return "%s/%s/%s/%s.%s" % (dir, subdir, sub_subdir, name, extension) It works great, except in one situation: When I rename an item, change the country it's from, or change the category it's in, the image becomes a dead link because it generates a new image path without moving the orignal file. So, the magic question: Is there some save function in Django that I can hook into and override that will let me have the original object and the proposed values and compare them so I know where the image path was and where it will need to go (and then use this info to move/rename in code)? A: You probably want to look into signals: http://docs.djangoproject.com/en/dev/topics/signals/ In particular, the django.db.models.signals.pre_save signal: http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#pre_save
In Django, How Do I Move Images When A Dynamic Path Changes?
I have a Django app with an image field (a custom ThumbnailImageField type) that auto-generates the file path for an image based on the title, type, and country of the item the image is attached to (upload_ to = get_ image_path). Here's how: def get_image_path(instance, filename): dir = 'images' subdir = instance.get_type_display() sub_subdir = 'other' if instance.country: sub_subdir = instance.country.name name = instance.name extension = filename.split('.')[-1] return "%s/%s/%s/%s.%s" % (dir, subdir, sub_subdir, name, extension) It works great, except in one situation: When I rename an item, change the country it's from, or change the category it's in, the image becomes a dead link because it generates a new image path without moving the orignal file. So, the magic question: Is there some save function in Django that I can hook into and override that will let me have the original object and the proposed values and compare them so I know where the image path was and where it will need to go (and then use this info to move/rename in code)?
[ "You probably want to look into signals:\nhttp://docs.djangoproject.com/en/dev/topics/signals/\nIn particular, the django.db.models.signals.pre_save signal:\nhttp://docs.djangoproject.com/en/dev/howto/custom-model-fields/#pre_save\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001556040_django_django_models_python.txt
Q: How to dereference a memory location from python ctypes? I want to replicate the following c code in python ctypes: main() { long *ptr = (long *)0x7fff96000000; printf("%lx",*ptr); } I can figure out how to call this memory location as a function pointer but not just do a normal dereference: from ctypes import * """ >>> fptr = CFUNCTYPE(None, None) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/ctypes/__init__.py", line 104, in CFUNCTYPE class CFunctionType(_CFuncPtr): TypeError: Error when calling the metaclass bases item 1 in _argtypes_ has no from_param method """ fptr = CFUNCTYPE(None, c_void_p) #add c_void_p since you have to have an arg fptr2 = fptr(0x7fff96000000) fptr2(c_void_p(0)) #python: segfault at 7fff96000000 ip 00007fff96000000 Since there it is a segfault with the instruction pointer pointing to this memory location it is successfully calling it. However I can't get it to just read the memory location: ptr = POINTER(c_long) ptr2 = ptr(c_long(0x7fff96000000)) #>>> ptr2[0] #140735709970432 #>>> hex(ptr2[0]) #'0x7fff96000000' #>>> ptr2.contents #c_long(140735709970432) A: ctypes.cast. >>> import ctypes >>> c_long_p = ctypes.POINTER(ctypes.c_long) >>> some_long = ctypes.c_long(42) >>> ctypes.addressof(some_long) 4300833936 >>> ctypes.cast(4300833936, c_long_p) <__main__.LP_c_long object at 0x1005983b0> >>> ctypes.cast(4300833936, c_long_p).contents c_long(42)
How to dereference a memory location from python ctypes?
I want to replicate the following c code in python ctypes: main() { long *ptr = (long *)0x7fff96000000; printf("%lx",*ptr); } I can figure out how to call this memory location as a function pointer but not just do a normal dereference: from ctypes import * """ >>> fptr = CFUNCTYPE(None, None) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/ctypes/__init__.py", line 104, in CFUNCTYPE class CFunctionType(_CFuncPtr): TypeError: Error when calling the metaclass bases item 1 in _argtypes_ has no from_param method """ fptr = CFUNCTYPE(None, c_void_p) #add c_void_p since you have to have an arg fptr2 = fptr(0x7fff96000000) fptr2(c_void_p(0)) #python: segfault at 7fff96000000 ip 00007fff96000000 Since there it is a segfault with the instruction pointer pointing to this memory location it is successfully calling it. However I can't get it to just read the memory location: ptr = POINTER(c_long) ptr2 = ptr(c_long(0x7fff96000000)) #>>> ptr2[0] #140735709970432 #>>> hex(ptr2[0]) #'0x7fff96000000' #>>> ptr2.contents #c_long(140735709970432)
[ "ctypes.cast.\n>>> import ctypes\n>>> c_long_p = ctypes.POINTER(ctypes.c_long)\n>>> some_long = ctypes.c_long(42)\n>>> ctypes.addressof(some_long)\n4300833936\n>>> ctypes.cast(4300833936, c_long_p)\n<__main__.LP_c_long object at 0x1005983b0>\n>>> ctypes.cast(4300833936, c_long_p).contents\nc_long(42)\n\n" ]
[ 32 ]
[]
[]
[ "ctypes", "ffi", "python" ]
stackoverflow_0001555944_ctypes_ffi_python.txt
Q: Python "Task Server" My question is: which python framework should I use to build my server? Notes: This server talks HTTP with it's clients: GET and POST (via pyAMF) Clients "submit" "tasks" for processing and, then, sometime later, retrieve the associated "task_result" submit and retrieve might be separated by days - different HTTP connections The "task" is a lump of XML describing a problem to be solved, and a "task_result" is a lump of XML describing an answer. When a server gets a "task", it queues it for processing The server manages this queue and, when tasks get to the top, organises that they are processed. the processing is performed by a long running (15 mins?) external program (via subprocess) which is feed the task XML and which produces a "task_result" lump of XML which the server picks up and stores (for later Client retrieval). it serves a couple of basic HTML pages showing the Queue and processing status (admin purposes only) I've experimented with twisted.web, using SQLite as the database and threads to handle the long running processes. But I can't help feeling that I'm missing a simpler solution. Am I? If you were faced with this, what technology mix would you use? A: I'd recommend using an existing message queue. There are many to choose from (see below), and they vary in complexity and robustness. Also, avoid threads: let your processing tasks run in a different process (why do they have to run in the webserver?) By using an existing message queue, you only need to worry about producing messages (in your webserver) and consuming them (in your long running tasks). As your system grows you'll be able to scale up by just adding webservers and consumers, and worry less about your queuing infrastructure. Some popular python implementations of message queues: http://code.google.com/p/stomper/ http://code.google.com/p/pyactivemq/ http://xph.us/software/beanstalkd/ A: I'd suggest the following. (Since it's what we're doing.) A simple WSGI server (wsgiref or werkzeug). The HTTP requests coming in will naturally form a queue. No further queueing needed. You get a request, you spawn the subprocess as a child and wait for it to finish. A simple list of children is about all you need. I used a modification of the main "serve forever" loop in wsgiref to periodically poll all of the children to see how they're doing. A simple SQLite database can track request status. Even this may be overkill because your XML inputs and results can just lay around in the file system. That's it. Queueing and threads don't really enter into it. A single long-running external process is too complex to coordinate. It's simplest if each request is a separate, stand-alone, child process. If you get immense bursts of requests, you might want a simple governor to prevent creating thousands of children. The governor could be a simple queue, built using a list with append() and pop(). Every request goes in, but only requests that fit will in some "max number of children" limit are taken out. A: My reaction is to suggest Twisted, but you've already looked at this. Still, I stick by my answer. Without knowing you personal pain-points, I can at least share some things that helped me reduce almost all of the deferred-madness that arises when you have several dependent, blocking actions you need to perform for a client. Inline callbacks (lightly documented here: http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.defer.html) provide a means to make long chains of deferreds much more readable (to the point of looking like straight-line code). There is an excellent example of the complexity reduction this affords here: http://blog.mekk.waw.pl/archives/14-Twisted-inlineCallbacks-and-deferredGenerator.html You don't always have to get your bulk processing to integrate nicely with Twisted. Sometimes it is easier to break a large piece of your program off into a stand-alone, easily testable/tweakable/implementable command line tool and have Twisted invoke this tool in another process. Twisted's ProcessProtocol provides a fairly flexible way of launching and interacting with external helper programs. Furthermore, if you suddenly decide you want to cloudify your application, it is not all that big of a deal to use a ProcessProtocol to simply run your bulk processing on a remote server (random EC2 instances perhaps) via ssh, assuming you have the keys setup already. A: You can have a look at celery A: It seems any python web framework will suit your needs. I work with a similar system on a daily basis and I can tell you, your solution with threads and SQLite for queue storage is about as simple as you're going to get. Assuming order doesn't matter in your queue, then threads should be acceptable. It's important to make sure you don't create race conditions with your queues or, for example, have two of the same job type running simultaneously. If this is the case, I'd suggest a single threaded application to do the items in the queue one by one.
Python "Task Server"
My question is: which python framework should I use to build my server? Notes: This server talks HTTP with it's clients: GET and POST (via pyAMF) Clients "submit" "tasks" for processing and, then, sometime later, retrieve the associated "task_result" submit and retrieve might be separated by days - different HTTP connections The "task" is a lump of XML describing a problem to be solved, and a "task_result" is a lump of XML describing an answer. When a server gets a "task", it queues it for processing The server manages this queue and, when tasks get to the top, organises that they are processed. the processing is performed by a long running (15 mins?) external program (via subprocess) which is feed the task XML and which produces a "task_result" lump of XML which the server picks up and stores (for later Client retrieval). it serves a couple of basic HTML pages showing the Queue and processing status (admin purposes only) I've experimented with twisted.web, using SQLite as the database and threads to handle the long running processes. But I can't help feeling that I'm missing a simpler solution. Am I? If you were faced with this, what technology mix would you use?
[ "I'd recommend using an existing message queue. There are many to choose from (see below), and they vary in complexity and robustness. \nAlso, avoid threads: let your processing tasks run in a different process (why do they have to run in the webserver?)\nBy using an existing message queue, you only need to worry about producing messages (in your webserver) and consuming them (in your long running tasks). As your system grows you'll be able to scale up by just adding webservers and consumers, and worry less about your queuing infrastructure.\nSome popular python implementations of message queues:\n\nhttp://code.google.com/p/stomper/\nhttp://code.google.com/p/pyactivemq/\nhttp://xph.us/software/beanstalkd/\n\n", "I'd suggest the following. (Since it's what we're doing.)\nA simple WSGI server (wsgiref or werkzeug). The HTTP requests coming in will naturally form a queue. No further queueing needed. You get a request, you spawn the subprocess as a child and wait for it to finish. A simple list of children is about all you need. \nI used a modification of the main \"serve forever\" loop in wsgiref to periodically poll all of the children to see how they're doing. \nA simple SQLite database can track request status. Even this may be overkill because your XML inputs and results can just lay around in the file system.\nThat's it. Queueing and threads don't really enter into it. A single long-running external process is too complex to coordinate. It's simplest if each request is a separate, stand-alone, child process. \nIf you get immense bursts of requests, you might want a simple governor to prevent creating thousands of children. The governor could be a simple queue, built using a list with append() and pop(). Every request goes in, but only requests that fit will in some \"max number of children\" limit are taken out.\n", "My reaction is to suggest Twisted, but you've already looked at this. Still, I stick by my answer. Without knowing you personal pain-points, I can at least share some things that helped me reduce almost all of the deferred-madness that arises when you have several dependent, blocking actions you need to perform for a client.\nInline callbacks (lightly documented here: http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.defer.html) provide a means to make long chains of deferreds much more readable (to the point of looking like straight-line code). There is an excellent example of the complexity reduction this affords here: http://blog.mekk.waw.pl/archives/14-Twisted-inlineCallbacks-and-deferredGenerator.html\nYou don't always have to get your bulk processing to integrate nicely with Twisted. Sometimes it is easier to break a large piece of your program off into a stand-alone, easily testable/tweakable/implementable command line tool and have Twisted invoke this tool in another process. Twisted's ProcessProtocol provides a fairly flexible way of launching and interacting with external helper programs. Furthermore, if you suddenly decide you want to cloudify your application, it is not all that big of a deal to use a ProcessProtocol to simply run your bulk processing on a remote server (random EC2 instances perhaps) via ssh, assuming you have the keys setup already.\n", "You can have a look at celery\n", "It seems any python web framework will suit your needs. I work with a similar system on a daily basis and I can tell you, your solution with threads and SQLite for queue storage is about as simple as you're going to get. \nAssuming order doesn't matter in your queue, then threads should be acceptable. It's important to make sure you don't create race conditions with your queues or, for example, have two of the same job type running simultaneously. If this is the case, I'd suggest a single threaded application to do the items in the queue one by one.\n" ]
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000805120_python.txt
Q: Should you import all classes you use in Python? Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter? Example someclass.py class SomeClass: def __init__(self, some_value): self.some_value = some_value someclient.py class SomeClient: def __init__(self, some_class_instance): self.some_class_helper = some_class_instance Here, the functionality of SomeClient clearly relies on SomeClass or at least something that behaves like it. However, someclient.py will work just fine without import someclass. Is this ok? It feels wrong to use something without saying anywhere that you're even using it. A: Yes, it's completely ok. some_class_instance might be anything, it doesn't have to be an instance of SomeClass. You might want to pass an instance that looks just like SomeClass, but uses a different implementation for testing purposes, for example. A: Importing SomeClass won't make any difference to how that code works. If you're worried about making the code understandable, comment the fact that SomeClient expects a SomeClass instance, and/or document it in the docstring. If you want to police the fact that SomeClient requires a SomeClass instance, you can assert it: class SomeClient: def __init__(self, some_class_instance): assert isinstance(some_class_instance, SomeClass) self.some_class_helper = some_class_instance which will require importing SomeClass. But note that you're being rather restrictive there - it precludes using a Mock SomeClass for testing purposes, for example. (There's a lengthy rant about this here: "isinstance() considered harmful".) A: In this case, you shouldn't import the class. Python relies on what is called "duck typing" - if it walks like a duck and quacks like a duck, it might as well be a duck. Your code doesn't care what class really gets passed in when the program runs. All it cares is that it acts just like "SomeClass" acts. duck-typing A pythonic programming style which determines an object’s type by inspection of its method or attribute signature rather than by explicit relationship to some type object (“If it looks like a duck and quacks like a duck, it must be a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). (Note, however, that duck-typing can be complemented with abstract base classes.) Instead, it typically employs hasattr() tests or EAFP programming. A: This is a good python code, "we are all consenting adults here", maybe if you expect a class you should include a comment and that's ok.
Should you import all classes you use in Python?
Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter? Example someclass.py class SomeClass: def __init__(self, some_value): self.some_value = some_value someclient.py class SomeClient: def __init__(self, some_class_instance): self.some_class_helper = some_class_instance Here, the functionality of SomeClient clearly relies on SomeClass or at least something that behaves like it. However, someclient.py will work just fine without import someclass. Is this ok? It feels wrong to use something without saying anywhere that you're even using it.
[ "Yes, it's completely ok. some_class_instance might be anything, it doesn't have to be an instance of SomeClass. You might want to pass an instance that looks just like SomeClass, but uses a different implementation for testing purposes, for example.\n", "Importing SomeClass won't make any difference to how that code works.\nIf you're worried about making the code understandable, comment the fact that SomeClient expects a SomeClass instance, and/or document it in the docstring.\nIf you want to police the fact that SomeClient requires a SomeClass instance, you can assert it:\nclass SomeClient:\n def __init__(self, some_class_instance):\n assert isinstance(some_class_instance, SomeClass)\n self.some_class_helper = some_class_instance\n\nwhich will require importing SomeClass. But note that you're being rather restrictive there - it precludes using a Mock SomeClass for testing purposes, for example. (There's a lengthy rant about this here: \"isinstance() considered harmful\".)\n", "In this case, you shouldn't import the class.\nPython relies on what is called \"duck typing\" - if it walks like a duck and quacks like a duck, it might as well be a duck.\nYour code doesn't care what class really gets passed in when the program runs. All it cares is that it acts just like \"SomeClass\" acts.\nduck-typing\n\nA pythonic programming style which determines an object’s type by\n inspection of its method or attribute\n signature rather than by explicit\n relationship to some type object (“If\n it looks like a duck and quacks like a\n duck, it must be a duck.”) By\n emphasizing interfaces rather than\n specific types, well-designed code\n improves its flexibility by allowing\n polymorphic substitution. Duck-typing\n avoids tests using type() or\n isinstance(). (Note, however, that\n duck-typing can be complemented with\n abstract base classes.) Instead, it\n typically employs hasattr() tests or\n EAFP programming.\n\n", "This is a good python code, \"we are all consenting adults here\", maybe if you expect a class you should include a comment and that's ok.\n" ]
[ 9, 6, 4, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0001556766_coding_style_python.txt
Q: Executing a MySQL query on command line via os.system in Python I am trying to pass the 'day' from the while loop into a sql statement that then gets passed into a MySQL command line to be executed with -e I can not use the DB module or other python libraries to access MySQL, it needs to be done via command line. It also looks like I might need to convert the day to a string before concatenating to sql? #!/usr/bin/python import datetime a = datetime.date(2009, 1, 1) b = datetime.date(2009, 7, 1) one_day = datetime.timedelta(1) day = a while day <= b: print day sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date" print "SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date" os.system('mysql -h -sN -u -p -e " + sql + " > /home/output/DateLoop-" + day + ".txt db') day += one_day Would it be possible to set this up to have the SQL as an input file and pass the day as a string to that? The query might become more complex or even require several queries and that might become a problem trying to pass as a string. I am open to any ideas as long as the query can take the date as input, name the output file with the same date and do it from the command line MySQL client A: Code below might help you out. It isn't particularly exciting and is deliberately simple. This is not the way many programmers would tackle this problem, but without more info it seems to fulfil your requirements. I have also made an assumption that you are new to python; If I'm wrong, feel free to ignore this post. Allows the passing of database credentials, output directory and dates (start and end) on the command line. Uses subprocess in place of os.system. Subprocess provides the preferred mechanisms to call external executables from python. This code uses the simplest of them; call() as it is similar to os.system() Uses optparse to process the command line arguments. Whilst the code is certainly longer and more verbose, it will be easier for you to make additions and modifications to the arg processing in the future. It is also pretty clear what is going on (and code is always read far more often than it is written). The command line setup only runs when the script is executed as it is within the __main__ block. As the "logic" of the script is within the main() method, you can also import it and provide the options object (and arg list) from another source. If you can remove the need to output each date in a separate file, you can have the database engine calculate the SUM() and group them by date. You would get all sums back in one db call which would be quicker and could yield simpler code. #!/usr/bin/python # -*- coding: utf-8 -*- import datetime import os import subprocess from optparse import OptionParser SQL = """SELECT d.Date, SUM(d.CostUsd) FROM Stats d WHERE d.Date = '%s' GROUP BY d.Date""" def get_stats(options, dateobj): """Return statistics for the date of `dateobj`""" _datestr = dateobj.strftime('%Y-%m-%d') sql = SQL % _datestr filepath = os.path.join(options.outdir, 'DateLoop-%s.txt' % _datestr) return subprocess.call('mysql -h %s -u %s -p -sN -e "%s" db > %s' % (options.dbhost, options.dbuser, sql, filepath), shell=True) def main(options, args): """""" _date = options.startdate while _date <= options.enddate: rs = get_stats(options, _date) _date += datetime.timedelta(days=1) if __name__ == '__main__': parser = OptionParser(version="%prog 1.0") parser.add_option('-s', '--startdate', type='string', dest='startdate', help='the start date (format: yyyymmdd)') parser.add_option('-e', '--enddate', type='string', dest='enddate', help='the end date (format: yyyymmdd)') parser.add_option('--output', type='string', dest='outdir', default='/home/output/', help='target directory for output files') parser.add_option('--dbhost', type='string', dest='dbhost', default='myhost', help='SQL server address') parser.add_option('--dbuser', type='string', dest='dbuser', default='dbuser', help='SQL server user') options, args = parser.parse_args() ## Process the date args if not options.startdate: options.startdate = datetime.datetime.today() else: try: options.startdate = datetime.datetime.strptime('%Y%m%d', options.startdate) except ValueError: parser.error("Invalid value for startdate (%s)" % options.startdate) if not options.enddate: options.enddate = options.startdate + datetime.timedelta(days=7) else: try: options.enddate = datetime.datetime.strptime('%Y%m%d', options.enddate) except ValueError: parser.error("Invalid value for enddate (%s)" % options.enddate) main(options, args) A: Try explicit formatting and quoting resulting string: sql = "....WHERE d.Date = '" + date.isoformat() + "' GROUP BY ..." Quotes at os.system call are messy and redirection look weird (if it's not a typo) os.system("mysql db -h -sN -u -p -e '" + sql + "' > /home/output/DateLoop-" + day + ".txt") A: Well, you can save the mysql template query in a config file and parse it with ConfigParser: The config file will look like that: [mysql query configuration] dbhost = db = username = guest password = [query template] template = SELECT Date, SUM(CostUsd)....... or you can just store it to a separate file and then read it with the standard open(filename).read, etc. If you think that the query will become more complex in the future, the config file approach may be simpler to manage and understand, but it is not a big difference. To get the date as a parameter, you can use sys.argv, or a library like optparse
Executing a MySQL query on command line via os.system in Python
I am trying to pass the 'day' from the while loop into a sql statement that then gets passed into a MySQL command line to be executed with -e I can not use the DB module or other python libraries to access MySQL, it needs to be done via command line. It also looks like I might need to convert the day to a string before concatenating to sql? #!/usr/bin/python import datetime a = datetime.date(2009, 1, 1) b = datetime.date(2009, 7, 1) one_day = datetime.timedelta(1) day = a while day <= b: print day sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date" print "SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date" os.system('mysql -h -sN -u -p -e " + sql + " > /home/output/DateLoop-" + day + ".txt db') day += one_day Would it be possible to set this up to have the SQL as an input file and pass the day as a string to that? The query might become more complex or even require several queries and that might become a problem trying to pass as a string. I am open to any ideas as long as the query can take the date as input, name the output file with the same date and do it from the command line MySQL client
[ "Code below might help you out. It isn't particularly exciting and is deliberately simple. This is not the way many programmers would tackle this problem, but without more info it seems to fulfil your requirements.\nI have also made an assumption that you are new to python; If I'm wrong, feel free to ignore this post.\n\nAllows the passing of database credentials, output directory and dates (start and end) on the command line.\nUses subprocess in place of os.system. Subprocess provides the preferred mechanisms to call external executables from python. This code uses the simplest of them; call() as it is similar to os.system()\nUses optparse to process the command line arguments. Whilst the code is certainly longer and more verbose, it will be easier for you to make additions and modifications to the arg processing in the future. It is also pretty clear what is going on (and code is always read far more often than it is written).\nThe command line setup only runs when the script is executed as it is within the __main__ block. As the \"logic\" of the script is within the main() method, you can also import it and provide the options object (and arg list) from another source.\n\nIf you can remove the need to output each date in a separate file, you can have the database engine calculate the SUM() and group them by date. You would get all sums back in one db call which would be quicker and could yield simpler code.\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport datetime\nimport os\nimport subprocess\nfrom optparse import OptionParser\n\nSQL = \"\"\"SELECT d.Date, SUM(d.CostUsd) FROM Stats d WHERE d.Date = '%s' GROUP BY d.Date\"\"\"\n\n\ndef get_stats(options, dateobj):\n \"\"\"Return statistics for the date of `dateobj`\"\"\"\n _datestr = dateobj.strftime('%Y-%m-%d')\n sql = SQL % _datestr\n filepath = os.path.join(options.outdir, 'DateLoop-%s.txt' % _datestr)\n return subprocess.call('mysql -h %s -u %s -p -sN -e \"%s\" db > %s' % (options.dbhost, options.dbuser, sql, filepath), shell=True)\n\n\ndef main(options, args):\n \"\"\"\"\"\"\n _date = options.startdate\n while _date <= options.enddate:\n rs = get_stats(options, _date)\n _date += datetime.timedelta(days=1)\n\n\nif __name__ == '__main__':\n parser = OptionParser(version=\"%prog 1.0\")\n parser.add_option('-s', '--startdate', type='string', dest='startdate', \n help='the start date (format: yyyymmdd)')\n\n parser.add_option('-e', '--enddate', type='string', dest='enddate', \n help='the end date (format: yyyymmdd)')\n\n parser.add_option('--output', type='string', dest='outdir', default='/home/output/', \n help='target directory for output files')\n\n parser.add_option('--dbhost', type='string', dest='dbhost', default='myhost', \n help='SQL server address')\n\n parser.add_option('--dbuser', type='string', dest='dbuser', default='dbuser', \n help='SQL server user')\n\n options, args = parser.parse_args()\n\n ## Process the date args\n if not options.startdate:\n options.startdate = datetime.datetime.today()\n else:\n try:\n options.startdate = datetime.datetime.strptime('%Y%m%d', options.startdate)\n except ValueError:\n parser.error(\"Invalid value for startdate (%s)\" % options.startdate)\n\n if not options.enddate:\n options.enddate = options.startdate + datetime.timedelta(days=7)\n else:\n try:\n options.enddate = datetime.datetime.strptime('%Y%m%d', options.enddate)\n except ValueError:\n parser.error(\"Invalid value for enddate (%s)\" % options.enddate)\n\n main(options, args)\n\n", "Try explicit formatting and quoting resulting string:\nsql = \"....WHERE d.Date = '\" + date.isoformat() + \"' GROUP BY ...\"\n\nQuotes at os.system call are messy and redirection look weird (if it's not a typo)\nos.system(\"mysql db -h -sN -u -p -e '\" + sql + \"' > /home/output/DateLoop-\" + day + \".txt\")\n\n", "Well, you can save the mysql template query in a config file and parse it with ConfigParser:\nThe config file will look like that:\n[mysql query configuration]\ndbhost = \ndb = \nusername = guest\npassword = \n\n[query template]\ntemplate = SELECT Date, SUM(CostUsd).......\n\nor you can just store it to a separate file and then read it with the standard open(filename).read, etc.\nIf you think that the query will become more complex in the future, the config file approach may be simpler to manage and understand, but it is not a big difference.\nTo get the date as a parameter, you can use sys.argv, or a library like optparse \n" ]
[ 3, 1, 0 ]
[]
[]
[ "mysql", "python", "shell" ]
stackoverflow_0001221232_mysql_python_shell.txt
Q: How does AMF communication work? How does Flash communicate with services / scripts on servers via AMF? Regarding the AMF libraries for Python / Perl / PHP which are easier to develop than .NET / Java: do they execute script files, whenever Flash sends an Remote Procedure Call? or do they communicate via sockets, to script classes that are running as services? Regarding typical AMF functionality: How is data transferred? is it by method arguments that are automatically serialised? How can servers "push" to clients? do Flash movies have to connect on a socket? Thanks for your time. A: The only AMF library I'm familiar with is PyAMF, which has been great to work with so far. Here are the answers to your questions for PyAMF: I'd imagine you can run it as a script (do you mean like CGI?), but the easiest IMO is to set up an app server specifically for AMF requests the easiest way is to define functions in pure python, which PyAMF wraps to serialize incoming / outgoing AMF data you can communicate via sockets if that's what you need to do, but again, it's the easiest to use pure Python functions; one use for sockets is to keep an open connection and 'push' data to clients, see this example Here's an example of three simple AMF services being served on localhost:8080: from wsgiref import simple_server from pyamf.remoting.gateway.wsgi import WSGIGateway ## amf services ################################################## def echo(data): return data def reverse(data): return data[::-1] def rot13(data): return data.encode('rot13') services = { 'myservice.echo': echo, 'myservice.reverse': reverse, 'myservice.rot13': rot13, } ## server ######################################################## def main(): app = WSGIGateway(services) simple_server.make_server('localhost', 8080, app).serve_forever() if __name__ == '__main__': main() I would definitely recommend PyAMF. Check out the examples to see what it's capable of and what the code looks like. A: How does Flash communicate with services / scripts on servers via AMF? Data is transferred over a TCP/IP connection. Sometimes an existing HTTP connection is used, and in other cases a new TCP/IP connection is opened for the AMF data. When the HTTP or additional TCP connections are opened, the sockets interface is probably used. The AMF definitely travels over a TCP connection of some sort, and the sockets interface is practically the only way to open such a connection. The "data" that is transferred consists of ECMA-script (Javascript(tm)) data types such as "integer", "string", "object", and so on. For a technical specification of how the objects are encoded into binary, Adobe has published a specification: AMF 3.0 Spec at Adobe.com Generally the way an AMF-using client/server system works is something like this: The client displays some user interface and opens a TCP connection to the server. The server sends some data to the client, which updates its user interface. If the user makes a command, the client sends some data to the server over the TCP connection. Continue steps 2-3 until the user exits. For example, if the user clicks a "send mail" button in the UI, then the client code might do this: public class UICommandMessage extends my.CmdMsg { public function UICommandMessage(action:String, arg: String) { this.cmd = action; this.data = String; } } Then later: UICommandMessage msg = new UICommandMessage("Button_Press", "Send_Mail"); server_connection.sendMessage(msg); in the server code, the server is monitoring the connection as well for incoming AMF object. It receives the message, and passes control to an appropriate response function. This is called "dispatching a message". With more information about what you are trying to accomplish, I could give you more useful details.
How does AMF communication work?
How does Flash communicate with services / scripts on servers via AMF? Regarding the AMF libraries for Python / Perl / PHP which are easier to develop than .NET / Java: do they execute script files, whenever Flash sends an Remote Procedure Call? or do they communicate via sockets, to script classes that are running as services? Regarding typical AMF functionality: How is data transferred? is it by method arguments that are automatically serialised? How can servers "push" to clients? do Flash movies have to connect on a socket? Thanks for your time.
[ "The only AMF library I'm familiar with is PyAMF, which has been great to work with so far. Here are the answers to your questions for PyAMF:\n\nI'd imagine you can run it as a script (do you mean like CGI?), but the easiest IMO is to set up an app server specifically for AMF requests\nthe easiest way is to define functions in pure python, which PyAMF wraps to serialize incoming / outgoing AMF data\nyou can communicate via sockets if that's what you need to do, but again, it's the easiest to use pure Python functions; one use for sockets is to keep an open connection and 'push' data to clients, see this example\n\nHere's an example of three simple AMF services being served on localhost:8080:\nfrom wsgiref import simple_server\nfrom pyamf.remoting.gateway.wsgi import WSGIGateway\n\n## amf services ##################################################\n\ndef echo(data):\n return data\n\ndef reverse(data):\n return data[::-1]\n\ndef rot13(data):\n return data.encode('rot13')\n\nservices = {\n 'myservice.echo': echo,\n 'myservice.reverse': reverse,\n 'myservice.rot13': rot13,\n}\n\n## server ########################################################\n\ndef main():\n app = WSGIGateway(services)\n\n simple_server.make_server('localhost', 8080, app).serve_forever()\n\nif __name__ == '__main__':\n main()\n\nI would definitely recommend PyAMF. Check out the examples to see what it's capable of and what the code looks like.\n", "\nHow does Flash communicate with services / scripts on servers via AMF?\n\nData is transferred over a TCP/IP connection. Sometimes an existing HTTP connection is used, and in other cases a new TCP/IP connection is opened for the AMF data. When the HTTP or additional TCP connections are opened, the sockets interface is probably used. The AMF definitely travels over a TCP connection of some sort, and the sockets interface is practically the only way to open such a connection.\nThe \"data\" that is transferred consists of ECMA-script (Javascript(tm)) data types such as \"integer\", \"string\", \"object\", and so on.\nFor a technical specification of how the objects are encoded into binary, Adobe has published a specification: AMF 3.0 Spec at Adobe.com \nGenerally the way an AMF-using client/server system works is something like this:\n\nThe client displays some user interface and opens a TCP connection to the server.\nThe server sends some data to the client, which updates its user interface.\nIf the user makes a command, the client sends some data to the server over the TCP connection.\nContinue steps 2-3 until the user exits.\n\nFor example, if the user clicks a \"send mail\" button in the UI, then the client code might do this:\npublic class UICommandMessage extends my.CmdMsg\n{\n public function UICommandMessage(action:String, arg: String)\n {\n this.cmd = action;\n this.data = String;\n }\n}\nThen later:\n\nUICommandMessage msg = new UICommandMessage(\"Button_Press\", \"Send_Mail\");\nserver_connection.sendMessage(msg);\n\nin the server code, the server is monitoring the connection as well for incoming AMF object. It receives the message, and passes control to an appropriate response function. This is called \"dispatching a message\".\nWith more information about what you are trying to accomplish, I could give you more useful details.\n" ]
[ 8, 4 ]
[]
[]
[ "actionscript_2", "amf", "flash", "perl", "python" ]
stackoverflow_0001422724_actionscript_2_amf_flash_perl_python.txt
Q: python: run a process with timeout and capture stdout, stderr and exit status Possible Duplicate: subprocess with timeout What is the easiest way to do the following in Python: Run an external process Capture stdout in a string, stderr, and exit status Set a timeout. I would like something like this: import proc try: status, stdout, stderr = proc.run(["ls", "-l"], timeout=10) except proc.Timeout: print "failed" A: I hate doing the work by myself. Just copy this into your proc.py module. import subprocess import time import sys class Timeout(Exception): pass def run(command, timeout=10): proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE) poll_seconds = .250 deadline = time.time()+timeout while time.time() < deadline and proc.poll() == None: time.sleep(poll_seconds) if proc.poll() == None: if float(sys.version[:3]) >= 2.6: proc.terminate() raise Timeout() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode if __name__=="__main__": print run(["ls", "-l"]) print run(["find", "/"], timeout=3) #should timeout A: Note on linux with coreutils >= 7.0 you can prepend timeout to the command like: timeout 1 sleep 1000
python: run a process with timeout and capture stdout, stderr and exit status
Possible Duplicate: subprocess with timeout What is the easiest way to do the following in Python: Run an external process Capture stdout in a string, stderr, and exit status Set a timeout. I would like something like this: import proc try: status, stdout, stderr = proc.run(["ls", "-l"], timeout=10) except proc.Timeout: print "failed"
[ "I hate doing the work by myself. Just copy this into your proc.py module.\nimport subprocess\nimport time\nimport sys\n\nclass Timeout(Exception):\n pass\n\ndef run(command, timeout=10):\n proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n poll_seconds = .250\n deadline = time.time()+timeout\n while time.time() < deadline and proc.poll() == None:\n time.sleep(poll_seconds)\n\n if proc.poll() == None:\n if float(sys.version[:3]) >= 2.6:\n proc.terminate()\n raise Timeout()\n\n stdout, stderr = proc.communicate()\n return stdout, stderr, proc.returncode\n\nif __name__==\"__main__\":\n print run([\"ls\", \"-l\"])\n print run([\"find\", \"/\"], timeout=3) #should timeout\n\n", "Note on linux with coreutils >= 7.0 you can prepend timeout to the command like:\ntimeout 1 sleep 1000\n\n" ]
[ 13, 12 ]
[]
[]
[ "external_process", "process", "python" ]
stackoverflow_0001556348_external_process_process_python.txt
Q: python/django for loop creating database populated with 0000-9999 Basically, i've created a view to populate my database with Serial models from 0000 to 9999. below is the code i'm using for the view. def insert_serials(request): for i in range(0,10000): serial = Serial(i,False) serial.save() else: print 'The for loop is over' what is the right way to do this, and i'm getting an IntegrityError, duplicate keys, my model defination is below: class Serial(models.Model): serial = models.CharField(max_length=4) closed = models.BooleanField() def __unicode__(self): return "%s" %(self.serial) def get_absolute_url(self): return "/draw/serial/%s/" % (self.serial) A: There may be positional default arguments, try using keywords: from django.db import transaction @transaction.commit_manually def insert_serials(request): for i in range(0,10000): serial = Serial(serial=str(i),closed=False) serial.save() transaction.commit() print 'The for loop is over' It's wrapped in a transaction should speed it up a bit. See transaction.commit_manually for details A: Your code is working on my site - Mac OS X, Python 2.6.3, django from trunk, sqlite3 I changed your view function code a bit, though - from django.http import HttpResponse from models import Serial def insert_serials(request): for i in range(0,10000): serial = Serial(i,False) serial.save() return HttpResponse("Serials are inserted") A: Try adding unique=False in the closed field declaration. Also, you're trying to put integers into a string field. You should do it like Serial('%04d' % i, False) to put values from '0000' to '9999'. A: Your id field (implied by the absence of a PK definition in your model) is not being autonumbered correctly and therefore every INSERT after the first is failing with a duplicate id value. What's your database? Did you have Django create the table, or did you do it yourself?
python/django for loop creating database populated with 0000-9999
Basically, i've created a view to populate my database with Serial models from 0000 to 9999. below is the code i'm using for the view. def insert_serials(request): for i in range(0,10000): serial = Serial(i,False) serial.save() else: print 'The for loop is over' what is the right way to do this, and i'm getting an IntegrityError, duplicate keys, my model defination is below: class Serial(models.Model): serial = models.CharField(max_length=4) closed = models.BooleanField() def __unicode__(self): return "%s" %(self.serial) def get_absolute_url(self): return "/draw/serial/%s/" % (self.serial)
[ "There may be positional default arguments, try using keywords:\nfrom django.db import transaction\n\[email protected]_manually\ndef insert_serials(request):\n for i in range(0,10000):\n serial = Serial(serial=str(i),closed=False)\n serial.save()\n transaction.commit()\n print 'The for loop is over'\n\nIt's wrapped in a transaction should speed it up a bit.\nSee transaction.commit_manually for details\n", "Your code is working on my site - Mac OS X, Python 2.6.3, django from trunk, sqlite3\nI changed your view function code a bit, though - \nfrom django.http import HttpResponse\nfrom models import Serial\n\ndef insert_serials(request):\n for i in range(0,10000):\n serial = Serial(i,False)\n serial.save()\n return HttpResponse(\"Serials are inserted\")\n\n", "Try adding unique=False in the closed field declaration.\nAlso, you're trying to put integers into a string field. You should do it like Serial('%04d' % i, False) to put values from '0000' to '9999'.\n", "Your id field (implied by the absence of a PK definition in your model) is not being autonumbered correctly and therefore every INSERT after the first is failing with a duplicate id value. What's your database? Did you have Django create the table, or did you do it yourself?\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001541891_django_python.txt
Q: PyQt: Displaying QTextEdits over the window I want to display some QTextEdits over my main window at arbitrary locations. Below is my first attempt. It doesn't quite work. If I create the text edits before I show the window, the text edits appear, but if I create them after I have shown the window they don't appear. What's up with that? How can I get the ones created later to show up? import sys, random from PyQt4 import QtGui, QtCore app = QtGui.QApplication(sys.argv) win = QtGui.QMainWindow() win.resize(500,500) def new_text(): print "new text" text = QtGui.QTextEdit(win) text.move(random.random() * 400, random.random() * 400) for i in range(3): new_text() timer = QtCore.QTimer() timer.connect(timer, QtCore.SIGNAL("timeout()"), new_text) timer.start(500) win.show() app.exec_() A: Oh, I got it. You have to call show on each widget before it appears. I guess QMainWindow.show recursively calls the method for all of its children. So just add text.show() to the end of the new_text function and it works.
PyQt: Displaying QTextEdits over the window
I want to display some QTextEdits over my main window at arbitrary locations. Below is my first attempt. It doesn't quite work. If I create the text edits before I show the window, the text edits appear, but if I create them after I have shown the window they don't appear. What's up with that? How can I get the ones created later to show up? import sys, random from PyQt4 import QtGui, QtCore app = QtGui.QApplication(sys.argv) win = QtGui.QMainWindow() win.resize(500,500) def new_text(): print "new text" text = QtGui.QTextEdit(win) text.move(random.random() * 400, random.random() * 400) for i in range(3): new_text() timer = QtCore.QTimer() timer.connect(timer, QtCore.SIGNAL("timeout()"), new_text) timer.start(500) win.show() app.exec_()
[ "Oh, I got it. You have to call show on each widget before it appears. I guess QMainWindow.show recursively calls the method for all of its children. So just add text.show() to the end of the new_text function and it works.\n" ]
[ 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0001557864_pyqt_pyqt4_python_qt_qt4.txt
Q: Getting proper code completion for Python on Vim? I've gotten omnicompletion with Pysmell to work before, but I can't seem to do it again. I tried following some steps online, but most, if not all, of them are to vague and assume too much that you know what you are doing to some extent. Can someone post a full, step-by-step tutorial on how to get code completion working properly, for complete Vim newbies (for dummies?)? A: There's also Ctrl+n in insert mode which will autocomplete based on the words it has seen in any of the open buffers (even in other tabs). A: You may try Pydiction (Excerpt below) Description Pydiction allows you to Tab-complete Python code in Vim, including: standard, custom and third-party modules and packages. Plus keywords, built-ins, and string literals. A: Pyflakes has a vim plugin that does this pretty awesomely. Unlike Pydiction, you don't need to build a dictionary beforehand (so if you're bouncing between different virtualenvs it's a bit less hassle.) I haven't been using it long but it seems very slick. A: Try hitting Ctrl-p while typing mid-word. Ctrl-p inserts the most recent word that starts with the prefix you're typing and Ctrl-n inserts the next match. If you have several possibilities, you can hit ctrl-p more than once to substitute each candidate in order.
Getting proper code completion for Python on Vim?
I've gotten omnicompletion with Pysmell to work before, but I can't seem to do it again. I tried following some steps online, but most, if not all, of them are to vague and assume too much that you know what you are doing to some extent. Can someone post a full, step-by-step tutorial on how to get code completion working properly, for complete Vim newbies (for dummies?)?
[ "There's also Ctrl+n in insert mode which will autocomplete based on the words it has seen in any of the open buffers (even in other tabs). \n", "You may try Pydiction (Excerpt below)\n\nDescription Pydiction allows you to\n Tab-complete Python code in Vim,\n including: standard, custom and\n third-party modules and packages. Plus\n keywords, built-ins, and string\n literals.\n\n", "Pyflakes has a vim plugin that does this pretty awesomely. Unlike Pydiction, you don't need to build a dictionary beforehand (so if you're bouncing between different virtualenvs it's a bit less hassle.) I haven't been using it long but it seems very slick.\n", "Try hitting Ctrl-p while typing mid-word. Ctrl-p inserts the most recent word that starts with the prefix you're typing and Ctrl-n inserts the next match. If you have several possibilities, you can hit ctrl-p more than once to substitute each candidate in order.\n" ]
[ 4, 2, 1, 0 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0001520576_python_vim.txt
Q: relevant query to what is the best python method for encryption I tried to use the gnupg.py module encryption decryption function named " def test_encryption_and_decryption(self): " Could i use this function by passing the key or fingerprint retrieved from public key server. I am getting the key by this : retk = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup op=get&search=hex format of key') pub_key = retk.read() i also tried to pass the fingerprint in encrypt method : data = "Hello, world!" edata = str(self.gpg.encrypt(data, fingerprint)) print edata Not getting the way how to do .Is somebody help me out by giving their valuble and effective solution/suggestions. thanks! A: Before you can encrypt with a key whose keyid you have, you need to import the key into the keyring. Use the import_keys function for that. Edit: that you cannot encrypt even after importing the key is because GPG does not trust it. This becomes apparent when you turn on verbose messages; you'll get gpg: <keyid>: There is no assurance this key belongs to the named user To work around (short of setting up a trust path for the key), you can change gpg's trust model. The following program works for me (with my key as an example) import gnupg, urllib retk = urllib.urlopen("http://keyserver.pramberger.at/pks/" "lookup?op=get&search=0x6AF053F07D9DC8D2") pub_key = retk.read() gpg = gnupg.GPG(gnupghome="/tmp/foo", verbose=True) print "Import:", gpg.import_keys(pub_key).summary() print "Encrypt:", gpg.encrypt("Hello, world!", "6AF053F07D9DC8D2", always_trust=True)
relevant query to what is the best python method for encryption
I tried to use the gnupg.py module encryption decryption function named " def test_encryption_and_decryption(self): " Could i use this function by passing the key or fingerprint retrieved from public key server. I am getting the key by this : retk = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup op=get&search=hex format of key') pub_key = retk.read() i also tried to pass the fingerprint in encrypt method : data = "Hello, world!" edata = str(self.gpg.encrypt(data, fingerprint)) print edata Not getting the way how to do .Is somebody help me out by giving their valuble and effective solution/suggestions. thanks!
[ "Before you can encrypt with a key whose keyid you have, you need to import the key into the keyring. Use the import_keys function for that.\nEdit: that you cannot encrypt even after importing the key is because GPG does not trust it. This becomes apparent when you turn on verbose messages; you'll get\ngpg: <keyid>: There is no assurance this key belongs to the named user\n\nTo work around (short of setting up a trust path for the key), you can change gpg's trust model. The following program works for me (with my key as an example)\nimport gnupg, urllib\nretk = urllib.urlopen(\"http://keyserver.pramberger.at/pks/\"\n \"lookup?op=get&search=0x6AF053F07D9DC8D2\")\npub_key = retk.read()\n\ngpg = gnupg.GPG(gnupghome=\"/tmp/foo\", verbose=True)\nprint \"Import:\", gpg.import_keys(pub_key).summary()\nprint \"Encrypt:\", gpg.encrypt(\"Hello, world!\", \"6AF053F07D9DC8D2\", \n always_trust=True)\n\n" ]
[ 3 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0001558287_encryption_python.txt
Q: how do I get only the time in models How do I format datetime to give me only the time in my model A: If you've got a datetime object in your template called foo, use: {{ foo|time:"H:i" }} Look at the time filter documentation. You're not limited to "H:i", there are lots of options around for formatting datetime objects. If for some reason you're wanting to do this directly in your model (which is probably not where it belongs), then use datetime's strftime - take a look at the relevant documentation. For example, again assuming a datetime object called foo: hour = foo.strftime("%H:%M")
how do I get only the time in models
How do I format datetime to give me only the time in my model
[ "If you've got a datetime object in your template called foo, use:\n{{ foo|time:\"H:i\" }}\n\nLook at the time filter documentation. You're not limited to \"H:i\", there are lots of options around for formatting datetime objects.\nIf for some reason you're wanting to do this directly in your model (which is probably not where it belongs), then use datetime's strftime - take a look at the relevant documentation.\nFor example, again assuming a datetime object called foo:\nhour = foo.strftime(\"%H:%M\")\n\n" ]
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001558896_django_python.txt
Q: Convert from hex string to unicode How can i convert the 'dead' string to an unicode string u'\xde\xad'? Doing this: from binascii import unhexlify out = ''.join(x for x in [unhexlify('de'), unhexlify('ad')]) creates a <type 'str'> string '\xde\xad' Trying to use the Unicode.join() like this: from binascii import unhexlify out = ''.join(x for x in [u'', unhexlify('de'), unhexlify('ad')]) results in an error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xde in position 0: ordinal not in range(128) A: Unicode is designed to be compatible with Latin-1, you can use that and simply decode the bytestring: In [2]: unhexlify('dead').decode('latin1') Out[2]: u'\xde\xad' A: See this Python unicode how-to, and use something akin to: unicode('\x80abc', errors='replace') or unicode('\x80abc', errors='ignore')
Convert from hex string to unicode
How can i convert the 'dead' string to an unicode string u'\xde\xad'? Doing this: from binascii import unhexlify out = ''.join(x for x in [unhexlify('de'), unhexlify('ad')]) creates a <type 'str'> string '\xde\xad' Trying to use the Unicode.join() like this: from binascii import unhexlify out = ''.join(x for x in [u'', unhexlify('de'), unhexlify('ad')]) results in an error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xde in position 0: ordinal not in range(128)
[ "Unicode is designed to be compatible with Latin-1, you can use that and simply decode the bytestring:\nIn [2]: unhexlify('dead').decode('latin1')\nOut[2]: u'\\xde\\xad'\n\n", "See this Python unicode how-to, and use something akin to:\nunicode('\\x80abc', errors='replace')\n\nor\nunicode('\\x80abc', errors='ignore')\n\n" ]
[ 5, 1 ]
[]
[]
[ "decode", "encode", "python", "unicode", "utf_8" ]
stackoverflow_0001559065_decode_encode_python_unicode_utf_8.txt
Q: String arguments in Python multiprocessing I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters. This is the code: import multiprocessing def write(s): print s write('hello') p = multiprocessing.Process(target=write, args=('hello')) p.start() I get this output: hello Process Process-1: Traceback (most recent call last): >>> File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 237, in _bootstrap self.run() File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) TypeError: write() takes exactly 1 argument (5 given) >>> What am I doing wrong? How am I supposed to pass a string? A: This is a common gotcha in Python - if you want to have a tuple with only one element, you need to specify that it's actually a tuple (and not just something with brackets around it) - this is done by adding a comma after the element. To fix this, just put a comma after the string, inside the brackets: p = multiprocessing.Process(target=write, args=('hello',)) That way, Python will recognise it as a tuple with a single element, as intended. Currently, Python is interpreting your code as just a string. However, it's failing in this particular way because a string is effectively list of characters. So Python is thinking that you want to pass ('h', 'e', 'l', 'l', 'o'). That's why it's saying "you gave me 5 parameters". A: Change args=('hello') to args=('hello',) or even better args=['hello']. Otherwise parentheses don't form a sequence. A: You have to pass p = multiprocessing.Process(target=write, args=('hello',)) Notice the comma! Otherwise it is interpreted as a simple string and not as a 1 element tuple.
String arguments in Python multiprocessing
I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters. This is the code: import multiprocessing def write(s): print s write('hello') p = multiprocessing.Process(target=write, args=('hello')) p.start() I get this output: hello Process Process-1: Traceback (most recent call last): >>> File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 237, in _bootstrap self.run() File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) TypeError: write() takes exactly 1 argument (5 given) >>> What am I doing wrong? How am I supposed to pass a string?
[ "This is a common gotcha in Python - if you want to have a tuple with only one element, you need to specify that it's actually a tuple (and not just something with brackets around it) - this is done by adding a comma after the element.\nTo fix this, just put a comma after the string, inside the brackets:\np = multiprocessing.Process(target=write, args=('hello',))\n\nThat way, Python will recognise it as a tuple with a single element, as intended. Currently, Python is interpreting your code as just a string. However, it's failing in this particular way because a string is effectively list of characters. So Python is thinking that you want to pass ('h', 'e', 'l', 'l', 'o'). That's why it's saying \"you gave me 5 parameters\".\n", "Change args=('hello') to args=('hello',) or even better args=['hello']. Otherwise parentheses don't form a sequence.\n", "You have to pass\np = multiprocessing.Process(target=write, args=('hello',))\n\nNotice the comma! Otherwise it is interpreted as a simple string and not as a 1 element tuple.\n" ]
[ 133, 16, 11 ]
[]
[]
[ "arguments", "multiprocessing", "python", "string" ]
stackoverflow_0001559125_arguments_multiprocessing_python_string.txt
Q: Regular Expression for HTML artifacts I some text with HTML artifacts where the < and > of tags got dropped, so now I need something that will match a small p followed by a capital letter, like pThe next day they.... And I also need something that will catch the trailing /p which is easier. These need to be stripped, i.e. replaced with "" in python. What RE would I use for that? Thanks! Stephan. A: Try this: re.sub(r"(/?p)(?=[A-Z]|$)", r"<\1>", str) You might want to extend the boundary assertion (here (?=[A-Z]|$)) with additional characters like whitespace. A: I got is. You use backreferences, import re smallBig = re.compile(r'[a-z]([A-Z])') ... cleanedString = smallBig.sub(r'\1', dirtyString) This removes the small letter but keeps the capital letter in cases where the '<' and '>' of html tags were stripped and you sit with text like pSome new paragraph text /p Quick and dirty but it works in my case.
Regular Expression for HTML artifacts
I some text with HTML artifacts where the < and > of tags got dropped, so now I need something that will match a small p followed by a capital letter, like pThe next day they.... And I also need something that will catch the trailing /p which is easier. These need to be stripped, i.e. replaced with "" in python. What RE would I use for that? Thanks! Stephan.
[ "Try this:\nre.sub(r\"(/?p)(?=[A-Z]|$)\", r\"<\\1>\", str)\n\nYou might want to extend the boundary assertion (here (?=[A-Z]|$)) with additional characters like whitespace.\n", "I got is. You use backreferences,\nimport re\nsmallBig = re.compile(r'[a-z]([A-Z])')\n\n...\ncleanedString = smallBig.sub(r'\\1', dirtyString)\n\nThis removes the small letter but keeps the capital letter in cases where the '<' and '>' of html tags were stripped and you sit with text like \npSome new paragraph text /p\nQuick and dirty but it works in my case.\n" ]
[ 1, 1 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0001559375_html_python_regex.txt
Q: Which is the most pythonic: installing python modules via a package manager ( macports, apt) or via pip/easy_install/setuptools Usually I tend to install things via the package manager, for unixy stuff. However, when I programmed a lot of perl, I would use CPAN, newer versions and all that. In general, I used to install system stuff via package manager, and language stuff via it's own package manager ( gem/easy_install|pip/cpan) Now using python primarily, I am wondering what best practice is? A: The system python version and its libraries are often used by software in the distribution. As long as the software you are using are happy with the same versions of python and all the libraries as your distribution is, than using the distribution packages will work just fine. However, quite often you need development version of packages, or newer version, or older versions. And then it doesn't work any more. It is therefore usually recommeded to install your own Python version that you use for development, and create development environments with buildout or virtualenv or both, to isolate the system python and the development environment from each other. A: There are two completely opposing camps: one in favor of system-provided packages, and one in favor of separate installation. I'm personally in the "system packages" camp. I'll provide arguments from each side below. Pro system packages: system packager already cares about dependency, and compliance with overall system policies (such as file layout). System packages provide security updates while still caring about not breaking compatibility - so they sometimes backport security fixes that the upstream authors did not backport. System packages are "safe" wrt. system upgrades: after a system upgrade, you probably also have a new Python version, but all your Python modules are still there if they come from a system packager. That's all personal experience with Debian. Con system packages: not all software may be provided as a system package, or not in the latest version; installing stuff yourself into the system may break system packages. Upgrades may break your application. Pro separate installation: Some people (in particular web application developers) argue that you absolutely need a repeatable setup, with just the packages you want, and completely decoupled from system Python. This goes beyond self-installed vs. system packages, since even for self-installed, you might still modify the system python; with the separate installation, you won't. As Lennart discusses, there are now dedicated tool chains to support this setup. People argue that only this approach can guarantee repeatable results. Con separate installation: you need to deal with bug fixes yourself, and you need to make sure all your users use the separate installation. In the case of web applications, the latter is typically easy to achieve.
Which is the most pythonic: installing python modules via a package manager ( macports, apt) or via pip/easy_install/setuptools
Usually I tend to install things via the package manager, for unixy stuff. However, when I programmed a lot of perl, I would use CPAN, newer versions and all that. In general, I used to install system stuff via package manager, and language stuff via it's own package manager ( gem/easy_install|pip/cpan) Now using python primarily, I am wondering what best practice is?
[ "The system python version and its libraries are often used by software in the distribution. As long as the software you are using are happy with the same versions of python and all the libraries as your distribution is, than using the distribution packages will work just fine.\nHowever, quite often you need development version of packages, or newer version, or older versions. And then it doesn't work any more.\nIt is therefore usually recommeded to install your own Python version that you use for development, and create development environments with buildout or virtualenv or both, to isolate the system python and the development environment from each other.\n", "There are two completely opposing camps: one in favor of system-provided packages, and one in favor of separate installation. I'm personally in the \"system packages\" camp. I'll provide arguments from each side below.\nPro system packages: system packager already cares about dependency, and compliance with overall system policies (such as file layout). System packages provide security updates while still caring about not breaking compatibility - so they sometimes backport security fixes that the upstream authors did not backport. System packages are \"safe\" wrt. system upgrades: after a system upgrade, you probably also have a new Python version, but all your Python modules are still there if they come from a system packager. That's all personal experience with Debian.\nCon system packages: not all software may be provided as a system package, or not in the latest version; installing stuff yourself into the system may break system packages. Upgrades may break your application.\nPro separate installation: Some people (in particular web application developers) argue that you absolutely need a repeatable setup, with just the packages you want, and completely decoupled from system Python. This goes beyond self-installed vs. system packages, since even for self-installed, you might still modify the system python; with the separate installation, you won't. As Lennart discusses, there are now dedicated tool chains to support this setup. People argue that only this approach can guarantee repeatable results.\nCon separate installation: you need to deal with bug fixes yourself, and you need to make sure all your users use the separate installation. In the case of web applications, the latter is typically easy to achieve.\n" ]
[ 17, 17 ]
[]
[]
[ "distutils", "pip", "python", "setuptools" ]
stackoverflow_0001559372_distutils_pip_python_setuptools.txt
Q: Embedded objects in MS Office documents using Python? How could I create embedded objects in an MS office document using Python? I don't need anything fancy, just what one used to do in the first version of OLE: doing a copy-paste from my application into e.g. MS Word should give me an object embedded in the Word document, which I can then double-click to open a copy of my application and edit the object. Can this be done from a Python/PyQt application (perhaps using pythoncom?) Are there any simple examples of this that can get me started? A: OLE compound documents enable users working within a single application to manipulate data written in various formats and derived from multiple sources. A compound document object is essentially a COM object that can be embedded in, or linked to, an existing document. As a COM object, a compound document object exposes the IUnknown interface, through which clients can obtain pointers to its other interfaces, including several, such as IOleObject, IOleLink, and IViewObject2, that provide special features unique to compound document objects. You'll use pywin32 extensions. This COM tutorial can get you started (I hope). Most info you need will come from microsoft itself. There's a book on the subject.
Embedded objects in MS Office documents using Python?
How could I create embedded objects in an MS office document using Python? I don't need anything fancy, just what one used to do in the first version of OLE: doing a copy-paste from my application into e.g. MS Word should give me an object embedded in the Word document, which I can then double-click to open a copy of my application and edit the object. Can this be done from a Python/PyQt application (perhaps using pythoncom?) Are there any simple examples of this that can get me started?
[ "OLE compound documents enable users working within a single application to manipulate data written in various formats and derived from multiple sources. A compound document object is essentially a COM object that can be embedded in, or linked to, an existing document. As a COM object, a compound document object exposes the IUnknown interface, through which clients can obtain pointers to its other interfaces, including several, such as IOleObject, IOleLink, and IViewObject2, that provide special features unique to compound document objects. \nYou'll use pywin32 extensions. This COM tutorial can get you started (I hope). Most info you need will come from microsoft itself. There's a book on the subject.\n" ]
[ 1 ]
[]
[]
[ "com", "ms_office", "ole", "python", "windows" ]
stackoverflow_0001559709_com_ms_office_ole_python_windows.txt
Q: "undefined symbol: TLSv1_method" error when import psycopg2 I installed psycopg2 by "easy_install psycopg2" on CentOS 5.3, no error was reported, but when I tried "import psycopg2", I got : exceptions.ImportError: /usr/lib/python2.4/site-packages/psycopg2-2.0.9-py2.4-linux-i686.egg/psycopg2/_psycopg.so: undefined symbol: TLSv1_method What might cause the problem? A: You might have to yum install openssl?
"undefined symbol: TLSv1_method" error when import psycopg2
I installed psycopg2 by "easy_install psycopg2" on CentOS 5.3, no error was reported, but when I tried "import psycopg2", I got : exceptions.ImportError: /usr/lib/python2.4/site-packages/psycopg2-2.0.9-py2.4-linux-i686.egg/psycopg2/_psycopg.so: undefined symbol: TLSv1_method What might cause the problem?
[ "You might have to yum install openssl?\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001560066_python.txt
Q: Optparse library - callback action while storing arg My code: def main(): usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-p", "--pending", action="callback", callback=pending, type="string", dest="test", help="View Pending Jobs") (options, args) = parser.parse_args() if x == 0: print usage, " (-h or --help for help)" print options.test if i had: script -p hello i need options.test to print out the argument as type string A: The arguments are available through sys.argv. A: Ended up passing the argument to the function that is being called.
Optparse library - callback action while storing arg
My code: def main(): usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-p", "--pending", action="callback", callback=pending, type="string", dest="test", help="View Pending Jobs") (options, args) = parser.parse_args() if x == 0: print usage, " (-h or --help for help)" print options.test if i had: script -p hello i need options.test to print out the argument as type string
[ "The arguments are available through sys.argv.\n", "Ended up passing the argument to the function that is being called.\n" ]
[ 1, 0 ]
[]
[]
[ "ironpython", "optparse", "python" ]
stackoverflow_0001560092_ironpython_optparse_python.txt
Q: Equivalent of GetCursorPos() in Mac's Carbon Background We're porting our PythonOgre-based games to Mac, and the publishers demand ability for mouse to leave the window. On Windows, we're going around OIS (Object-oriented Input System) for the purposes of mouse control; that is, we don't let OIS keep the mouse captured inside window borders, and then track the mouse cursor in screen coordinates using GetCursorPos() Win32 API. We cannot trivially modify the Ogre3d loop -- it would require at least a rebuild of the library, plus a rebuild of the wrapper which can easily take about an entire workday on our build machine. Theoretically we could modify OIS but we're on tight schedule so, for same reasons, we'd rather not unnecessarily play with it either. Question What is the Carbon API for obtaining screen-space mouse cursor coordinate, equivalent to Windows API GetCursorPos()? A: I believe that what you are looking for is GetMouse(). You can find an example in Apple's UIElementInspector sample code. This is in Obj-C not Python, though. EDIT: HIGetMousePosition() is the preferred method, according to NSD.
Equivalent of GetCursorPos() in Mac's Carbon
Background We're porting our PythonOgre-based games to Mac, and the publishers demand ability for mouse to leave the window. On Windows, we're going around OIS (Object-oriented Input System) for the purposes of mouse control; that is, we don't let OIS keep the mouse captured inside window borders, and then track the mouse cursor in screen coordinates using GetCursorPos() Win32 API. We cannot trivially modify the Ogre3d loop -- it would require at least a rebuild of the library, plus a rebuild of the wrapper which can easily take about an entire workday on our build machine. Theoretically we could modify OIS but we're on tight schedule so, for same reasons, we'd rather not unnecessarily play with it either. Question What is the Carbon API for obtaining screen-space mouse cursor coordinate, equivalent to Windows API GetCursorPos()?
[ "I believe that what you are looking for is GetMouse(). You can find an example in Apple's UIElementInspector sample code. This is in Obj-C not Python, though.\nEDIT: HIGetMousePosition() is the preferred method, according to NSD.\n" ]
[ 1 ]
[]
[]
[ "macos", "macos_carbon", "mouse", "python" ]
stackoverflow_0001560472_macos_macos_carbon_mouse_python.txt
Q: Perform an action and redirecting to the same URL doesn't refresh the page We are working on a new web site using Apache, Python and Django. In the development phase, no problem but once binding to Apache, using Firefox 3.5.3, we got a strange problem. We stand on : http://website.fr/search/ When we want to change the ordering of the research, we are sending the user to : http://website.fr/search/order/price/ This page change a session variable and redirect, with code 302, to : http://website.fr/search/ The problem is that Apache send a 302 Apache code and that Firefox doesn't refresh the page. We got the same problem when we are redirecting the user to the same page he was before. How should we do to force the refresh of the page ? A: What happens is, the browser asks for the new URL and via 302 gets redirected back to the previous one, which is in the cache and thus not refreshed. Adding a random integer, like Piotr is suggesting will solve the problem. For randomness you can use simple timestamp. Implication of performing forward as you are doing makes your app unRESTful and prohibits user bookmarking the results - i wonder if it is really what you would like to do. It might be worth a try to try and use 303 or 307 status code instead of 302, maybe that behaves differently. See also: http://en.wikipedia.org/wiki/HTTP_302 http://en.wikipedia.org/wiki/Representational_State_Transfer A: I'd say you're doing it wrong. The same URL should be the same page. Everything with HTTP and web browsers assume this, and when you don't follow this convention you're going to get yourself into trouble. Just add the search parameters and sort orders as query parameters to the URL. A: How about redirecting to http://website.fr/search/?ignoredvar=<random int> Please provide the full http conversation If you need a better solution. The conversation can be traced using firebug or live http headers. Btw. The above solution is the only one I know for similar bug in a flash on IE.
Perform an action and redirecting to the same URL doesn't refresh the page
We are working on a new web site using Apache, Python and Django. In the development phase, no problem but once binding to Apache, using Firefox 3.5.3, we got a strange problem. We stand on : http://website.fr/search/ When we want to change the ordering of the research, we are sending the user to : http://website.fr/search/order/price/ This page change a session variable and redirect, with code 302, to : http://website.fr/search/ The problem is that Apache send a 302 Apache code and that Firefox doesn't refresh the page. We got the same problem when we are redirecting the user to the same page he was before. How should we do to force the refresh of the page ?
[ "What happens is, the browser asks for the new URL and via 302 gets redirected back to the previous one, which is in the cache and thus not refreshed. Adding a random integer, like Piotr is suggesting will solve the problem. For randomness you can use simple timestamp.\nImplication of performing forward as you are doing makes your app unRESTful and prohibits user bookmarking the results - i wonder if it is really what you would like to do.\nIt might be worth a try to try and use 303 or 307 status code instead of 302, maybe that behaves differently.\nSee also: \nhttp://en.wikipedia.org/wiki/HTTP_302\nhttp://en.wikipedia.org/wiki/Representational_State_Transfer\n", "I'd say you're doing it wrong. The same URL should be the same page. Everything with HTTP and web browsers assume this, and when you don't follow this convention you're going to get yourself into trouble. Just add the search parameters and sort orders as query parameters to the URL.\n", "How about redirecting to\nhttp://website.fr/search/?ignoredvar=<random int>\n\nPlease provide the full http conversation If you need a better solution.\nThe conversation can be traced using firebug or live http headers.\nBtw. The above solution is the only one I know for similar bug in a flash on IE.\n" ]
[ 5, 1, 0 ]
[]
[]
[ "django", "http", "http_status_code_302", "httpwebrequest", "python" ]
stackoverflow_0001538994_django_http_http_status_code_302_httpwebrequest_python.txt
Q: Histogram in matplotlib gets cropped at top I have a Python program that generates a histogram using matplotlib. The problem is that the images that are generated sometimes get cropped at the top. First, here's the relevant code excerpt, where plt is matplotlib.pyplot and fig is matplotlib.figure: plt.hist(grades, bins=min(20, maxScore), range=(0,maxScore), figure=fig.Figure(figsize=(3,2), dpi=150)) plt.xlabel("Raw Score") plt.ylabel("Count") plt.title("Raw Score Histogram") plt.savefig(histogramFile) The problem appears in a situation like the following. I might have 300 elements in grades, 3 of the bins have more than 20 elements in them, and the rest less than 20. The ones with more than 20 will have their tops cut off and the y-axis will only go up to 20. This doesn't always happen though: a different 300 elements in grades with a similar distribution might render correctly, with the y-axis scaling to fit within the figsize. Also note that the x-axis always comes out right. What can I do to get the y-axis to scale correctly and produce bars that fit within the image? A: File a bug report to the matplotlib's developers, and ask them to write a test case on it. You should be able to set the y axis with the ylim function: is it what you are asking for? Can you show a screenshot of your problem?
Histogram in matplotlib gets cropped at top
I have a Python program that generates a histogram using matplotlib. The problem is that the images that are generated sometimes get cropped at the top. First, here's the relevant code excerpt, where plt is matplotlib.pyplot and fig is matplotlib.figure: plt.hist(grades, bins=min(20, maxScore), range=(0,maxScore), figure=fig.Figure(figsize=(3,2), dpi=150)) plt.xlabel("Raw Score") plt.ylabel("Count") plt.title("Raw Score Histogram") plt.savefig(histogramFile) The problem appears in a situation like the following. I might have 300 elements in grades, 3 of the bins have more than 20 elements in them, and the rest less than 20. The ones with more than 20 will have their tops cut off and the y-axis will only go up to 20. This doesn't always happen though: a different 300 elements in grades with a similar distribution might render correctly, with the y-axis scaling to fit within the figsize. Also note that the x-axis always comes out right. What can I do to get the y-axis to scale correctly and produce bars that fit within the image?
[ "File a bug report to the matplotlib's developers, and ask them to write a test case on it.\nYou should be able to set the y axis with the ylim function: is it what you are asking for? Can you show a screenshot of your problem?\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python", "python_imaging_library" ]
stackoverflow_0001560734_matplotlib_python_python_imaging_library.txt
Q: Playing sounds with python and changing their tone during playback? Is there a way to do this? Also, I need this to work with pygame, since I want audio in my game. I'm asking this because I didn't see any tone change function in pygame.. Anyone knows? Update: I need to do something like the noise of a car accelerating. I don't really know if it is timbre or tone. A: Well, it depends on how you're doing your sounds: I'm not sure if this is possible with pygame, but SDL (which pygame is based off of) lets you have a callback to retrieve data for the sound buffer, and it's possible to change the frequency of the sine wave (or whatever) to get different tones in the callback, given that you generate the sound there. If you're using a pre-rendered tone, or sound file, then you'll probably have to resample it to get it to play at different frequencies, although it'd be difficult to keep the same length. If you're talking about changing the timbre of the sound, then that's a whole different ballpark... Also, it depends on how fast the sound needs to change: if you can accept a little lag in response, you could probably generate a few short sounds, and play/loop them as necessary. I'm not sure how constant replaying of sounds would impact performance/the overall audio quality, though: you'd have to make sure the ends of all the waveform ends smoothly transition to the beginning of the next one (maybe).
Playing sounds with python and changing their tone during playback?
Is there a way to do this? Also, I need this to work with pygame, since I want audio in my game. I'm asking this because I didn't see any tone change function in pygame.. Anyone knows? Update: I need to do something like the noise of a car accelerating. I don't really know if it is timbre or tone.
[ "Well, it depends on how you're doing your sounds: I'm not sure if this is possible with pygame, but SDL (which pygame is based off of) lets you have a callback to retrieve data for the sound buffer, and it's possible to change the frequency of the sine wave (or whatever) to get different tones in the callback, given that you generate the sound there.\nIf you're using a pre-rendered tone, or sound file, then you'll probably have to resample it to get it to play at different frequencies, although it'd be difficult to keep the same length. If you're talking about changing the timbre of the sound, then that's a whole different ballpark...\nAlso, it depends on how fast the sound needs to change: if you can accept a little lag in response, you could probably generate a few short sounds, and play/loop them as necessary. I'm not sure how constant replaying of sounds would impact performance/the overall audio quality, though: you'd have to make sure the ends of all the waveform ends smoothly transition to the beginning of the next one (maybe).\n" ]
[ 1 ]
[]
[]
[ "pitch", "pygame", "python" ]
stackoverflow_0001561104_pitch_pygame_python.txt
Q: Grouping data points into series I have a series of data points (tuples) in a list with a format like: points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string. I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into: [['a', 'b', 'a', 'd'], ['c']] I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets? def split_series(points, interval): series = [] start = points[0][0] finish = points[-1][0] marker = start next = start + interval while marker <= finish: series.append([point[1] for point in points if marker <= point[0] < next]) marker = next next += interval return series A: One way to do it (no promises on speed): Break your list of tuples into two lists: [1,2,2,3,4] and ['a','b','a','d','c'] Since the first list is sorted, you can just keep iterating over it until you get to an element out of the range. Then, you know the indexes of the start and end elements so you can just slice the strings out of second array. Continue until you've got all the intervals. I'm not sure how efficient that'll be with tradition Python lists, but if your dataset is large enough, you could try using a NumPy array, which will slice really quickly. A: Your code is O(n2). Here's an O(n) solution: def split_series(points, interval): series = [] current_group = [] marker = points[0][0] for value, data in points: if value >= marker + interval: series.append(current_group) current_group = [] marker += interval current_group.append(data) if current_group: series.append(current_group) return series points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] print split_series(points, 3) # Prints [['a', 'b', 'a', 'd'], ['c']] A: For completeness, here's a solution with itertools.groupby, but the dictionary solution will probably be faster (not to mention a lot easier to read). import itertools import operator def split_series(points, interval): start = points[0][0] return [[v for k, v in grouper] for group, grouper in itertools.groupby((((n - start) // interval, val) for n, val in points), operator.itemgetter(0))] Note that the above assumes you've got at least one item in each group, otherwise it'll give different results from your script, i.e.: >>> split_series([(1, 'a'), (2, 'b'), (6, 'a'), (6, 'd'), (11, 'c')], 3) [['a', 'b'], ['a', 'd'], ['c']] instead of [['a', 'b'], ['a', 'd'], [], ['c']] Here's a fixed-up dictionary solution. At some point the dictionary lookup time will begin to dominate, but maybe it's fast enough for you like this. from collections import defaultdict def split_series(points, interval): offset = points[0][0] maxval = (points[-1][0] - offset) // interval vals = defaultdict(list) for key, value in points: vals[(key - offset) // interval].append(value) return [vals[i] for i in xrange(maxval + 1)] A: From your code, I'm assuming my prior comment is correct. The problem here appears to be that the performance is O(n^2) - you repeat the list comprehension (which iterates all items) multiple times. I say, use a simple for loop. If the current item belongs in the same group as the previous one, add it to the existing inner list [["a"], ["b"]] -> [["a"], ["b", "c"]]. If it doesn't, add it to a new inner list, perhaps adding empty padding lists first. A: Expanding on Am's answer, use a defaultdict, and floor-divide the key by the interval to break them up correctly. from collections import defaultdict def split_series(points, interval): vals = defaultdict(list) for key, value in points: vals[(key-1)//interval].append(value) return vals.values() A: Here's a lazy approach that uses the step behavior of xrange: def split_series(points, interval): end_of_chunk = interval chunk = [] for marker, item in points: if marker > end_of_chunk: for end_of_chunk in xrange(end_of_chunk, marker, interval): yield chunk chunk = [] end_of_chunk += interval chunk.append(item) yield chunk A: How about using iterators for lazy evaluation? This should be the equivalent of your initial solution: from itertools import groupby def split_series(points, interval): """ >>> points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] >>> print list(split_series(points, 3)) [['a', 'b', 'a', 'd'], ['c']] """ def interval_key(t): return (t[0] - points[0][0]) // interval groups = groupby(points, interval_key) for group in groups: yield [v for _, v in group[1]]
Grouping data points into series
I have a series of data points (tuples) in a list with a format like: points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string. I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into: [['a', 'b', 'a', 'd'], ['c']] I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets? def split_series(points, interval): series = [] start = points[0][0] finish = points[-1][0] marker = start next = start + interval while marker <= finish: series.append([point[1] for point in points if marker <= point[0] < next]) marker = next next += interval return series
[ "One way to do it (no promises on speed):\nBreak your list of tuples into two lists:\n[1,2,2,3,4] and ['a','b','a','d','c']\nSince the first list is sorted, you can just keep iterating over it until you get to an element out of the range. Then, you know the indexes of the start and end elements so you can just slice the strings out of second array. Continue until you've got all the intervals.\nI'm not sure how efficient that'll be with tradition Python lists, but if your dataset is large enough, you could try using a NumPy array, which will slice really quickly.\n", "Your code is O(n2). Here's an O(n) solution:\ndef split_series(points, interval):\n series = []\n current_group = []\n marker = points[0][0]\n for value, data in points:\n if value >= marker + interval:\n series.append(current_group)\n current_group = []\n marker += interval\n current_group.append(data)\n\n if current_group:\n series.append(current_group)\n\n return series\n\npoints = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]\nprint split_series(points, 3) # Prints [['a', 'b', 'a', 'd'], ['c']]\n\n", "For completeness, here's a solution with itertools.groupby, but the dictionary solution will probably be faster (not to mention a lot easier to read).\nimport itertools\nimport operator\n\ndef split_series(points, interval):\n start = points[0][0]\n\n return [[v for k, v in grouper] for group, grouper in\n itertools.groupby((((n - start) // interval, val)\n for n, val in points), operator.itemgetter(0))]\n\nNote that the above assumes you've got at least one item in each group, otherwise it'll give different results from your script, i.e.:\n>>> split_series([(1, 'a'), (2, 'b'), (6, 'a'), (6, 'd'), (11, 'c')], 3)\n[['a', 'b'], ['a', 'd'], ['c']]\n\ninstead of\n[['a', 'b'], ['a', 'd'], [], ['c']]\n\nHere's a fixed-up dictionary solution. At some point the dictionary lookup time will begin to dominate, but maybe it's fast enough for you like this.\nfrom collections import defaultdict\n\ndef split_series(points, interval):\n offset = points[0][0]\n maxval = (points[-1][0] - offset) // interval\n vals = defaultdict(list)\n for key, value in points:\n vals[(key - offset) // interval].append(value)\n return [vals[i] for i in xrange(maxval + 1)]\n\n", "From your code, I'm assuming my prior comment is correct. The problem here appears to be that the performance is O(n^2) - you repeat the list comprehension (which iterates all items) multiple times.\nI say, use a simple for loop. If the current item belongs in the same group as the previous one, add it to the existing inner list [[\"a\"], [\"b\"]] -> [[\"a\"], [\"b\", \"c\"]]. If it doesn't, add it to a new inner list, perhaps adding empty padding lists first.\n", "Expanding on Am's answer, use a defaultdict, and floor-divide the key by the interval to break them up correctly.\nfrom collections import defaultdict\ndef split_series(points, interval):\n vals = defaultdict(list)\n for key, value in points:\n vals[(key-1)//interval].append(value)\n return vals.values()\n\n", "Here's a lazy approach that uses the step behavior of xrange:\ndef split_series(points, interval):\n end_of_chunk = interval\n chunk = []\n for marker, item in points:\n if marker > end_of_chunk:\n for end_of_chunk in xrange(end_of_chunk, marker, interval):\n yield chunk\n chunk = []\n end_of_chunk += interval\n chunk.append(item)\n yield chunk\n\n", "How about using iterators for lazy evaluation?\nThis should be the equivalent of your initial solution:\nfrom itertools import groupby\n\ndef split_series(points, interval):\n \"\"\"\n >>> points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]\n >>> print list(split_series(points, 3))\n [['a', 'b', 'a', 'd'], ['c']]\n \"\"\"\n\n def interval_key(t):\n return (t[0] - points[0][0]) // interval\n\n groups = groupby(points, interval_key)\n\n for group in groups:\n yield [v for _, v in group[1]]\n\n" ]
[ 2, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "algorithm", "python", "series" ]
stackoverflow_0001549412_algorithm_python_series.txt
Q: How do you make a shared network file read-only using Python? Using Python, what's the correct way to set a file to be read-only when the file is located on a network share (being served from a Windows 2003 Server)? I'm running Python 2.6.2 in OS X (10.6.1). The following code throws an exception (as expected) when path is local, but os.chmod appears to have no effect when path points to a Windows share. import os, stat path = '/Volumes/Temp/test.txt' # Create a test file. open(path, 'w').close() # Make the file read-only. os.chmod(path, stat.S_IREAD) # Try writing to it again. This should fail. open(path, 'w').close() A: I am pretty sure you must have the proper settings on your local SAMBA server (/etc/samba/smb.conf) to make this behave the way you intend. There is many ways to go around permission checking if smb.conf isn't set correctly.
How do you make a shared network file read-only using Python?
Using Python, what's the correct way to set a file to be read-only when the file is located on a network share (being served from a Windows 2003 Server)? I'm running Python 2.6.2 in OS X (10.6.1). The following code throws an exception (as expected) when path is local, but os.chmod appears to have no effect when path points to a Windows share. import os, stat path = '/Volumes/Temp/test.txt' # Create a test file. open(path, 'w').close() # Make the file read-only. os.chmod(path, stat.S_IREAD) # Try writing to it again. This should fail. open(path, 'w').close()
[ "I am pretty sure you must have the proper settings on your local SAMBA server (/etc/samba/smb.conf) to make this behave the way you intend. There is many ways to go around permission checking if smb.conf isn't set correctly.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0001561482_python.txt
Q: Is it possible to use django Piston on Google AppEngine? I haven't been able to do so due to all sort of missing dependencies (mainly, I think the problem is in the authentication code which relies on django stuff that is not available on AppEngine) I was wondering if anyone patched\forked piston to get it working on AppEngine? A: http://bitbucket.org/gumptioncom/django-piston-app-engine/ A: It turns out the problem with Piston and AppEngine is mainly when it comes to the authentication code. So, I managed to port Piston to AppEngine doing the following: I'm using the app-engine-patch project which integrates django's authentication framework with Google AppEngine I forked Piston and removed all the OAuth authentication code and models (in authentication.py). Its probably not too complicated to convert the model and auth code but as I don't need it I didn't bother... A: I've forked django-oauth, to make it compatible with app-engine-patch. So it could eventually be used with django-piston-app-engine. http://bitbucket.org/mtourne/django-oauth-appengine/
Is it possible to use django Piston on Google AppEngine?
I haven't been able to do so due to all sort of missing dependencies (mainly, I think the problem is in the authentication code which relies on django stuff that is not available on AppEngine) I was wondering if anyone patched\forked piston to get it working on AppEngine?
[ "http://bitbucket.org/gumptioncom/django-piston-app-engine/\n", "It turns out the problem with Piston and AppEngine is mainly when it comes to the authentication code.\nSo, I managed to port Piston to AppEngine doing the following:\n\nI'm using the app-engine-patch project which integrates django's authentication framework with Google AppEngine\nI forked Piston and removed all the OAuth authentication code and models (in authentication.py). Its probably not too complicated to convert the model and auth code but as I don't need it I didn't bother...\n\n", "I've forked django-oauth, to make it compatible with app-engine-patch. So it could eventually be used with django-piston-app-engine.\nhttp://bitbucket.org/mtourne/django-oauth-appengine/\n" ]
[ 5, 2, 1 ]
[]
[]
[ "django", "django_piston", "google_app_engine", "python" ]
stackoverflow_0001453909_django_django_piston_google_app_engine_python.txt
Q: View Windows file metadata in Python I am writing a script to email the owner of a file when a separate process has finished. I have tried: import os FileInfo = os.stat("test.txt") print (FileInfo.st_uid) The output of this is the owner ID number. What I need is the Windows user name. A: Once I stopped searching for file meta data and started looking for file security I found exactly what I was looking for. import tempfile import win32api import win32con import win32security f = tempfile.NamedTemporaryFile () FILENAME = f.name try: sd = win32security.GetFileSecurity (FILENAME,win32security.OWNER_SECURITY_INFORMATION) owner_sid = sd.GetSecurityDescriptorOwner () name, domain, type = win32security.LookupAccountSid (None, owner_sid) print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible) print "File owned by %s\\%s" % (domain, name) finally: f.close () Mercilessly ganked from http://timgolden.me.uk/python-on-windows/programming-areas/security/ownership.html A: I think the only chance you have is to use the pywin32 extensions and ask windows yourself. Basically you look on msdn how to do it in c++ and use the according pywin32 functions. from win32security import GetSecurityInfo, LookupAccountSid from win32security import OWNER_SECURITY_INFORMATION, SE_FILE_OBJECT from win32file import CreateFile from win32file import GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL fh = CreateFile( __file__, GENERIC_READ, FILE_SHARE_READ, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None ) info = GetSecurityInfo( fh, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION ) name, domain, type_id = LookupAccountSid( None, info.GetSecurityDescriptorOwner() ) print name, domain, type_id
View Windows file metadata in Python
I am writing a script to email the owner of a file when a separate process has finished. I have tried: import os FileInfo = os.stat("test.txt") print (FileInfo.st_uid) The output of this is the owner ID number. What I need is the Windows user name.
[ "Once I stopped searching for file meta data and started looking for file security I found exactly what I was looking for.\nimport tempfile\nimport win32api\nimport win32con\nimport win32security\n\nf = tempfile.NamedTemporaryFile ()\nFILENAME = f.name\ntry:\n sd = win32security.GetFileSecurity (FILENAME,win32security.OWNER_SECURITY_INFORMATION)\n owner_sid = sd.GetSecurityDescriptorOwner ()\n name, domain, type = win32security.LookupAccountSid (None, owner_sid)\n\n print \"I am\", win32api.GetUserNameEx (win32con.NameSamCompatible)\n print \"File owned by %s\\\\%s\" % (domain, name)\nfinally:\n f.close ()\n\nMercilessly ganked from http://timgolden.me.uk/python-on-windows/programming-areas/security/ownership.html\n", "I think the only chance you have is to use the pywin32 extensions and ask windows yourself.\nBasically you look on msdn how to do it in c++ and use the according pywin32 functions. \nfrom win32security import GetSecurityInfo, LookupAccountSid\nfrom win32security import OWNER_SECURITY_INFORMATION, SE_FILE_OBJECT\n\nfrom win32file import CreateFile\nfrom win32file import GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL\n\nfh = CreateFile( __file__, GENERIC_READ, FILE_SHARE_READ, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None )\ninfo = GetSecurityInfo( fh, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION )\n\nname, domain, type_id = LookupAccountSid( None, info.GetSecurityDescriptorOwner() )\nprint name, domain, type_id\n\n" ]
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001561831_python.txt
Q: Using DPAPI with Python? Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python? I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow. EDIT: I've taken the example code pointed to by "dF" and tweaked it into a standalone library which can be simply used at a high level to crypt and decrypt using DPAPI in user mode. Simply call dpapi.cryptData(text_to_encrypt) which returns an encrypted string, or the reverse decryptData(encrypted_data_string), which returns the plain text. Here's the library: # DPAPI access library # This file uses code originally created by Crusher Joe: # http://article.gmane.org/gmane.comp.python.ctypes/420 # from ctypes import * from ctypes.wintypes import DWORD LocalFree = windll.kernel32.LocalFree memcpy = cdll.msvcrt.memcpy CryptProtectData = windll.crypt32.CryptProtectData CryptUnprotectData = windll.crypt32.CryptUnprotectData CRYPTPROTECT_UI_FORBIDDEN = 0x01 extraEntropy = "cl;ad13 \0al;323kjd #(adl;k$#ajsd" class DATA_BLOB(Structure): _fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))] def getData(blobOut): cbData = int(blobOut.cbData) pbData = blobOut.pbData buffer = c_buffer(cbData) memcpy(buffer, pbData, cbData) LocalFree(pbData); return buffer.raw def Win32CryptProtectData(plainText, entropy): bufferIn = c_buffer(plainText, len(plainText)) blobIn = DATA_BLOB(len(plainText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptProtectData(byref(blobIn), u"python_data", byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def Win32CryptUnprotectData(cipherText, entropy): bufferIn = c_buffer(cipherText, len(cipherText)) blobIn = DATA_BLOB(len(cipherText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptUnprotectData(byref(blobIn), None, byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def cryptData(text): return Win32CryptProtectData(text, extraEntropy) def decryptData(cipher_text): return Win32CryptUnprotectData(cipher_text, extraEntropy) A: I have been using CryptProtectData and CryptUnprotectData through ctypes, with the code from http://article.gmane.org/gmane.comp.python.ctypes/420 and it has been working well. A: Also, pywin32 implements CryptProtectData and CryptUnprotectData in the win32crypt module. A: The easiest way would be to use Iron Python.
Using DPAPI with Python?
Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python? I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow. EDIT: I've taken the example code pointed to by "dF" and tweaked it into a standalone library which can be simply used at a high level to crypt and decrypt using DPAPI in user mode. Simply call dpapi.cryptData(text_to_encrypt) which returns an encrypted string, or the reverse decryptData(encrypted_data_string), which returns the plain text. Here's the library: # DPAPI access library # This file uses code originally created by Crusher Joe: # http://article.gmane.org/gmane.comp.python.ctypes/420 # from ctypes import * from ctypes.wintypes import DWORD LocalFree = windll.kernel32.LocalFree memcpy = cdll.msvcrt.memcpy CryptProtectData = windll.crypt32.CryptProtectData CryptUnprotectData = windll.crypt32.CryptUnprotectData CRYPTPROTECT_UI_FORBIDDEN = 0x01 extraEntropy = "cl;ad13 \0al;323kjd #(adl;k$#ajsd" class DATA_BLOB(Structure): _fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))] def getData(blobOut): cbData = int(blobOut.cbData) pbData = blobOut.pbData buffer = c_buffer(cbData) memcpy(buffer, pbData, cbData) LocalFree(pbData); return buffer.raw def Win32CryptProtectData(plainText, entropy): bufferIn = c_buffer(plainText, len(plainText)) blobIn = DATA_BLOB(len(plainText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptProtectData(byref(blobIn), u"python_data", byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def Win32CryptUnprotectData(cipherText, entropy): bufferIn = c_buffer(cipherText, len(cipherText)) blobIn = DATA_BLOB(len(cipherText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptUnprotectData(byref(blobIn), None, byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def cryptData(text): return Win32CryptProtectData(text, extraEntropy) def decryptData(cipher_text): return Win32CryptUnprotectData(cipher_text, extraEntropy)
[ "I have been using CryptProtectData and CryptUnprotectData through ctypes, with the code from\nhttp://article.gmane.org/gmane.comp.python.ctypes/420\nand it has been working well.\n", "Also, pywin32 implements CryptProtectData and CryptUnprotectData in the win32crypt module.\n", "The easiest way would be to use Iron Python.\n" ]
[ 10, 6, 2 ]
[]
[]
[ "dpapi", "encryption", "python", "security", "windows" ]
stackoverflow_0000463832_dpapi_encryption_python_security_windows.txt
Q: handling db connection on daemonize threads I have a problem handling database connections in a daemon I've been working on, I first connect to my postgres database with: try: psycopg2.apilevel = '2.0' psycopg2.threadsafety = 3 cnx = psycopg2.connect( "host='192.168.10.36' dbname='db' user='vas' password='vas'") except Exception, e: print "Unable to connect to DB. Error [%s]" % ( e,) exit( ) after that I select all rows in the DB that are with status = 0: try: cursor = cnx.cursor( cursor_factory = psycopg2.extras.DictCursor) cursor.execute( "SELECT * FROM table WHERE status = 0") rows = cursor.fetchall( ) cursor.close( ) except Exception, e: print "Error on sql query [%s]" % ( e,) then if there are rows selected the program forks into: while 1: try: psycopg2.apilevel = '2.0' psycopg2.threadsafety = 3 cnx = psycopg2.connect( "host='192.168.10.36' dbname='sms' user='vas' password='vas'") except Exception, e: print "Unable to connect to DB. Error [%s]" % ( e,) exit( ) if rows: daemonize( ) for i in rows: try: global q, l q = Queue.Queue( max_threads) for i in rows: cursor = cnx.cursor( cursor_factory = psycopg2.extras.DictCursor) t = threading.Thread( target=sender, args=(i, cursor)) t.setDaemon( True) t.start( ) for i in rows: q.put( i) q.join( ) except Exception, e: print "Se ha producido el siguente error [%s]" % ( e,) exit( ) else: print "No rows where selected\n" time.sleep( 5) My daemonize function looks like this: def daemonize( ): try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) os.chdir("/") os.umask(0) try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) threads target to sender function: def sender( row, db): while 1: item = q.get( ) if send_to( row['to'], row['text']): db.execute( "UPDATE table SET status = 1 WHERE id = %d" % sms['id']) else: print "UPDATE table SET status = 2 WHERE id = %d" % sms['id'] db.execute( "UPDATE table SET status = 2 WHERE id = %d" % sms['id']) db.close( ) q.task_done( ) send_to function just opens a url and return true or false on success Since yesterday i keep getting these error and cant find my way thru: UPDATE outbox SET status = 2 WHERE id = 36 Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/lib/python2.6/threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File "sender.py", line 30, in sender db.execute( "UPDATE table SET status = 2 WHERE id = %d" % sms['id']) File "/usr/lib/python2.6/dist-packages/psycopg2/extras.py", line 88, in execute return _cursor.execute(self, query, vars, async) OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. A: Database handles don't survive across fork(). You'll need to open a new database handle in each subprocess, ie after you call daemonize() call psycopg2.connect. I've not used postgres but I know this to be definitely true for MySQL.
handling db connection on daemonize threads
I have a problem handling database connections in a daemon I've been working on, I first connect to my postgres database with: try: psycopg2.apilevel = '2.0' psycopg2.threadsafety = 3 cnx = psycopg2.connect( "host='192.168.10.36' dbname='db' user='vas' password='vas'") except Exception, e: print "Unable to connect to DB. Error [%s]" % ( e,) exit( ) after that I select all rows in the DB that are with status = 0: try: cursor = cnx.cursor( cursor_factory = psycopg2.extras.DictCursor) cursor.execute( "SELECT * FROM table WHERE status = 0") rows = cursor.fetchall( ) cursor.close( ) except Exception, e: print "Error on sql query [%s]" % ( e,) then if there are rows selected the program forks into: while 1: try: psycopg2.apilevel = '2.0' psycopg2.threadsafety = 3 cnx = psycopg2.connect( "host='192.168.10.36' dbname='sms' user='vas' password='vas'") except Exception, e: print "Unable to connect to DB. Error [%s]" % ( e,) exit( ) if rows: daemonize( ) for i in rows: try: global q, l q = Queue.Queue( max_threads) for i in rows: cursor = cnx.cursor( cursor_factory = psycopg2.extras.DictCursor) t = threading.Thread( target=sender, args=(i, cursor)) t.setDaemon( True) t.start( ) for i in rows: q.put( i) q.join( ) except Exception, e: print "Se ha producido el siguente error [%s]" % ( e,) exit( ) else: print "No rows where selected\n" time.sleep( 5) My daemonize function looks like this: def daemonize( ): try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) os.chdir("/") os.umask(0) try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) threads target to sender function: def sender( row, db): while 1: item = q.get( ) if send_to( row['to'], row['text']): db.execute( "UPDATE table SET status = 1 WHERE id = %d" % sms['id']) else: print "UPDATE table SET status = 2 WHERE id = %d" % sms['id'] db.execute( "UPDATE table SET status = 2 WHERE id = %d" % sms['id']) db.close( ) q.task_done( ) send_to function just opens a url and return true or false on success Since yesterday i keep getting these error and cant find my way thru: UPDATE outbox SET status = 2 WHERE id = 36 Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/lib/python2.6/threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File "sender.py", line 30, in sender db.execute( "UPDATE table SET status = 2 WHERE id = %d" % sms['id']) File "/usr/lib/python2.6/dist-packages/psycopg2/extras.py", line 88, in execute return _cursor.execute(self, query, vars, async) OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.
[ "Database handles don't survive across fork(). You'll need to open a new database handle in each subprocess, ie after you call daemonize() call psycopg2.connect.\nI've not used postgres but I know this to be definitely true for MySQL.\n" ]
[ 1 ]
[]
[]
[ "daemons", "multithreading", "psycopg2", "python" ]
stackoverflow_0001561427_daemons_multithreading_psycopg2_python.txt